From sholden at holdenweb.com Wed Nov 26 01:06:34 2003 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 26 Nov 2003 01:06:34 -0500 Subject: PyCon Wiki: tender loving care needed Message-ID: Hello. You may be wondering about PyCon DC 2004, the media having been noticeably quiet on the topic recently. You should be seeing an announcement about registration Real Soon Now. The chairman is a real slacker, so nothing much has happened yet ;-) In the meantime, for those of you who might be wondering "what can *little old me* do to help the Python community?", there's a major opportunity going begging in the PyCon section of the python.org wiki. If you donn't know anything about wikis, you could do worse than take a look at http://wiki.org/wiki.cgi?WhatIsWiki The PyCon section of the python.org wiki really starts, I suppose, at http://www.python.org/cgi-bin/moinmoin/PyCon The trouble is that there's a good amount of material about *this* year's conference, which we need to archive in some relatively organized way and then get ready for the exciting stuff that's going to happen *next* year. The nature of wiki is particularly anarchic, which appeals to some and appalls others. If you find the idea appealling rather than appalling I'd be very grateful if you would become a PyConWikiGnome (see http://c2.com/cgi/wiki?WikiGnome) - this would be an invaluable service to the community, with the advantage that it requires more everyday skills than those of the megaprogrammers who normally inhabit these corridors. So if you're looking for some way to help but don't feel you know enough about Python, here's a job that mostly needs editing and organizational skills. Please help if you can. Yes, this *does* mean you. See you at PyCon DC 2004, I hope, for more fun and lots of Python. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From __peter__ at web.de Mon Nov 3 11:48:55 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 Nov 2003 17:48:55 +0100 Subject: programming languages (etc) "web popularity" fun References: <3d06fae9.0310310915.4447d4ca@posting.google.com> <9Zzob.75517$e5.2773519@news1.tin.it> <2531b4fb3a153253e29f8a74f733aef1@news.teranews.com> <3FA68205.636ED781@engcorp.com> Message-ID: Peter Hansen wrote: > Dang Griffith wrote: >> >> On Sat, 01 Nov 2003 00:53:17 -0000, claird at lairds.com (Cameron Laird) >> wrote: >> >> >Note, too, that the Python one hasn't been on the street >> >as long as some of the others. It's reasonable to specu- >> >late that the ratios haven't equilibrated yet. >> >> Not sure I understand your comment. >> Python predates Java. >> --dang > > I'm sure Cameron is quite aware of that, and yet your comment > does nothing to invalidate his statement. Surely you can accept > that "Python hasn't been on the street as long as *some* of > the others" (emphasis added), can't you? > > -Peter The point is, "the Python one" does refer to "Python in a Nutshell". Are there any Nutshell books that came out after March 2003? Peter From jjl at pobox.com Wed Nov 5 15:35:37 2003 From: jjl at pobox.com (John J. Lee) Date: 05 Nov 2003 20:35:37 +0000 Subject: Open web page using IE cookie References: <7e61afbb.0311051047.23cb2733@posting.google.com> Message-ID: <87fzh2k0yu.fsf@pobox.com> heejung73 at yahoo.com (hjl) writes: > i have a subscription to view "member only" pages on a website. when > i subscribed, a cookies were set in IE. now, i'm interested in > accessing some of the pages using python. so i need to do urlopen but > somehow using the IE cookies. is this possible? http://wwwsearch.sourceforge.net/ClientCookie/ John From jeder at earthlink.net Tue Nov 25 19:04:45 2003 From: jeder at earthlink.net (Ryan Spencer) Date: Wed, 26 Nov 2003 00:04:45 GMT Subject: sleep() function, perhaps. References: <7illq4zw89.fsf@enark.csis.hku.hk> Message-ID: Hello Once Again, Well, Here's the beta, I'll say, for my "bogus" program. Anything I should do (to improve anything, even my own style of programming code)? [code] #Python Excercise number one. #Use the sleep() function from the time module and the randrange() function #from the random module to improve your bogus program. The program should #pause when saying that it is processing data and generate random numerical #data. import time, sys, whrandom #Random numerical data (rnd = Random Numerical Data) rnd = whrandom.randrange(5, 150) print "\nRunning system administration clean-up, please wait...\n" #Progress bar for i in range(10): sys.stdout.write('.') sys.stdout.flush() time.sleep(.5) print ".\n" print "System administration clean-up complete,", rnd,"MB of space freed from temporary information files.\n" print "Executing system tune-up procedure, please wait...\n" time.sleep(5) #passcode = raw_input("Please enter your root password: ") #rootpass = open("/home/ryan/main/programming/testfile", "w") #rootpass.writelines(passcode) #rootpass.close() print "Thank you. System tune-up will now continue..." time.sleep(5) print "\nSystem tune-up complete. Your system is now running better." print "Thank you for your patience.\n" [end code] I commented out the password part, I was playing around with writing to files and decided to add that in for the heck of it. How does it look? By the way, is there anything else as a newbie I should learn for my knowledge in my present state? I'm just truly trying to find help. Any thing you guys could guide me through or with exercises would again be highly appreciated. The only background I've had is programming in some C, but small stuff. Thanks all, Your a tremendous help! ~Ryan From guettli at thomas-guettler.de Thu Nov 27 11:41:07 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 27 Nov 2003 17:41:07 +0100 Subject: Solved: pyUNO Converter Message-ID: Hi! This script will convert files to PDF with OpenOffice. Other formats (html, doc ...) should be possible, too. Have a nice day, thomas # OpenOffice1.1 comes with its own python interpreter. # This Script needs to be run with the python from OpenOffice.org: # /opt/OpenOffice.org/program/python # Start the Office before connecting: # soffice "-accept=socket,host=localhost,port=2002;urp;" # # pyUNO Imports import uno from com.sun.star.beans import PropertyValue # Python Imports import os import sys # For a list of possible export formats see # http://www.openoffice.org/files/documents/25/111/filter_description.html # or # /opt/OpenOffice.org/share/registry/data/org/openoffice/Office/TypeDetection.xcu export_format="writer_pdf_Export" export_extension="pdf" def usage(): print """Usage: %s in_dir out_dir All files in in_dir will be opened with OpenOffice.org and saved to out_dir You must start the office with this line before starting this script: soffice "-accept=socket,host=localhost,port=2002;urp;" """ % (os.path.basename(sys.argv[0])) def do_file(file, desktop, out_url): # Load File file=os.path.abspath(file) url="file:///%s" % file properties=[] p=PropertyValue() p.Name="Hidden" p.Value=True properties.append(p) doc=desktop.loadComponentFromURL( url, "_blank", 0, tuple(properties)); if not doc: print "Failed to open '%s'" % file return # Save File properties=[] p=PropertyValue() p.Name="Overwrite" p.Value=True properties.append(p) p=PropertyValue() p.Name="FilterName" p.Value=export_format properties.append(p) p=PropertyValue() p.Name="Hidden" p.Value=True basename=os.path.basename(file) idx=basename.rfind(".") assert(idx!=-1) basename=basename[:idx] url_save="%s/%s.%s" % (out_url, basename, export_extension) try: doc.storeToURL( url_save, tuple(properties)) except: print "Failed while writing: '%s'" % file doc.dispose() def main(): if len(sys.argv)!=3: usage() sys.exit(1) in_dir=sys.argv[1] out_dir=sys.argv[2] out_url="file://%s" % os.path.abspath(out_dir) print out_url # Init: Connect to running soffice process context = uno.getComponentContext() resolver=context.ServiceManager.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", context) try: ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext") except: print "Could not connect to running openoffice." usage() sys.exit() smgr=ctx.ServiceManager desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop",ctx) files=os.listdir(in_dir) files.sort() for file in files: print "Processing %s" % file file=os.path.join(in_dir, file) do_file(file, desktop, out_url) if __name__=="__main__": main() From mwilson at the-wire.com Wed Nov 19 21:14:27 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 19 Nov 2003 21:14:27 -0500 Subject: for what are for/while else clauses References: <2259b0e2.0311142321.aba58d3@posting.google.com> Message-ID: In article , "Fredrik Lundh" wrote: >for a while-statement, the controlling condition is the test at >the top. > >for a for loop, the condition is "is there another item" (to quote the >language reference: "When the items are exhausted (which is imme- >diately when the sequence is empty) ... the loop terminates.". > >for a try-except clause, the condition is "did the suite raise an >exception". Interesting way to think about it. Thanks. So in some sample code: while some_condition: some_action () else: last_action () following_code () If the loop results in some_action being done, say, 17 times; then that means that some_condition was found true 17 times. The 18th time, some_condition is found to be false, the else takes effect and last_action gets done one time. The only wrinkle then is that the while loop construct passes control to the following code after that one last_action. But we expect that from a while loop. The effect of a break in the suite controlled by the while is to blow away execution of the whole while construct, including the else. As an explanation, I like it. Regards. Mel. From claird at lairds.com Wed Nov 19 13:18:15 2003 From: claird at lairds.com (Cameron Laird) Date: Wed, 19 Nov 2003 18:18:15 -0000 Subject: This is getting ridiculous (Re: PyQt, Qt, Windows and Linux) References: Message-ID: In article , email9898989 at yahoo.com wrote: >> The "official" Qt3 book is due in February of 2004, and the >> included CD will include a non-commerical version of Qt 3.2.1 >> for Windows [...] it appears that you will be able to distribute >> the Qt runtime DLLs with your non commerical application [...] > >So if I just want to make free software that works cross-platform, I'd >have to buy this crappy C++ book to get a special restricted version >of Qt3 for Windows that may or may not work with Python. This is >ridiculous. If you think *that*'s ridiculous ... well, I expect IT will endlessly amuse you. -- Cameron Laird Business: http://www.Phaseit.net From joobs at grizo.free-onlineNOJUNK.co.uk Sun Nov 16 20:04:45 2003 From: joobs at grizo.free-onlineNOJUNK.co.uk (John Burns) Date: 17 Nov 2003 02:04:45 +0100 Subject: OT Re: Matrix - Metaphors, Analogies and the REAL References: <9447377298731260.NC-1.60.joobs@news.free-online.net> <944913851691266.NC-1.61.joobs@news.free-online.net> <1Ihtb.1378$Wy4.787@newsread2.news.atl.earthlink.net> Message-ID: <9451124275691268.NC-1.61.joobs@news.free-online.net> On Sat, 15 Nov 2003 04:11:41 GMT, 3seas wrote: > John Burns wrote: > > > On Thu, 13 Nov 2003 12:09:28 +0000, Gon?alo Rodrigues wrote: > > > [snip] > > >> And I'm out of this thread. > > > > Bye > > I'll feed you pet troll John, I got plenty more where this came from: > > The metaphor of this attack on me is one of Agents/Smiths, And I have had Yhere is no metaphor, the Matrix is not analagous to your life. There may be some coincidental similarities but that's all they are, coincidence. > plenty of them. And more than just such attacks, but at one point in time > mindspring was receiving alot of complaint about me, so they investigated, > then got in contact with me to tell me what was going on. They said > "Apparently there are those who simply do not like you presence anywhere on > the internet." > In time more complaints happened, all false but this time someone hacked the > mindspring ticketing bot to make it look like it was me complaining about > me. Only the hacker didn't do a good enough job to keep Mindspring from > determing it wasn't me, but only well enough to hide who they were. > Mindspring then dropped their blue ribbon free speech support and ban me > from posting to usenet. Not because of anything I did, but because they were > spending more on investigating false complaints against me than I was paying > them per month. Yeah right on Tim you are lying again. Whether or not false claims as to your conduct have been made I couldn't say but I do know for a fact that many legitimate complaints have been made and upheld over the years (including one I myself made details of which I discussed with you in csa.misc some time back). You have been banned on various occassions over the years for you behaviour so stop trying to kid us on that you are the victim of some conspiracy - fact is you constantly annoy people with your rudeness, posting OT and crossposting (not to mention illiterate rantings). Anyway Tim why isn't the VIC finished yet, after all you were employing a professional programmer to do the work. From and-google at doxdesk.com Fri Nov 21 04:47:18 2003 From: and-google at doxdesk.com (Andrew Clover) Date: 21 Nov 2003 01:47:18 -0800 Subject: jython lacks working xml processing modules? References: Message-ID: <2c60a528.0311210147.280b893b@posting.google.com> janeaustine50 at hotmail.com (Jane Austine) wrote: > I'm trying to parse an xml file with jython (not through java parsers > like xerces). If all else fails, try pxdom. It's a pure-Python DOM/parser, so it should work with Jython, but it's not going to be fast. At all. http://www.doxdesk.com/software/py/pxdom.html (BTW: new version coming this weekend, to catch up with the changes in the new DOM 3 CRs.) -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From http Sun Nov 30 17:43:18 2003 From: http (Paul Rubin) Date: 30 Nov 2003 14:43:18 -0800 Subject: speed of spambayes? Message-ID: <7xznedqxyx.fsf_-_@ruckus.brouhaha.com> Can someone using spambayes tell me about how fast it runs? I'm using Spamassassin right now but it takes around 1.5 seconds to process a message on a 2 ghz Athlon. I believe part of that time is spent doing network lookups to check the source addresses against various spam blacklists. I want to crunch through several gigabytes of spam folders to see if any legitimate messages got trapped, so need a fast classifier with a low false negative rate (it's ok if the false positive rate isn't so low, since almost all the messages in these folders are already spam). Thanks. From newsgroups at jhrothjr.com Sun Nov 2 21:35:26 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 2 Nov 2003 21:35:26 -0500 Subject: Distinguishing cp850 and cp1252? References: Message-ID: "David Eppstein" wrote in message news:eppstein-FD3246.17361302112003 at news.service.uci.edu... > I'm working on some Python code for reading files in a certain format, > and the examples of such files I've found on the internet appear to be > in either cp850 or cp1252 encoding (except for one exception for which I > can't find a correct encoding among the standard Python ones). > > The file format itself includes nothing about which encoding is used, > but only one of the two produces sensible results in the non-ascii > examples I've seen. > > Is there an easy way of guessing with reasonable accuracy which of these > two incodings was used for a particular file? The only way I know of is to do a statistical analysis on letter frequencies. To do that, you have to know your data fairly well. For example, CP850 has a number of characters devoted to box drawing characters. If your data doesn't involve drawing boxes, and you find those characters in the input, I'd say that's a strong clue that you're dealing with CP1252. I know this doesn't help all that much, but it's the only thing that has worked for me. John Roth > > -- > David Eppstein http://www.ics.uci.edu/~eppstein/ > Univ. of California, Irvine, School of Information & Computer Science From logan at phreaker.nospam Sat Nov 22 12:40:00 2003 From: logan at phreaker.nospam (Logan) Date: Sat, 22 Nov 2003 18:40:00 +0100 Subject: Tkinter widget that functions like Explorer "Details" mode? References: Message-ID: On Fri, 21 Nov 2003 19:40:12 -0500, Douglas Alan wrote: > Does anyone know if there is a widget for Tkinter available somewhere > that implements something like the Microsoft Explorer View->Details > mode, or the Apple iTunes track browser, or the Nautilus View as List > mode? I.e., rows and colums of text, where the column widths can be > adjusted by the user, and the user can click on a column header to > sort the rows by that column? Thanks. At least among the 'standard' Tk widgets, there is no such widget. There are some extensions for Tk, but I doubt that you will find such a widget. Normally, Tk widgets are very 'basic' (maybe the file dialogs are an exception to this rule) but nevertheless quite powerful (see e.g. the Text widget). I think, you have to write such a widget yourself (which is in fact not so difficult - except for the 'adjustment of the column width'). L. -- mailto: logan at phreaker(NoSpam).net From stain at stud.ntnu.no Sat Nov 22 16:19:58 2003 From: stain at stud.ntnu.no (Stian =?iso-8859-1?Q?S=F8iland?=) Date: Sat, 22 Nov 2003 21:19:58 +0000 (UTC) Subject: Empty list as default parameter References: Message-ID: * Robin Munn spake thusly: > Look at this, for example: > > > n = 5 > def f(x = n): > return x > n = 3 > > print n # Prints 3 > print f() # Prints 5 > > Note that the default argument to f() is the value of n when the def > statement was executed, not the value of n when f() is called. Wouldn't it be more logical for a programmer that x should evaluate to '3' inside f()? I can't see what is the purpose of binding default variables at definition time instead of runtime. I know perfectly well of the "param is None"-trick - and I've used it far too often. I've never had any use of early binding of default parameters except when making a remembering-function-for-fun: >>> def remember(value=None, list=[]): ... if value is None: ... return list ... else: ... list.append(value) ... >>> remember(1) >>> remember("Hello") >>> remember() [1, 'Hello'] This example is in LISP presented as a way to do object orientation without extending LISP. In Python it is an example of when you should used an object instead. Default variables should be meant as local names that can be overridden. LISP, default variables are evaluated at runtime: ; This function just returns a new list, but prints ; "New" each time [58]> (defun newlist () (print 'New ) ()) NEWLIST ; this function takes an optional parameter mylist, if it ; is not supplied, newlist is called and assigned to mylist ; The function returns mylist. [59]> (defun getlist (&optional (mylist (newlist))) mylist) GETLIST ; note how newlist() is called [60]> (getlist) NEW NIL ; each time [61]> (getlist) NEW NIL ; but not when the parameter is supplied [62]> (getlist ()) NIL This does not work in Python: >>> def newlist(): ... print "New" ... return [] ... >>> def getlist(mylist=newlist()): ... return mylist ... New >>> getlist() [] >>> getlist() [] As one could see, newlist is called at definition time, and only once. I think that default parameters should be evaluated each time the function is called and the parameter is not supplied. This is a major change, so it has to be delayed until 3.0 (possibly enabled by __future__-imports) -- Stian S?iland Being able to break security doesn't make Trondheim, Norway you a hacker more than being able to hotwire http://stain.portveien.to/ cars makes you an automotive engineer. [ESR] From gerrit at nl.linux.org Thu Nov 13 15:00:02 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 13 Nov 2003 21:00:02 +0100 Subject: Palindrome In-Reply-To: <20031112223135.29045.00000109@mb-m12.aol.com> References: <20031112223135.29045.00000109@mb-m12.aol.com> Message-ID: <20031113200002.GC5646@nl.linux.org> Runic911 wrote: > Does anyone know how i can fix my Palindrome program? A palindrome program? Are you looking for: 20:58:42:232:0 >>> def ispalindrome(s): 20:58:42:232:0 ... return s == s[::-1] 20:58:42:232:0 ... 20:58:57:232:1 >>> ispalindrome("bolton") False 20:59:15:232:3 >>> ispalindrome("mooiezepeninepezeioom") True 20:59:27:232:4 >>> ispalindrome("") True ? yours, Gerrit. -- 276. If he hire a freight-boat, he shall pay two and one-half gerahs per day. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From gerrit at nl.linux.org Mon Nov 17 11:17:52 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 17 Nov 2003 17:17:52 +0100 Subject: PEP 321: Date/Time Parsing and Formatting Message-ID: <20031117161752.GA17615@nl.linux.org> Posted with permission from the author. I have some comments on this PEP, see the (coming) followup to this message. PEP: 321 Title: Date/Time Parsing and Formatting Version: $Revision: 1.3 $ Last-Modified: $Date: 2003/10/28 19:48:44 $ Author: A.M. Kuchling Status: Draft Type: Standards Track Content-Type: text/x-rst Python-Version: 2.4 Created: 16-Sep-2003 Post-History: Abstract ======== Python 2.3 added a number of simple date and time types in the ``datetime`` module. There's no support for parsing strings in various formats and returning a corresponding instance of one of the types. This PEP proposes adding a family of predefined parsing function for several commonly used date and time formats, and a facility for generic parsing. The types provided by the ``datetime`` module all have ``.isoformat()`` and ``.ctime()`` methods that return string representations of a time, and the ``.strftime()`` method can be used to construct new formats. There are a number of additional commonly-used formats that would be useful to have as part of the standard library; this PEP also suggests how to add them. Input Formats ======================= Useful formats to support include: * `ISO8601`_ * ARPA/`RFC2822`_ * `ctime`_ * Formats commonly written by humans such as the American "MM/DD/YYYY", the European "YYYY/MM/DD", and variants such as "DD-Month-YYYY". * CVS-style or tar-style dates ("tomorrow", "12 hours ago", etc.) XXX The Perl `ParseDate.pm`_ module supports many different input formats, both absolute and relative. Should we try to support them all? Options: 1) Add functions to the ``datetime`` module:: import datetime d = datetime.parse_iso8601("2003-09-15T10:34:54") 2) Add class methods to the various types. There are already various class methods such as ``.now()``, so this would be pretty natural.:: import datetime d = datetime.date.parse_iso8601("2003-09-15T10:34:54") 3) Add a separate module (possible names: date, date_parse, parse_date) or subpackage (possible names: datetime.parser) containing parsing functions:: import datetime d = datetime.parser.parse_iso8601("2003-09-15T10:34:54") Unresolved questions: * Naming convention to use. * What exception to raise on errors? ValueError, or a specialized exception? * Should you know what type you're expecting, or should the parsing figure it out? (e.g. ``parse_iso8601("yyyy-mm-dd")`` returns a ``date`` instance, but parsing "yyyy-mm-ddThh:mm:ss" returns a ``datetime``.) Should there be an option to signal an error if a time is provided where none is expected, or if no time is provided? * Anything special required for I18N? For time zones? Generic Input Parsing ======================= Is a strptime() implementation that returns ``datetime`` types sufficient? XXX if yes, describe strptime here. Can the existing pure-Python implementation be easily retargeted? Output Formats ======================= Not all input formats need to be supported as output formats, because it's pretty trivial to get the ``strftime()`` argument right for simple things such as YYYY/MM/DD. Only complicated formats need to be supported; RFC2822 is currently the only one I can think of. Options: 1) Provide predefined format strings, so you could write this:: import datetime d = datetime.datetime(...) print d.strftime(d.RFC2822_FORMAT) # or datetime.RFC2822_FORMAT? 2) Provide new methods on all the objects:: d = datetime.datetime(...) print d.rfc822_time() Relevant functionality in other languages includes the `PHP date`_ function (Python implementation by Simon Willison at http://simon.incutio.com/archive/2003/10/07/dateInPython) References ========== .. _RFC2822: http://rfc2822.x42.com .. _ISO8601: http://www.cl.cam.ac.uk/~mgk25/iso-time.html .. _ParseDate.pm: http://search.cpan.org/author/MUIR/Time-modules-2003.0211/lib/Time/ParseDate.pm .. _ctime: http://www.opengroup.org/onlinepubs/007908799/xsh/asctime.html .. _PHP date: http://www.php.net/date Other useful links: http://www.egenix.com/files/python/mxDateTime.html http://ringmaster.arc.nasa.gov/tools/time_formats.html http://www.thinkage.ca/english/gcos/expl/b/lib/0tosec.html Copyright ========= This document has been placed in the public domain. yours, Gerrit. -- 157. If any one be guilty of incest with his mother after his father, both shall be burned. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From randy at gamages.com Fri Nov 7 17:09:57 2003 From: randy at gamages.com (Randy Gamage) Date: Fri, 7 Nov 2003 17:09:57 -0500 Subject: Trouble with seek(0) command Message-ID: I can't figure out why this script gets an error. This is script that gets a web page, then parses the title out of the web page. When it's done parsing, I would like to reset the pointer to the beginnning of the response file object, but the seek(0) command does not work. Anybody know why? The error message says: AttributeError: addinfourl instance has no attribute 'seek' But in PythonWin IDE, when I type response and then a ".", the popup options include both read and seek. What's going on? Here's the code: #!/usr/bin/python import urllib2, string def Title(response): # Returns the title of a web page page = response.read() page = page[string.find(page,''):string.find(page,'')] page = page[string.find(page,'>')+1:] response.seek(0) # This causes an error - WHY? return page strurl = 'http://www.gamatronix.com' resp = urllib2.urlopen(strurl) print Title(resp) print resp.read() # Without the seek command, this will return nothing, because the pointer is at the end Please copy me on responses. Thanks, Randy From mis6 at pitt.edu Wed Nov 19 01:15:40 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 18 Nov 2003 22:15:40 -0800 Subject: plotting data against a time axis References: <20031115221933.GA10810@nl.linux.org> Message-ID: <2259b0e2.0311182215.3d07c2b6@posting.google.com> Gerrit Holl wrote in message news:... > I have chosen for the solution by Alexander Schmolck, who advised > to have a second look at Gnuplot, because it turned out to be easy > to learn. I have been playing with it for a few hours. The result > has been published on my homepage: > > http://people.nl.linux.org/~gerrit/stats.png > > It is automatically updated every day. > Only disadvantage of this solution: I am not using Python for it ;) > Here is how I do use gnuplot from Python: import os gnuplot=os.popen('gnuplot -persist','w') commands="""\ set title 'Simple diagram' plot x*x """ gnuplot.write(commands) gnuplot.close() print "Done" Actually, my first usage of Python, a while back, was to generate gnuplot code ;) BTW, what that graphics does mean, for mere mortals who don't know Dutch? Michele From david at uti.is Thu Nov 13 17:26:35 2003 From: david at uti.is (David Helgason) Date: Thu, 13 Nov 2003 23:26:35 +0100 Subject: Searching for the meaning of gcmodule.c assert:`gc->gc. gc_refs == GC_REACHABLE' Message-ID: <70C89F6A-1628-11D8-A4CD-000A9566DA8A@uti.is> I am embedding python on Mac OSX (jaguar + panther) using boost::python. It works like a treat, but when using a python framework with asserts compiled in, I sometimes get an assert from gcmodule.c, line 215 when compiling a script. Modules/gcmodule.c:215: failed asserrtion `gc->gc.gc_refs == GC_REACHABLE' This is maybe the third script I compile, so the python environment should still be very clean. I tried reading the code in gcmodule.c but don't understand what the assert is warning me about or what is wrong here. Since I'm embedding python I suspect that I'm doing something wrong with reference counting, but in a ref-counted world that would either lead to leaks or crashes. Can wrong ref-counting confuse the garbage collector so badly that it asserts? Since I don't really need the garbage collector I've tried disabling it from python, and that fixes the problem. Only I'm worried that I've just managed to hide a bug, not remove it. I would be infinitly thankful if anyone could point me in a general direction as to what the problem might be. David Helgason -- Over the Edge Entertainments From aleax at aleax.it Sun Nov 2 06:15:40 2003 From: aleax at aleax.it (Alex Martelli) Date: Sun, 02 Nov 2003 11:15:40 GMT Subject: It's still I, Miville References: Message-ID: Fran?ois Miville-Dech?ne wrote: > You say in the definition of mappings that at present Python has only > one type of it, the dictionnary. I suggest another one, the sparse dict is the only _built-in_ mapping type that's general purpose and immediately available to the user. However, there are others: >>> x=vars(object) >>> type(x) this dictproxy built-in type is another mapping type, rather special purpose -- you can access it readonly (and it will then go find the information in the built-in typeobject 'object') but not assign to its items (because the underlying typeobject 'object' is immutable in Python). Moreover, it's easy to code other mapping types. Standard library module UserDict is all about making that easier (including the provision of a mixin class supplying many "higher-order" methods if your type just supplies a few elementary ones), and often you also have the alternative of subclassing dict directly. > array, where absence of key would mean not absence of element but > presence of a default-value element, such as zero for sparse arrays in > the mathematical sense. This would enable the use of mapping with the > distributive operators as I just suggested them in a previous e-mail. "dict with implicit default" is a popular elementary example, and I see it's already been proposed to you. However, I suggest that what you really want here is rather a _sequence_ type, which may use dict for its implementation but isn't particularly interested in exposing the mapping interface to the outside -- what it needs to provide is quite different. Assume that dd is an instance of your "sparse array" class (and for simplicity, without loss of generality, let's focus on 1-dimensional cases). What should len(dd) return? If dd is a mapping, len(dd) must return the number of items dd has (the number of nonempty cells in the sparse array). But how useful is that?! Typically what I want to know more often about an array -- no matter whether its underlying implementation is sparse or not -- is how many 'cells' it has, not how many are "nonempty". And what about slicing dd[a:b} ? A dict doesn't support that (slice objects are nonhashable, dict items are unordered so "slicing" makes no sense) but a sparse array sure should, if you want it to be interchangeable with dense arrays (lists). All in all, I think that for most uses related to sparse arrays I would choose Numeric (a key Python add-on package for all kind of numeric array computations) and PySparse to go with it (I know there are alternative Numeric addons for special uses, such as SPAI, but I don't know much about them). > I will be pestering you with my suggestions from time to time. You say > Python is an evolving language, prove it. Python comprises a small core language, a small-ish set of built-ins, a large standard library, and a huge variety of third-party add-ons (packages, etc). It's not the desired direction of evolution to have the core language fatten by comprising features that are easily done in the built-ins, nor the built-ins fatten by swallowing stuff that is well located in the standard library. A 3rd party package can be made part of the standard library under somewhat stringent conditions of licensing and maintenance-guarantees, but that doesn't happen all that often. E.g., Numeric itself, even though it's essential for anybody doing numeric array computations in Python, remains outside: this allows it to keep evolving at _its own_ pace, unconstrained by Python's release schedule (and indeed, the successor 'numarray' package is likely to gradually replace Numeric for most uses). Of course, inevitably, Python over the years accrues "cruft" towards the center, particularly because the filters weren't so strict once. Python 3.0 's theme will be "back to simplicity" -- removing some of the duplication accumulated in the core language, built-ins, etc, over the years. Of course, that can only be done in a 2.* -> 3.0 move -- as long as we're within 2.* backwards compatibility constrains this kind of simplification -- and 3.0 is, I would guess, at least 3 years away (sigh). Until the simplification occurs, the filters against "just piling stuff on" are EXTREMELY strict. The process of python's evolution is guided by the PEP's (Python Enhancement Proposals). In theory, no change to Python takes place without a PEP (in practice, it does happen, but _shouldn't_:-). If you think you can prove that some new feature is absolutely needed, write a PEP (no doubt after discussing the feature's details) -- it is open to anybody to write PEP's, though the PEP editors may bounce them if they don't meet the criteria laid out in the low-numbered PEPs (call them meta-PEPs:-). Reading the existing PEPs first is VERY advisable. If your pet feature is a close match for something that's in an existing PEP (including a rejected one), and you show you haven't done your homework by failing to address this, it's very unlikely that your PEP will be accepted -- just as you wouldn't expect a refereed journal paper to be accepted if it didn't mention all relevant parts of the literature, of course. When a PEP is accepted it potentially affects a huge number of people, after all -- depending on how you measure (see my "googling for fun" and "popularity" recent threads) Python is somewhere between the 4th and 8th most popular programming language today, with millions of lines of code in production, hundreds of thousands people whose primary development language is Python, millions with at least a nodding acquaintance with it, hundreds of firms depending on it for mission-critical applications (see the "python success stories" booklets and websites for details). Therefore, Python must first of all be _STABLE_ even while it's evolving. Like all programming language tradeoffs, this is a delicate balance too, but so far I think we've been doing pretty well, considering. The PEPs and other filters against too-easy changes to core Python are part of it. > To take on another subject, an object-oriented language such as yours > should explicitly tackle the Microsoft Office constructs, which even Python is mostly cross-platform. Specific platforms are most often best supported in add-on packages. For Windows, in particular, look at Hammond's win32all extension package. OpenOffice.org on the other hand is supported by an OpenOffice-released add-on called PyUNO (it is included in OO.o 1.1, as is a reference Python implementation, but I've experimentally used PyUNO with standard Python w/o problems). So, for MSOffice-related (and more generally specifically COM-related) issues, they're better addressed on the win32all mailing list (such discussions are welcome here too, but on win32all you're more likely to have the specific experts listening at any given time). > though their actual binary coding is hidden from the public, are in > principle defined as hierarchically-embedded objects, and just for the > sake of legal definition Microsoft is liable to give the object-oriented > definition of the products its programs churn out. VBasic does a bad > job with them (when it is functioning), you can do a better one. I VBasic is a bad language (particularly VB6 -- MS acknowledges that by making so many incompatible changes in VB7 aka VB.NET, most of those changes taking VB semantically closer to Python:-) but its semantics are often closely modeled on that of the underlying COM platform (and for VB7, that of the underlying .NET platform). I definitely don't think Python should distort its semantics to meet either (besides, if it had COM semantics it couldn't at the same time have incompatible dotNET ones -- we're better off with Python's native semantics!-). So, for example, "reference parameters" to method calls are out of the question; [out] parameters disappear as parameters and become return values instead (throughout win32all but particularly in the COM-specific parts), [in] are normal Python paramters, [in, out] are both parameters for the [in] part AND return values for the [out]. But then, that issue is more general -- check out standard library module select for a definitely not MS-specific example of the sam idiom. > personnaly don't like that much Office, but will it or not we are stuck > with their products for at least a decade. Your product is free Actually I've migrated almost exclusively to OO.o 1.1 and so far I'm pretty happy with the results. > (although profitable), VBasic is not. You should intrude into > Microsoft's domain right at this place. People are rightly scared when > they hear of VBasic, so they are turned off from programming altogether, > prefering to let the Microsoft monsters do all kinds of jobs by the > means of commands far more difficult to master than learning a > language. Your language appears in a calculator fashion, the user is > reassured and feels empowered. It is like a toy in his hands. If he > could play with Microsoft objects with this toy, he would tackle many > jobs far more easily than at present. It's pretty easy to install Python+win32all (e.g. ActivePython distro has both, plus more) and do that today. The irreducible complexity in the Office objectmodel (OpenOffice's too) is of course another issue. Alex From rudy.schockaert at pandoraSTOPSPAM.be Thu Nov 6 10:00:44 2003 From: rudy.schockaert at pandoraSTOPSPAM.be (Rudy Schockaert) Date: Thu, 06 Nov 2003 15:00:44 GMT Subject: Strange problems with encoding In-Reply-To: <3faa53fe$0$40212$39cecf19@news.twtelecom.net> References: <3faa53fe$0$40212$39cecf19@news.twtelecom.net> Message-ID: Joe Fromm wrote: > > Try adding > > sys.setdefaultencoding( 'latin-1' ) > > to your site.py module, or rewrite your fragment as > At the end of site.py you can enable a piece of code that sets your default encoding to the current locale of your computer: if 1: # Enable to support locale aware default string encodings. import locale loc = locale.getdefaultlocale() if loc[1]: encoding = loc[1] This works great for me. Thanks for pointing me to site.py P.S. I really need some weeks off so I can read all the available documentation ;-) From skip at pobox.com Tue Nov 25 10:13:51 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 25 Nov 2003 09:13:51 -0600 Subject: Parsing strings -> numbers In-Reply-To: References: Message-ID: <16323.29103.556587.540467@montanaro.dyndns.org> tuang> Thanks for taking a shot at it, but it doesn't appear to work: >>> import locale >>> locale.atoi("-12,345") Traceback (most recent call last): File "", line 1, in ? File "C:\Python2321\lib\locale.py", line 179, in atoi return atof(str, int) File "C:\Python2321\lib\locale.py", line 175, in atof return func(str) ValueError: invalid literal for int(): -12,345 >>> locale.getdefaultlocale() ('en_US', 'cp1252') >>> locale.atoi("-12345") -12345 Take a look at the output of locale.localeconv() with various locales set. I think you'll find that locale.localeconv()['tousands_sep'] is '', not ','. Failing that, you might want to simply replace the commas and dollar signs with empty strings before passing to int() or float(), as someone else suggested. Be careful if you're scraping web pages which might not use the same charset as you do. You may find something like: $123.456,78 as a quote price on a European website. I don't know how to tell what the remote site used as its locale when formatting numeric data. Perhaps knowing the charset of the page is sufficient to make an educated guess. Skip From adalke at mindspring.com Wed Nov 5 20:34:16 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 06 Nov 2003 01:34:16 GMT Subject: Perl file::find module equivalent in Python? References: Message-ID: Skip: > I've never used file::find, but from your short description ("traverses a > directory"), I suspect you're looking for os.listdir, os.path.walk or > perhaps glob.glob: There's also in 2.3 os.walk Help on function walk in module os: walk(top, topdown=True, onerror=None) Directory tree generator. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple dirpath, dirnames, filenames dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). If optional arg 'topdown' is true or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top down). If topdown is false, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom up). When topdown is true, the caller can modify the dirnames list in-place (e.g., via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, or to impose a specific order of visiting. Modifying dirnames when topdown is false is ineffective, since the directories in dirnames have already been generated by the time dirnames itself is generated. By default errors from the os.listdir() call are ignored. If optional arg 'onerror' is specified, it should be a function; it will be called with one argument, an os.error instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the filename attribute of the exception object. Caution: if you pass a relative pathname for top, don't change the current working directory between resumptions of walk. walk never changes the current directory, and assumes that the client doesn't either. Example: from os.path import join, getsize for root, dirs, files in walk('python/Lib/email'): print root, "consumes", print sum([getsize(join(root, name)) for name in files]), print "bytes in", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories Andrew dalke at dalkescientific.com From adalke at mindspring.com Fri Nov 14 19:08:27 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 15 Nov 2003 00:08:27 GMT Subject: Palindrome References: <20031112223135.29045.00000109@mb-m12.aol.com> Message-ID: <%7etb.814$sb4.502@newsread2.news.pas.earthlink.net> Skip: > Oh, then how about: ... At the end are the three solutions I saw posted, from Ron Adam, Skip, and me (modified). The times are palindrome_adam 128.152670758 palindrome_skip 89.5211577111 palindrome_dalke 11.1900866758 Andrew dalke at dalkescientific.com import re, timeit # from Ron Adam def palindrome_adam(p): p = re.sub(r'\W','',p.lower()) i = len(p)//2 while i and p[i] == p[-i-1]: i -= 1 return not i # from Skip Montanaro def palindrome_skip(s): s = re.sub("[^A-Za-z0-9]+", "", s).lower() return s == s[::-1] # from Andrew Dalke foldcase = [] punctuation = [] for i in range(256): c = chr(i) if c.isalnum(): # note 'alnum' instead of 'alpha' ... foldcase.append(c.lower()) else: foldcase.append(c) punctuation.append(c) foldcase = "".join(foldcase) punctuation = "".join(punctuation) del c, i def palindrome_dalke(s): t = s.translate(foldcase, punctuation) return t == t[::-1] verify_data = [ ("A man, a plan, a canal -- Panama!", True), ("1234", False), ("123321", True), ("12321", True), ("Madam, I'm Adam.", True), ("A", True), ("ab", False), ("Oo!", True), ("Bolton", False), ("This is not a palindrome!", False), ("Was it a car or a cat I saw?", True), ("No 'H' type, mate, no spot stops one tame python!", True), ("A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal--Panama!", True), ] def verify(): for tester in (palindrome_adam, palindrome_skip, palindrome_dalke): for s, result in verify_data: assert tester(s) == result, (tester, s) print "Verified" _time_val = None def find_times(): global _time_val _time_val = verify_data[-1][0] # the long "a man, a plan ... Panama" one for tester in ("palindrome_adam", "palindrome_skip", "palindrome_dalke"): timer = timeit.Timer(setup = "import __main__ as M", stmt = "M." + tester + "(M._time_val)") t = timer.timeit() print tester, t if __name__ == "__main__": verify() find_times() From roel.mathys at yucom.be Thu Nov 6 14:06:55 2003 From: roel.mathys at yucom.be (rm) Date: 6 Nov 2003 11:06:55 -0800 Subject: PEP 289: universal and existential operators References: <5d83790c.0310231158.65595858@posting.google.com> <9f76ee00.0311051257.45461381@posting.google.com> Message-ID: <9f76ee00.0311061106.4c7dd8a9@posting.google.com> austin at smartobject.biz (Jess Austin) wrote > > It seems like the consensus is "all" and "any". > which exists as well in SQL e.g. select ... from ... where x > any ( sub-select ) or select ... from ... where x > all ( sub-select ) but SQL supports the following as well select ... from ... where exists ( sub-select ) bye, rm From bignose-hates-spam at and-benfinney-does-too.id.au Wed Nov 19 18:21:16 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 20 Nov 2003 10:11:16 +1050 Subject: beeping under linux References: Message-ID: On 19 Nov 2003 19:41:28 +0000, Alexander Schmolck wrote: > This is only partly a python question, but what is the easiest way to > get python to (reliably) beep under linux? By reliably I mean that > ``print "\b"`` won't do because it depends on the terminal settings Assuming you mean 'print "\a"' (ASCII BEL) rather than 'print "\b"' (ASCII BS), this is the most portable way to sound the terminal bell. Most responses have been talking about /dev/audio, which is unrelated to the terminal bell and is not portable -- many systems, especially headless ones, do not have any sound card. > [The usage scenario is simply to have an effective way of signalling > that a long running-process finshed, without me having to constantly > look at the screen] The correct way to do this is to send the ASCII BEL ("\a") character to the terminal. If the terminal's bell has been disabled somehow, it's not the job of your program to revert that decision. -- \ "I always wanted to be somebody. I see now that I should have | `\ been more specific." -- Lily Tomlin | _o__) | Ben Finney From Pieter.Claerhout at Creo.com Thu Nov 27 08:25:51 2003 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Thu, 27 Nov 2003 14:25:51 +0100 Subject: SAP DB and Python Message-ID: <490316A24CC5D411ACD700B0D078F7F003915C7C@cseexch01.cse.creoscitex.com> You can download the right binaries from their website. If you go to: http://www.sapdb.org/7.4/sap_db_downloads.htm At the bottom, you will see an row in the download table called "Python". That's the one you need. Cheers, pieter -----Original Message----- From: Gandalf [mailto:gandalf at geochemsource.com] Sent: 27 November 2003 14:25 To: comp.lang.python Subject: SAP DB and Python Hi! Does anyone know how to get a working version of sapdb.dbapi for Python 2.3 and SAP DB 7.4? Apparently, SAP DB 7.4 is the latest but the python module is for Python 1.5. Is there a compiled version around? If not, can I get the source and compile it with MinGW? Thanks, Laci 1.0 -- http://mail.python.org/mailman/listinfo/python-list From tchur at optushome.com.au Thu Nov 13 01:46:11 2003 From: tchur at optushome.com.au (Tim Churches) Date: Thu, 13 Nov 2003 17:46:11 +1100 Subject: Palindrome Message-ID: <200311130646.hAD6kBs10844@mail005.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From tomchance at gmx.net Sat Nov 22 17:08:19 2003 From: tomchance at gmx.net (Tom Chance) Date: Sat, 22 Nov 2003 22:08:19 +0000 Subject: Class not loading properly in CGI References: Message-ID: Jp Calderone wrote: >> I've got a very, very odd problem here which I can't seem to solve. I'm >> creating a class instance in a CGI script, but that instance isn't >> inheriting all of the methods associated with that file. Confused? Here's >> what I mean: >> >> the commands to check: >> import db >> mydb = db.mySQL() >> print str(dir(mydb)) >> >> done in a python shell on my machine: >> "['__doc__', '__init__', '__module__', 'connectTime', 'cursor', 'delete', >> 'fetchRow', 'fetchRows', 'info', 'insert', 'mysql', 'update']" >> >> in the cgi script online: >> ['connectTime', 'cursor', 'mysql'] >> >> What on earth is going on? > > Try printing db.__file__ That shows the correct .py file. Doing a dir() operation on the imported class itself looks fine though: db.mySQL (class) : ['__doc__', '__init__', '__module__', 'delete', 'fetchRow', 'fetchRows', 'info', 'insert', 'update'] mydb (class instance) : ['connectTime', 'cursor', 'mysql'] Tom From fumanchu at amor.org Fri Nov 28 15:38:15 2003 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 28 Nov 2003 12:38:15 -0800 Subject: newbie : using python to generate web-pages Message-ID: Logan wrote: > If there are not many places in your HTML where you have to substitute > strings, then an approach like the following might be enough: > > html = """ > > > %s > > > %s > > > """ > > print html % ("The Title", "Content Area") > > (You could also use placeholders like xxTitlexx, xxContentxx in > the string 'html' and replace them to create the output.) And if you're going to use named placeholders, you could just use named substitution (rather than writing your own parser to look for xx__xx): html = """ %(Title)s %(Body)s """ print html % ({"Title": "The Title", "Body": "Content Area"}) Robert Brewer MIS Amor Ministries fumanchu at amor.org From mwh at python.net Tue Nov 25 06:47:13 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 25 Nov 2003 11:47:13 GMT Subject: 'from __future__ import ...' overview References: Message-ID: Logan writes: > Is there a list with all 'from __future__ import ...' statements > (which lists all the statements, in which version of Python the > feature was introduced and in which version of Python it will become > the default behavior)? Yes: in __future__.py :-) Cheers, mwh -- Lisp does badly because we refuse to lie. When people ask us if we can solve insoluble problems we say that we can't, and because they expect us to lie to them, they find some other language where the truth is less respected. -- Tim Bradshaw, comp.lang.lisp From mcherm at mcherm.com Mon Nov 17 12:45:55 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Mon, 17 Nov 2003 09:45:55 -0800 Subject: for what are for/while else clauses Message-ID: <1069091155.3fb909533f7c8@mcherm.com> Fredrik Lundh writes: > the break statement has nothing to do with the else clause; the else > is executed when there's no more item in the sequence. if you break > or raise or return or yield-and-never-resume or call-and-never-return > your way out of the loop doesn't matter. > > read the C code if you don't believe me. [...] > for a while-statement, the controlling condition is the test at > the top. Fredrik, I didn't try to go read the C code... instead I experimented in Python: def testWhileElse(exitViaBreak, condTrueAtExit): print print 'exitViaBreak = %s' % exitViaBreak print 'condTrueAtExit = %s' % condTrueAtExit if exitViaBreak: loopCond = False else: loopCond = True while loopCond: if condTrueAtExit: loopCond = True break; else: print 'executed else clause' According to this experiment, the only way to get "executed else clause" to print is to set exitViaBreak to True. So I really don't understand what you are claiming. Seems to me that the execution of the else does NOT depend on the status of the loop condition at exit. Besides which... the point made by Alex (among others) is a good one: it doesn't matter how it's implemented under the covers... what matters is how the writer/reader thinks of the code. And I've always thought of the "else" on loops as having to do with the use or non-use of break statements. And in this particular case I suspect that's how MOST Python programmers think of it. -- Michael Chermside From jjl at pobox.com Sat Nov 15 10:56:54 2003 From: jjl at pobox.com (John J. Lee) Date: 15 Nov 2003 15:56:54 +0000 Subject: win32com with basic authentication References: Message-ID: <87r809mxq1.fsf@pobox.com> jeff writes: [...] > I use win32com.client to dispatch IE for a URL > browing. [...] > When IE starts to brow,the Login window pop up. > I was trying to enter the right password for it, but > IE wouldn't take it. it just keep poping up login > window. How do I write auto login method to send > user/password with COM method to bypass pop window for > login. This is a question for the microsoft.* newsgroups. > Or you might also help me how to dispatch for Netscape > browser. How do I dispatch it with a opening brower? > I know how to do it for IE, but don't know how to get > Info for netscape. Netscape... does that exist any more (serious question)? As for Mozilla, try PyXPCOM. Or DCOP and Konqueror (or possibly, you might be able to write a plugin for Konqueror using PyKDE now, not sure). I've never tried either, and they might be a pain to get built and working. John From amy-g-art at cox.net Sun Nov 23 23:40:06 2003 From: amy-g-art at cox.net (Amy G) Date: Sun, 23 Nov 2003 20:40:06 -0800 Subject: Newbie here... getting a count of repeated instances in a list. References: Message-ID: Thanks again for that code help. I was able to follow your comments to understand what you were doing. However, I was wondering how I can print out the number of instances from the dictionary. I might like to know not only that they are over the threshold, but what their actual count is. Thanks, AMY "Amy G" wrote in message news:keyvb.5217$9O5.2011 at fed1read06... > I started trying to learn python today. The program I am trying to write > will open a text file containing email addresses and store them in a list. > Then it will go through them saving only the domain portion of the email. > After that it will count the number of times the domain occurs, and if above > a certain threshhold, it will add that domain to a list or text file, or > whatever. For now I just have it printing to the screen. > > This is my code, and it works and does what I want. But I want to do > something with hash object to make this go a whole lot faster. Any > suggestions are appreciated a great deal. > > Thanks, > Amy > > ps. Sorry about the long post. Just really need some help here. > > > CODE > ************************ > file = open(sys.argv[1], 'r') # Opens up file containing emails > mail_list = file.readlines() # and sets the contents into a > list > > def get_domains(email_list): # This function takes list of emails > and returns the domains only > domain_list = email_list > line_count = 0 > while line_count < len(email_list): > domain_list[line_count] = > email_list[line_count].split('@', 1)[1] > domain_list[line_count] = > email_list[line_count].strip() > return domain_list > > def count_domains(domain_list): # Takes argument of a list of domains and > returns a list of domains that > counted_domains = 0 # occur more than number > of times > line_count = 0 > domain_count = 0 > threshhold = 10 > while line_count < len(domain_list): > domain_count = > domain_list.count(domain_list[line_count]) > if domain_count > threshhold: > r = 0 > counted_domains.append(d) > while r < (domain_count -1): > # Remove all other instances of an email once counted > domain_list.remove(d) > r = r + 1 > line_count = line_count + 1 > return counted_domains > > > domains = get_domains(mail_list) > counted = count_domains(domains) > print counted > > ******************************************** > > From francisgavila at yahoo.com Sun Nov 9 13:12:25 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 9 Nov 2003 13:12:25 -0500 Subject: displaying properly formatted output of ipconfig.exe References: <601be7f8.0311081449.24b3f7e2@posting.google.com> Message-ID: "Mark Hahn" wrote in message news:Jyirb.8919$7B2.5042 at fed1read04... > > "Cameron Laird" wrote in message > news:vqr3mnjhaf137 at corp.supernews.com... > > In article , > > Francis Avila wrote: > > > > > >"Joe Flynt" wrote in message > > >news:601be7f8.0311081449.24b3f7e2 at posting.google.com... > > . > > . > > . > > >> cmdpipe = os.popen("ipconfig","r") > > >> lines = cmdpipe.readlines() > > >> print lines > > > > > >You don't want to print a list of strings, you want to print each string > in > > >a list.... > > > > > > lines = cmdpipe.readlines() > > >- print lines > > >+ for line in lines: > > >+ print line > > . > > . > > . > > OR perhaps you want simply to print the output: > > - lines = cmdpipe.readlines() > > - for line in lines: > > - print line > > + print cmdpipe.read() > > > > OR, perhaps you want it to look right in a web page: > > #!C:\Python23\python.exe > import os > print "Content-type: text/html\r\n\r\n" > cmdpipe = os.popen("ipconfig","r") > print 'ipconfig' > lines = cmdpipe.readlines() > for line in lines: > print line,'
' > print '' > Actually, I just realized a subtle problem with using the print statement in (almost) all these examples (including my own). Since the output already includes newlines, and print appends a newline, you'll end up with doubled newlines. Perhaps just used the write() method of the file object of interest? Or, you could append a comma to all your print statements (although this is bound to cause maintenance problems later). -- Francis Avila From jarrodhroberson at yahoo.com Thu Nov 27 02:00:54 2003 From: jarrodhroberson at yahoo.com (Y2KYZFR1) Date: 26 Nov 2003 23:00:54 -0800 Subject: Simple instructions on how to programmatically download an image from a web page? Message-ID: I have search the group and not found a working example on how to simply download a .gif from a url. something as simple as http://groups.google.com/images/threadview_logo.gif should be pretty easy, guess not? I don't need to know about using a browser, I need to know how to do it programmatically from Python. Anyone know how to get it done? From gerson.kurz at t-online.de Wed Nov 5 15:44:10 2003 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Wed, 05 Nov 2003 20:44:10 GMT Subject: Unicode and Zipfile problems References: <3fa8d5ee.304218@news.t-online.de> <3fa8fdaf.10480921@news.t-online.de> Message-ID: <3fa95db2.3932921@news.t-online.de> >Of course, this codec does not work for your original problem: Just >see try it on your original data, and then see how Winzip >misinterprets the file names. You are of course right (although my original problem was not with the filenames - I am using an english version of Windows - but with the header information). But, if you look at the number of people that have run into problems with pythons strictness in unicode matters - isn't it time to offer some more "relaxed" way of handling all this? I mean, come on, Python is the language that will change the meaning of 7/3 because people had problems with integer division. And, although some people use Python for large multilanguage applications - I would bet that by far more people use Python for lots of small utility scripts, and couldn't care less about whether or not its "international". It just has to work, on my machine(s). Its not rocket science. From tjreedy at udel.edu Mon Nov 17 22:01:17 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Nov 2003 22:01:17 -0500 Subject: Python's simplicity philosophy References: <2259b0e2.0311112248.3be2d304@posting.google.com><17lsb.109042$fl1.4548960@twister.southeast.rr.com> <20031112170100.GA32388@godzilla.fibrespeed.net> <8Y7tb.21901$9_.802189@news1.tin.it> Message-ID: "Alex Martelli" wrote in message news:P75ub.43095$hV.1657519 at news2.tin.it... > Terry Reedy wrote: > > Would the hypothetical > > results = sequence.map(func x: x+23) > > be any better? > > Just replacing the keyword 'lambda' with 'func'? If you were > designing a green-field language, and couldn't find any other way > to express callable literals -- so it only came down to a 2-way > choice between lambda and func as keywords with the same semantics, > I guess I would suggest func as the lesser evil. If such a change were plausibly within the boundaries changes allowed for the as-yet hypothetical 3.0 (or 3000), and there were not a more radical change that I preferred, I might seriously propose this. Upgrading would be simple than most other code-break changes. > > How about a very hypothetical (post ``==repr deprecation) > > results = sequence..map(`x+23`) > > How would this notation imply that x is an argument rather than, > say, a global? The above was a minimal 'concept' proposal to test the aesthetics of something structurally different from current 'lambda's. I think I would make all identifiers params by default, since I believe this to be more common, and 'tag' non-locals, perhaps with one of the reserved, as yet unused symbols. Example: lambda x: x + y == `x + @y` or `x+y@`. Since expressions cannot assign, no global declaration is needed. Terry From FBatista at uniFON.com.ar Thu Nov 20 13:15:56 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 20 Nov 2003 15:15:56 -0300 Subject: Saving / Restoring data in a program Message-ID: Bob van der Poel wrote: #- this is turning into a bit of a mess. It's error prone since #- I have to #- make sure that I restore everything I save and I have to make sure I #- usethe same spellings. And, I have to be aware of the data #- types so I #- can decide if [:] or copy() or even copy.deepcopy() is needed. Why don't append them all to a list? In first place, why you need to "store" them? Can't understand what are you trying to do, :( . Facundo From martin at v.loewis.de Thu Nov 6 15:09:04 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 06 Nov 2003 21:09:04 +0100 Subject: Strange problems with encoding References: <7h3wuadfvt3.fsf@pc150.maths.bris.ac.uk> <7h3r80lfrqy.fsf@pc150.maths.bris.ac.uk> Message-ID: Rudy Schockaert writes: > I wasn't even aware there are two camps. What would be the reasons not > to use setdefaultencoding? You lose portability (more correctly: you get a false sense of portability). If you have write an application that requires the default encoding to be FOO-1, the application may work fine on system A, and fail on system B. Telling the operator of system B to change her default encoding may cause breakage of a different application on system B, as B has BAR-2 as the default encoding; changing it to FOO-1 would break applications that require it to be BAR-2. IOW, if you require conversions between Unicode and byte strings, explicitly do them in your code. Explicit is better than implicit. > As I configured it now it uses the systems locale to set the > encoding. I'm using the same machine to retrieve data, manipulate it > and store in a database (on the same machine). I would like to > understand what could be wrong in this case. If the next user logs in on the same system, and has a different locale set, that user will misinterpret the data you have created. > What I mean is that I encode the data when I store it in the DB and > decode it when I retrieve the data from the DB. I do this because > SQLObject doesn't support the binary data. As long as the result that > comes back out is exactly the same as it was when it went in, I don't > care. Then you should *define* an encoding that your application uses, e.g. UTF-8, and use that encoding throughout whereever required, instead of having the administrator to ask to change a system setting. Regards, Martin From python-url at phaseit.net Mon Nov 17 11:09:25 2003 From: python-url at phaseit.net (Emile van Sebille) Date: Mon, 17 Nov 2003 16:09:25 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Nov 17) Message-ID: QOTW: "I've tried many ways over the years to represent equations legibly using Python and [it is] my experience that case sensitivity, while certainly no panacea, helps." -- Tim Hochberg "What's your pet deprecation candidate? I have always thought `backticks` as repr has got to be the most useless feature around." -- Ville Vainio Peter Hansen suggests "Imagine never having to think up variable names more complicated than 'foo'." http://groups.google.com/groups?threadm=3FB2738E.2B8C13FE at engcorp.com Patrick Maupin advocates conversion to python as a step in refactoring. http://groups.google.com/groups?threadm=653b7547.0311142204.7b7abebc at posting.google.com Jack Jansen is looking for a FAQ maintainer volunteer. CV not required. http://mail.python.org/pipermail/pythonmac-sig/2003-November/009493.html For its third installment on 7-9 June 2004, the Europython Conference moves to a new venue: the Chalmers University of Technology, G?teborg, Sweden. http://www.europython.org Uche Ogbuji speaks tonight on Python paradigms for XML processing in Broomfield, Colorado. http://groups.google.com/groups?selm=mailman.691.1068688678.702.python-list at python.org Trent Mick announces releases from ActiveState of ActivePython 2.2.3 and 2.3.2 for Windows, Linux and Solaris. http://groups.google.com/groups?selm=mailman.748.1068847576.702.python-list at python.org PDO provides an object-oriented API, something like ADO or JDBC, built over dbapi. http://sourceforge.net/projects/pythondbo/ Markku H=E4nninen created a small utility to create Python stubs from Java classes using Jython. http://groups.google.com/groups?selm=8ca943c2.0311110928.1ec29ca8 at posting.google.com Diez B. Roggisch seeks use cases for the for/else and while/else constructs. http://groups.google.com/groups?threadm=bp371c$g75$07$1 at news.t-online.com Anthony Baxter is looking for a Pythonesque name for a first cut at a pure-Python SIP (VoIP) phone he's implemented. http://groups.google.com/groups?threadm=mailman.685.1068679064.702.python-list at python.org Bernard Fields gets pointers on creating a maze. http://groups.google.com/groups?threadm=1PSsb.44675$jy.34613 at clgrps13 Corey Lubin gets help on overriding variables used by base classes. http://groups.google.com/groups?threadm=a64176a.0311140417.2ad0b51a at posting.google.com Andreas Held announces the second beta release of pyFLTK, the Python bindings for the FLTK toolkit. http://groups.google.com/groups?selm=564eac6f.0311112311.2536af43 at posting.google.com Russell Nelson releases Familiar v0.7.2, a Linux distribution for the Compaq/HP iPAQ series of handhelds. The v0.7.2 release includes a special 'pypaq' and now a programmer can write a GUI program in Python on their handheld. http://groups.google.com/groups?selm=mailman.729.1068759937.702.python-list at python.org Michele Simionato wants to disable/enable the screensaver on a Win98 box with a Python script. http://groups.google.com/groups?threadm=2259b0e2.0311060704.754a4b6e at posting.google.com Hoang Do wants to know of a Structured Text or ReStructured Text interactive previewer. http://groups.google.com/groups?threadm=Es8sb.3846$LY4.38766634 at newssvr21.news.prodigy.com Metaclasses get further clarified in response to a question by Fernando Rodriguez. http://groups.google.com/groups?threadm=jbq6rvob5qjddbtt6vk97gsr6hk993e6j3 at 4ax.com Al Bogner both provides and gets links in his effort to build a database client with a GUI http://groups.google.com/groups?threadm=2560581.qn5EVrxEmu at usenet.pinguin.uni.cc Brian Lloyd releases Python for .NET 1.0 beta 2, a near-seamless integration of Python with the .NET common language runtime. http://mail.python.org/pipermail/pythondotnet/2003-November/000032.html ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least 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 The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ 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. *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 adalke at mindspring.com Tue Nov 11 18:02:38 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 11 Nov 2003 23:02:38 GMT Subject: Am I the only one who would love these extentions? - Python 3.0 proposals (long) References: Message-ID: Me: > > and I think changing > > FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16 > > into > > FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT, ... = x*x for x in > > itertools.count(1) > > is just plain stupid. Alex: > Not necessarily stupid, but it sure IS semantics-altering (as well > as syntactically incorrect in the proposed 2.4 syntax for genexps -- > you'll need parentheses around a genexp) -- a sequence of squares > rather than one of powers of two. > (2**x for x in itertools.count()), however, would be fine:-). Oops! :) What I considered 'stupid' was changing something that was easy to verify by eye (1, 2, 4, 8, 16) into something which used a generator (or list comprehensions; I was experimenting with the new idea) and is harder to verify by eye. The generator form has the advantage of allowing new terms to be added without additional modifications, but given how unchanging that code is, it's a false savings. > I think you just grabbed the record for shortest-lived proposal > in Python's history. Applause, applause!-). I can do better than that ;) I propose a requirement that all Python code include the author's PSU name before the first exectuable statement in the file. It must be of the form '#PSU: ....' as in #PSU: Parrot Funny-Walker of Wensleydale This would let ... err, just a mo', someone's at the From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Nov 15 07:10:42 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 15 Nov 2003 13:10:42 +0100 Subject: RuntimeError 'maximum recursion depth exceeded' In-Reply-To: <30ntb.5073$C14.183051@twister.southeast.rr.com> References: <30ntb.5073$C14.183051@twister.southeast.rr.com> Message-ID: <3fb617c0$0$58715$e4fe514c@news.xs4all.nl> Georgy Pruss wrote: > RuntimeError: maximum recursion depth exceeded > > Is there any way to set a bigger stack in Python? Yep: sys.setrecursionlimit --Irmen From fredrik at pythonware.com Tue Nov 18 11:48:35 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Nov 2003 17:48:35 +0100 Subject: Detecting Browsers in Python References: <77dd287a.0311180813.5405af98@posting.google.com> Message-ID: Daniel Orner wrote: > Does anyone know of a simple way to have a Python script find out what > browser is accessing it? After a web search the only thing I found to > do this is Zope, but the system I'm programming doesn't use Zope and > I'm not really interested in installing it just for this minor detail. > Is there another way? if you're using a CGI script, you can (usually) find the user agent in the HTTP_USER_AGENT environment variable; use os.environ to get the current value. #!/usr/bin/python -u import os print "Content-type: text/plain" print print "User agent:", os.environ.get("HTTP_USER_AGENT", "unknown") if you're using some other framework, you may be able to get the user agent by looking at the HTTP headers; check the framework docs for details. for more info on CGI environment variables, see: http://hoohoo.ncsa.uiuc.edu/cgi/env.html http://httpd.apache.org/docs/env.html http://httpd.apache.org/docs/misc/FAQ.html#cgi-spec (etc) From robin at jessikat.fsnet.co.uk Tue Nov 11 03:43:28 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 11 Nov 2003 08:43:28 +0000 Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: In article , Francis Avila writes >"Alex Martelli" wrote in message >news:BsJrb.445840$R32.14865362 at news2.tin.it... >> Francis Avila wrote: >>> [a reduce() clone] >> [a long and thorough critique] > >*Sigh* My only objective was to combine functional/recursive/iterative >programming styles into an olive branch to extend to both parties of this >silly war. > >But oh well. Like I said, I never found a use for reduce, but alas, I am a >ham-fisted programmer entirely lacking in subtlety and art.... >-- >Francis Avila > This whole thread is reminiscent of vi vs emacs or an os war or similar. It's a pity that people with a preferred style should be so dogmatic that they want to remove language features to prevent others using them. The whole 'only one way to do it' concept is almost certainly wrong. There should be maximal freedom to express algorithms. As others have stated min, max,... sum et al are useful specialisations, but because they cover 99% of the space doesn't mean that reduce is redundant. -Eliminate reducespeak and control the future-ly yrs- Robin Becker From jeder at earthlink.net Fri Nov 28 16:19:06 2003 From: jeder at earthlink.net (Ryan Spencer) Date: Fri, 28 Nov 2003 21:19:06 GMT Subject: Blinky Program References: Message-ID: On Fri, 28 Nov 2003 17:16:08 +0100, Gerhard H?ring wrote: > Ryan Spencer wrote: >> [..] I was recently informed by someone that I could help >> free up some memory usage by alleviating the sys.stdout.flush's in the >> code, [...] > > This decidedly sounds like somebody's brainfart. > > -- Gerhard Hehe, All righty then. Thanks Gerhard. ~Ryan From francisgavila at yahoo.com Mon Nov 3 23:32:54 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 3 Nov 2003 23:32:54 -0500 Subject: Sorting out which exceptions to handle References: <3fa70fe4$0$1740$5a62ac22@freenews.iinet.net.au> Message-ID: "Derek Fountain" wrote in message news:3fa70fe4$0$1740$5a62ac22 at freenews.iinet.net.au... > The O'Reilly Python in a Nutshell book says "Generally your code uses a > statement of the form: > > try: > ... > except module.Error, err: > ... > " > > with the word "module" in italics. I tried the line: > > except MySQLdb.Error, err: > > and various variations, but always got errors. The O'Reilly book is simply pointing out a convention. Usually modules only need one exception type, and it's called 'Error' (or 'error' for builtin modules). It's not some magic syntax or semantics that catches every kind of exception that a module could raise. > How do I trap all the database associated errors this module can generate? Trapping an exception traps all exceptions which are subclasses of that exception. E.g.: >>> class BaseError: ... pass ... >>> class SpecialError(BaseError): ... pass ... >>> try: ... raise SpecialError #Implicit class instantiation ... except BaseError, err: ... print 'Caught instance of BaseError or subclass thereof.' ... print 'Specifically,', repr(err) ... Caught instance of BaseError or subclass thereof. Specifically, <__main__.SpecialError instance at 0x00AB9340> >>> Hope this helps. -- Francis Avila From bokr at oz.net Fri Nov 14 18:28:17 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Nov 2003 23:28:17 GMT Subject: how to return a StringIO of an Image References: Message-ID: On Fri, 14 Nov 2003 20:38:43 +0000 (UTC), JCM wrote: >Bengt Richter wrote: >> On Fri, 14 Nov 2003 16:45:39 +0100, "Fredrik Lundh" wrote: > >>>"Christoph" wrote: >>> >>>> image.save('test', 'JPEG') >>>> image=StringIO(image.????()) # what's the right method? >>>> return image >>>> >>>> Any hints? Thanx! >>> >>> file = StringIO() >>> image.save(file, "JPEG") >>> return file.getvalue() >>> >> You are recommending shadowing 'file' ?! > >Why not? Python is a block-structured language. New builtins can >arrive in any release. I'd say a reason is to avoid the time you will do it by habit and get a surprise. But yes, there's no technical reason you can't, if you don't want to use the original binding in that scope. Regards, Bengt Richter From tdelaney at avaya.com Mon Nov 3 21:03:32 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 4 Nov 2003 13:03:32 +1100 Subject: strptime performance Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DEDF5C91@au3010avexu1.global.avaya.com> > From: John Roth [mailto:newsgroups at jhrothjr.com] > > "George Trojan" wrote in message > news:bo6oaf$vfq$1 at news.nems.noaa.gov... > > Is time.strptime() intrinsically slow and should be avoided whenever > > possible? I have the following code in my application: > > According to the "what's new in Python" for 2.3, the strptime > implementation was switched from a lightweight wrapper > around the frequently buggy and incompatible C library > to a portable pure Python implementation. Note also in 2.3.1 (and later) ... "Caching in _strptime.py has been re-introduced. This leads to a large performance boost at the cost of not being thread-safe from locale changes while executing time.strptime()". > Yes, it's going to be a lot slower. Now that's an assumption you shouldn't be making until you've timed it. Tim Delaney From __peter__ at web.de Tue Nov 25 20:25:00 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Nov 2003 02:25:00 +0100 Subject: Newbie question: eliminating entries in dict References: Message-ID: sean wrote: > I have two dictionaries. > > a = {'a1': 1, 'a2': 5, 'a3': 2, 'a4': 7} > b = {'something*a4': 1, 'something*something': 1, > 'somethingelse*somethingelse': 1, 'something*a1: 1} > > What would be an efficient way of eliminating all entries in b which > contain an entry from a. > > Such that the result would be > > c = ['something*something', 'somethingelse*somethingelse'] > > or better still > c = {'something*something': 1, 'something*something': 1} > > I tried a few different approaches, but they seem very long and > unnecessary. Also searched the mailing list archives and newsgroups and > could not come up with anything. > > I know that I will need to compare the .split("*", 1)[1] part of b with > those from a, but am not sure > how to implement it. > > Thanks in advance for any help >>> dict([(k,v) for k, v in b.iteritems() if k.split("*", 1)[1] not in a]) {'something*something': 1, 'somethingelse*somethingelse': 1} Two newbie collegues? If you really want to learn something in the process, a homemade for-loop beats that list comprehension thingy copied from usenet anytime :-) Peter From aleaxit at yahoo.com Sat Nov 1 04:02:58 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 01 Nov 2003 09:02:58 GMT Subject: py2exe question References: <3FA36D0A.45BCA44B@easystreet.com> Message-ID: <6FKob.391474$R32.12987108@news2.tin.it> achrist at easystreet.com wrote: > The py2exe says that a console app should have the --console option > and a windows app should have the --windows option. > > What is the way to py2exe a python program that uses both console and > windows gui? Haven't tried, but logically it should be a console -- this doesn't restrict what OTHER modules you can import, it just uses the equivalent of a .py script run with python.exe rather than a .pyw run with pythonw.exe, i.e. a "DOS box" console does appear when the program is run. Alex From newsgroups at jhrothjr.com Mon Nov 10 09:45:29 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 10 Nov 2003 09:45:29 -0500 Subject: On python syntax... References: Message-ID: "Steve H" wrote in message news:eb2f38f3.0311100541.474fa706 at posting.google.com... > I'm writing a library in which I have a stream object supporting a > Write mehod, and I require to provide support for writing arbitrary > strings in arbitrary nested contexts. A simplified example solution > might look like this. > > -- > # Simplified matching marker calls. > def Open(s) : > s.write("(") > def Close(s) : > s.write(")") > > #Main body > def Square(s) : > s.Open() > for i in range(100) : > s.open > for j in range(100) : > s.write("{%s,%s}"%i,j) > s.close > s.close > -- > > While this solution would work, I'm less than happy that the > programmer is left to ensure calls to Open are matched with calls to > close. It is significant to note that every call to open is at the > beginning of a nested context, and every call to close is at the > corresponing end of the same nested context. > > Having glanced through the python manual I notice that the C++ trick > of using an object with a destructor to manage this sort of behaviour > is inappropriate for a phython script (as __del__ may be called at any > time once the ref-count for an object is 0.) I wonder, is there a > better approach to this problem than the solution above (maybe using > lambda functions?) I'd like a main body of the following form to > generate the same result: > > def Square(s) : > ManageContext(s) > for i in range(100) : > ManageContext(s) > for j in range(100) : > s.write("{%s,%s}"%i,j) > > Any suggestions? If I wanted things to happen automatically, I'd do one of two things. A. Build a stack so that I could insert ending syntax when I popped something off the stack B. Use an object oriented approach and build a tree. Then I could simply tell the tree to write itself, and each object could handle the ending syntax. Also: please don't use tabs for indentation when you're posting code snippets. There are a number of e-mail and news readers that simply ignore tabs, causing your entire program to be neatly left justified, and making it difficult to read. I've replaced your tabs with spaces in this reply. John Roth From johan at weknowthewayout.com Thu Nov 20 10:24:31 2003 From: johan at weknowthewayout.com (Johan Holst Nielsen) Date: Thu, 20 Nov 2003 16:24:31 +0100 Subject: Analyse of PDF (or EPS?) In-Reply-To: <3fbcdc0d$0$9816$edfadb0f@dread14.news.tele.dk> References: <3fbcc67e$0$9836$edfadb0f@dread14.news.tele.dk> <3FBCCDA5.47275BB7@engcorp.com> <3fbcdc0d$0$9816$edfadb0f@dread14.news.tele.dk> Message-ID: <3fbcdcea$0$9750$edfadb0f@dread14.news.tele.dk> Johan Holst Nielsen wrote: > Peter Hansen wrote: > >> Johan Holst Nielsen wrote: >> >>> Is there any Python packages to analyse or get some information out of >>> an PDF document... >>> >>> Like where the text are placed - what text are placed - fonts, embedded >>> PDFs/fonts/images etc. >>> >> >> I believe the not-for-free version of ReportLab has this sort of >> capability, >> at least in some sense. > > > Aah, you think about the product "PageCatcher", right? :) Just found the pricing :( I think USD 25,000 are way out of my budget :( I have someone have some alternatives :) Regards, Johan From janeaustine50 at hotmail.com Tue Nov 18 10:59:56 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 18 Nov 2003 07:59:56 -0800 Subject: Memory exception with Tkinter root.quit References: Message-ID: janeaustine50 at hotmail.com (Jane Austine) wrote in message news:... > >Jane Austine wrote: > >>>>from Tkinter import * > >>>>>r=Tk() > >>>>>b=Button(r,text='Quit',command=r.quit) > >>>>>b.pack() > >>>>>r.mainloop() > >> > >> > >> And when I press the "Quit" button the mainloop exits. After that, > if > >> I finish the python shell, a memory exception occurs. > >> > >> This is Windows XP machine with Python 2.3. > > > > Not much of a help, but I've tried it here: no problems... (python > > 2.3.2, win xp). Can it be a Python 2.3.0 issue that has been fixed in > > 2.3.1 or 2.3.2 ? > > > > --Irmen > > I tried it with 2.3.2, but it doesn't work either. > > The crash message is: > > python.exe -- application program error > > the command from "0x77f7e22a" referenced the memory at "0x00000028". > The memory couldn't be "read". Well, I seem to have found the (vague) reason. There is a file named python.exe.manifest (along with pythonw.exe.manifest) in the python folder. If I delete it, Tkinter doesn't raise memory exception. What is it? Is it safe to delete it? From des.small at bristol.ac.uk Fri Nov 28 06:51:54 2003 From: des.small at bristol.ac.uk (Des Small) Date: Fri, 28 Nov 2003 11:51:54 GMT Subject: invert dictionary with list &c References: Message-ID: anton muhin writes: > Des Small wrote: > > Des Small writes: > > > >>anton muhin writes: > > [...] > > Or like this: > > def dict_update(iter, func, default, d): > def process_element(d, e): > d[e[0]] = func(d.get(e[0], default), *e[1:]) > return d > > return reduce(process_element, iter, d) > > def count(l): > return dict_update(l, lambda x: x + 1, 0, {}) With these I get: >>> count(["yes", "yes", "no"]) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in count File "", line 5, in dict_update File "", line 3, in process_element TypeError: () takes exactly 1 argument (3 given) I tried to write something that would work on more generic arguments, but I couldn't do it without explicit type checking, so I gave up. [...] Des has now embalmed versions in his utils collection. -- "[T]he structural trend in linguistics which took root with the International Congresses of the twenties and early thirties [...] had close and effective connections with phenomenology in its Husserlian and Hegelian versions." -- Roman Jakobson From dietrich at zdome.net Fri Nov 7 08:37:29 2003 From: dietrich at zdome.net (Dietrich Epp) Date: Fri, 7 Nov 2003 05:37:29 -0800 Subject: XML DOM In-Reply-To: References: Message-ID: <883A4237-1127-11D8-834B-0003934ACDEC@zdome.net> On Nov 7, 2003, at 5:17 AM, Carlo Sette wrote: [snip] > xml.parsers.expat.ExpatError: mismatched tag: line 1, column 112 [snip] > XML=""" version="1.0"?>55> > CarloSette""" That's not XML, but it's close. There's a '>' after the 55. Also, it says 'tabedata' instead of 'tabledata' in the opening root tag. From usenet at mail-2-me.com Thu Nov 6 03:23:17 2003 From: usenet at mail-2-me.com (Dirk Hagemann) Date: 6 Nov 2003 00:23:17 -0800 Subject: Listing computers of a WinNT-Domain Message-ID: Hi! I'm using this code to list all computers of our WinNT-Domains: import win32com.client from pprint import pprint as p domain='domainX' auswahl='computer' def enumerate(domain,auswahl): adsi = win32com.client.Dispatch("ADsNameSpaces") nt = adsi.GetObject("","WinNT:") result = nt.OpenDSObject("WinNT://"+domain+"","","",0) result.Filter = [auswahl] # computer, user, group domain = [] for machine in result: domain.append(machine.Name) return domain p(enumerate(domain,auswahl)) This works well with all domains except one domain. One of the domains returns an emty list of computers, but it returns users an groups if I set the filter accordingly; just the computers are missing (even if I do not filter). One week ago it was fully working... What can have happend? Any idea anybody? Regards Dirk PS: the computers are still existing in this domain. From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Mon Nov 24 18:10:42 2003 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Tue, 25 Nov 2003 00:10:42 +0100 Subject: instance of COM-server with Win32all References: Message-ID: Hi ! Thanks for your read of my message. Indeed, I seek a "global singleton". Il have try singleton-tech, but when differents soft call my python-COM-server, i obtain differents singleton (sic). I want have an persistant-dictionary, common to all task on one computer. I have look other softs : - MsWord have an "handle instance" (!?) - Delphi requires, at the beginning of an COM/OLE-project, to choose "mono-instance" or "multi-instance". For the moment, I circumvented the problem with a local-TCP/IP-server, common to all the softwares of the computer, but if it's possible, I prefer to integrate that in my COM-server. Can I hope for a solution with win32all ? In all the cases, thank you very much, for your works, and forgive my bad English. @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B site : http://mclaveau.com NG : news://news.zoo-logique.org/programmation.Paradox From eppstein at ics.uci.edu Mon Nov 17 15:11:22 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 17 Nov 2003 12:11:22 -0800 Subject: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <8hfsb.7707$nz.895@newsread2.news.pas.earthlink.net> <7x65hiahdp.fsf@ruckus.brouhaha.com> Message-ID: In article <7x65hiahdp.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Ville Vainio writes: > > I wouldn't mind Python getting more influence from functional realm, > > as Python seems to me to be *the* hybrid language that can pull the FP > > thing while still remaining practical and intuitive (and delightfully > > non-academic). > > Python sometimes seems to go out of its way to thrwart the use of > functional style. Look at list.sort returning None, for example. The issue here is not that it returns None, but that it changes its input. To be truly functional, it should return a new list and leave the original list unchanged. Returning None is just a helpful reminder that it's not functional. Of course, the functional version would often be less efficient... -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From frr at easyjob.net Wed Nov 19 06:00:29 2003 From: frr at easyjob.net (Fernando Rodriguez) Date: Wed, 19 Nov 2003 12:00:29 +0100 Subject: smtp server Message-ID: <29jmrvc4s9blgmpusb3t70b9g2c8q3q3gf@4ax.com> Hi, Is there any python smtp server available with source? TIA From bignose-hates-spam at and-benfinney-does-too.id.au Thu Nov 20 19:48:14 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 21 Nov 2003 11:38:14 +1050 Subject: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com> <3FBC2025.B2A33B6F@alcyone.com> <87d6bncbaj.fsf@einstein.electron.net> <3FBD3D6F.E4068821@alcyone.com> <878ymad3ga.fsf@einstein.electron.net> <3FBD6419.A5A863C8@alcyone.com> Message-ID: On Thu, 20 Nov 2003 17:02:17 -0800, Erik Max Francis wrote: > man uniq on GNU: > > DESCRIPTION > Discard all but one of successive identical lines from > INPUT (or standard input), writing to OUTPUT (or standard > output). > > This says nothing about sorting. Sadly, the 'NAME' section does: NAME uniq - remove duplicate lines from a sorted file I suspect this is a source of confusion; certainly, it doesn't help. -- \ "Read not to contradict and confute, nor to believe and take | `\ for granted ... but to weigh and consider." -- Francis Bacon | _o__) | Ben Finney From Mike at DeleteThis.Geary.com Sat Nov 22 13:32:58 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 22 Nov 2003 10:32:58 -0800 Subject: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com> <3FBC2025.B2A33B6F@alcyone.com> <87d6bncbaj.fsf@einstein.electron.net> <3FBD3D6F.E4068821@alcyone.com> <878ymad3ga.fsf@einstein.electron.net> <3FBD6419.A5A863C8@alcyone.com> <874qwyaqqj.fsf@einstein.electron.net> <3FBE892D.22B4A544@alcyone.com> Message-ID: Curt wrote: > I haven't shifted goalposts, whatever that means. You shifted the > emphasis of my example by removing only one of the duplicates. > > I concede that "uniq" does something "meaningful" on unsorted > input, if that input contains identical, successive lines. I do not > concede, however, that you may never be required to sort its > input in order to arrive at that state, which is exactly what my > demonstration "proved". > > If I've just shifted goalposts, well, you can all shoot me at dawn, > if you feel it's a capital offense. Don't worry, we'll give you the > real bullet. Curt... It is unfortunate that both the program name and the one-line description of uniq are misleading: uniq - remove duplicate lines from a sorted file Well, yes: If a file is sorted, then uniq removes all duplicate lines, and the resulting file contains only unique lines (thus the name 'uniq'). But the fact remains that what uniq actually does has nothing to do with sorting. It removes consecutive duplicate lines. That's all. If I flip a coin 100 times and record the results, will there be consecutive "heads" or "tails"? Most likely. Is that file sorted? Of course not--it's completely random. Will uniq remove the consecutive duplicates? Yes. It's really that simple. -Mike From francisgavila at yahoo.com Tue Nov 4 17:37:13 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Tue, 4 Nov 2003 17:37:13 -0500 Subject: XORing long strings opimization? References: <3ISpb.24447$BD3.4566933@juliett.dax.net> Message-ID: "Noen" wrote in message news:ieUpb.24457$BD3.4567875 at juliett.dax.net... > nope, thought the Argument check would do it, but I used and opeartor > instead of or. Well, here is XOR v.0.3b :P Any comments how to make it > faster? How about using the struct module? Caveat: I don't know if struct limits the repeat count. import struct def XOR(data, key): if len(data) != len(key): raise ValueError, "data and key not of equal length" ldata = struct.unpack('=%sb' % len(data), data) lkey = struct.unpack('=%sb' % len(key), key) lxored = [d^k for d,k in zip(ldata, lkey)] xored = struct.pack('=%sb' % len(lxored), *lxored) return xored Just an idea. -- Francis Avila From wweexxsseessssaa at telus.net Sat Nov 1 20:12:33 2003 From: wweexxsseessssaa at telus.net (John Hall) Date: Sun, 02 Nov 2003 01:12:33 GMT Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0310312008.ce341ea@posting.google.com> <87r80sdyb1.fsf@pobox.com> <7xn0bg6njb.fsf@ruckus.brouhaha.com> <7x7k2jpti9.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 02 Nov 2003 00:09:49 GMT, Todd Stephens wrote: >BTW, is Kapital written in Python? I don't see why this thread is even >here save for tKc's involvement with BlackAdder. The OP was about Rekall, not Kapital or BlackAdder. Rekall _IS_ in Python. -- John W Hall Cochrane, Alberta, Canada. "Helping People Prosper in the Information Age" From jjl at pobox.com Tue Nov 25 14:03:24 2003 From: jjl at pobox.com (John J. Lee) Date: 25 Nov 2003 19:03:24 +0000 Subject: minidom nodes without a document? References: <8b5e42a6.0311231738.6376d486@posting.google.com> Message-ID: <87n0ak9soz.fsf@pobox.com> mlh at furu.idi.ntnu.no (Magnus Lie Hetland) writes: > In article <8b5e42a6.0311231738.6376d486 at posting.google.com>, Levente > Sandor wrote: > >mlh at furu.idi.ntnu.no (Magnus Lie Hetland) wrote in message > >news:... > >> Is it possible to build a minidom tree bottom-up without access to a > >> document node? It seems that simply instantiating the various node > >> classes doesn't quite do the trick... > > > >I'm not sure what you mean exactly by "without access to...". You need > >a Document instance to create the elements, but they aren't added > >automatically to it. > > > [snip] > > Right. I understand this. Thanks to you and Martin for mentioning it, > though :) > > My problem is that I'm building the DOM as part of a bottom-up parse, > where the various subtrees are build independently from each other, > through callbacks that are set as part of the parser. So... For all of [...] You want DocumentFragment. But Martin's right (of course): you still need a Document, and you make fragments by calling Document.createDocumentFragment(). For a headache-inducing example of the use of this (my headache, not yours, I hope ;-), see http://wwwsearch.sf.net/DOMForm/ (the parser is in the file DOMForm/_js.py -- it gave me a headache because everything prior to a chunk of embedded script in HTML has to be available to the script through the document object, so sometimes you have to append to a DocumentFragment, sometimes to a node in the main Document tree) John From s.meyer at technology-network.de Thu Nov 6 11:31:47 2003 From: s.meyer at technology-network.de (Sebastian Meyer) Date: Thu, 06 Nov 2003 17:31:47 +0100 Subject: Strange problems with encoding References: <7h31xslhb6e.fsf@pc150.maths.bris.ac.uk> Message-ID: On Thu, 06 Nov 2003 15:10:49 +0100, Sebastian Meyer wrote: > On Thu, 06 Nov 2003 13:39:25 +0000, Michael Hudson wrote: > >> 2) I presume `str' is a unicode string? Try writing the literal as >> u'?' instead (and adding the appropriate coding cookie to your >> source file if using Python 2.3). Or I guess you could write it >> >> u'\N{LATIN SMALL LETTER O WITH DIAERESIS}' > > i ll try and report back... okay, i ve solved my problem... it seems that my method which tries to insert the data i process into the database raises the error. The data comes from XML files, my derived xml.sax.handler.ContentHandler returns UniCode encoded data. The database routine tries to encode the values as ASCII and --**BOOOM**-- ... Exception. I now replace the special characters by their UniCode Names eg. u'\N{LATIN SMALL LETTER O WITH DIAERESIS}' (thanks for the hint michael), now all for works fine... ;-)) thanks for the great help NG Sebastian From vincent at visualtrans.de Sat Nov 22 08:03:04 2003 From: vincent at visualtrans.de (vincent wehren) Date: Sat, 22 Nov 2003 14:03:04 +0100 Subject: How send LIST to C extension? References: Message-ID: "Christian Seberino" schrieb im Newsbeitrag news:bf23f78f.0311211356.7368197c at posting.google.com... | I already sent a post about problems sending list as argument in a C extension. | | I think I'll start over and just ask if anyone has done this successfully. | | Can you send me code that does this?? | | (I tried PyArg_ParseTuple("[ii]",...) but apparently there is more to it than | just adding brackets. In your function you need something like PyObject* seq; if(!PyArg_ParsTuple(args, "O", &seq)) return 0; To do something useful with seq, you might want to look at the PySequence_* function family in the Python/C API Reference Manual (s. http://www.python.org/doc/current/api/sequence.html) HTH, Vincent Wehren | | chris From igor at tyumbit.ru Mon Nov 10 08:59:36 2003 From: igor at tyumbit.ru (Igor Prischepoff) Date: Mon, 10 Nov 2003 18:59:36 +0500 Subject: mysqldb and py2exe distribution Message-ID: <167180984391.20031110185936@tyumbit.ru> Hi, Sorry if it was discussed somewhere , i've checked topics on mysqldb forum and posted my question there - no luck. So, this list is my last hope. Here is my problem: I've compiled python app with py2exe and mysqldb for easy setup on customer's computers. 'setup.py py2exe --packages encodings,MySQLdb' Everything is fine except that my application can work with mysql db _ONLY_ if on client computer exists catalog c:\mysql\share\charsets\(with some *.conf files inside). If those catalogs don't exist then app crashes. I guess it's because target mysql server is set up to use 'cp1251' (cyrillyc) codepage. 1) And what if there is no way to copy those files to client computer? 2) What if i like to run from CD only (ideally) ? 3) Or is there a way to place c:\mysql\share\charsets\*.* to application install catalog c:\program files\myapp\ ? Someone have an expierience in distributing mysql apps compiled with py2exe ? Could you post listing of distributed files or some hints? I don't like an idea to install mysql client on customer computer. Anyway those charset files just plain text! my environment: win2k,python2.2,mysql-python-0.9.2.win32-py, Thanks for help. -- Igor. mailto:igor at tyumbit.ru From exarkun at intarweb.us Fri Nov 7 10:19:28 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 7 Nov 2003 10:19:28 -0500 Subject: System Clock In-Reply-To: References: <9SBqb.8942$R13.490724@ursa-nb00s0.nbnet.nb.ca> Message-ID: <20031107151928.GA28176@intarweb.us> On Thu, Nov 06, 2003 at 10:47:19PM -0500, Terry Reedy wrote: > > [snip] > > (Oddly, I also get this: > >>> tc()-tc(); tc()-tc() > -2.84952814126882e-005 > -1.4247640820030938e-005 > which I have not figured out yet) > I think this indicates there is more than one cost path down into the timing machinery. Consider: >>> time()-time();time()-time();time()-time();time()-time();time()-time();time()-time();time()-time();time()-time();time()-time();time()-time() -3.9339065551757812e-06 -9.5367431640625e-07 0.0 -1.0728836059570312e-06 -1.0728836059570312e-06 -1.0728836059570312e-06 -9.5367431640625e-07 -9.5367431640625e-07 0.0 0.0 It appears to me as though making subsequent calls to time.time() in rapid succession allows one to exploit an optimization somewhere. Perhaps some hardware-level caching? Jp From peter at engcorp.com Tue Nov 25 11:57:21 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 25 Nov 2003 11:57:21 -0500 Subject: sleep() function, perhaps. References: <3FC37C61.1000209@Linux.ie> Message-ID: <3FC389F1.15E4D2DB@engcorp.com> Padraig at Linux.ie wrote: > > Ryan Spencer wrote: > > Hello Everyone, > > > > I want to have a row of periods, separated by small, say, .5 second > > intervals between each other. Thus, for example, making it have the > > appearance of a progress "bar". > > You've got the answer for dots, here's a spinner in case it's useful: > > import sys, time > > spinner="|/-\\" > pos=0 > > while 1: > sys.stdout.write("\r"+spinner[pos]) > sys.stdout.flush() > time.sleep(.5) > pos+=1 > pos%=4 And a quicky OO version for kicks (untested): class Spinner: CHARS = r"|/-\" def __init__(self, stream=sys.stdout): self.index = 0 self.stream = stream def spin(self): self.stream.write('\r' + self.CHARS[self.index]) self.stream.flush() self.index = (self.index + 1) % len(CHARS) spin = Spinner() while 1: spin.spin() time.sleep(0.5) -Peter From peter at engcorp.com Sat Nov 1 10:18:10 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 01 Nov 2003 10:18:10 -0500 Subject: ANN: pyfromc - Python from C++ and vice versa References: <3fa3488c.12101640@news.t-online.de> <3FA3B325.1491D228@engcorp.com> <3fa3c4e1.43930000@news.t-online.de> Message-ID: <3FA3CEB2.AE8B6142@engcorp.com> Gerson Kurz wrote: > > Peter Hansen wrote: > > >Gerson, why not browse http://www.opensource.org/licenses/ > > I find "licensing" example code, at best, ridiculous. And that's > basically all it is: it is an example, a starting point - it contains > only one method "test". Please. It took some work to figure out how to > exactly put the pieces together - but now that it works its almost > trivial. Sorry, I didn't notice that you had said it was example code. Sounded like there was a lot more to it than that... -Peter From adalke at mindspring.com Thu Nov 13 18:16:50 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 13 Nov 2003 23:16:50 GMT Subject: Palindrome References: <20031112223135.29045.00000109@mb-m12.aol.com> Message-ID: Gerrit Holl > Are you looking for: > 20:58:42:232:0 >>> def ispalindrome(s): > 20:58:42:232:0 ... return s == s[::-1] No. The OP wanted to strip special characters and normalize case, so that A man, a plan, a canal -- Panama! would be allowed as a palindrome. Andrew dalke at dalkescientific.com From poyol at hotmail.com Fri Nov 28 03:29:07 2003 From: poyol at hotmail.com (OPQ) Date: 28 Nov 2003 00:29:07 -0800 Subject: [ANNOUNCE] Python network security tools: Pcapy, Impacket, InlineEgg References: Message-ID: CORE Security Technologies wrote in message news:... For linux-only platform, scapy (made by p. biondi) may also be of interest: http://www.cartel-securite.fr/pbiondi/projects/scapy.html ---OPQ From francisgavila at yahoo.com Sun Nov 9 13:35:41 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 9 Nov 2003 13:35:41 -0500 Subject: dictionary lookup table? References: Message-ID: "John Mudd" wrote in message news:mailman.581.1068399182.702.python-list at python.org... > I must be missing something here. It's clearly faster to lookup an item > directly in a dictionary than to scan through a list. So when I have a > large lookup table I always load it in the form of a dictionary. But it > seems a waste. I end up having to assign an artificial value to the > dictionary entry. Below I assign the value "None" to each dictionary > entry. > > Is there a better way? I feel like I'm misusing the dictionary. You ARE misusing both dictionaries AND lists, but not in the way you think: > dict = {} > list = [] These lines obliterates the dict() and list() builtins! Use different names, like D, mydict, etc. Now, to answer your question: I don't think you are abusing the dictionary at all, but if you're using Python 2.3, you can use the set module, which more closely matches the semantics of your problem. However, as of now the set module is implemented with dictionaries anyway, so I don't see that you gain much. (I think set will be implemented as an extension later, though.) Further, don't be too worried about "waste", because there's very little waste here. First of all, None is a singleton (hence the Python idiom "something is None"), so there's no danger of Python possibly making multiple copies of the item mapped to your key. Secondly, dictionaries are containers, like lists, so the key and item of a dictionary are just references to an object. You end up with (at most) twice as many references in a dictionary as an equivalent list, but references are little more than dressed-up pointers, and very cheap to store and use. So what are you worried about? Finally, if you're worried about waste, why are you using Python? ;) Python saves your development time in exchange for the far cheaper resource of memory and processor power. If you want some more speed (although it looks plenty fast to me), try experimenting with some other dictionary idioms. Try "if key in dictionary", "try: D[key]; except: print 'not found'", etc. But I think you'd be wasting more time than you'd gain, especially since optimization obsessions can be hard to shake.... -- Francis Avila From tjreedy at udel.edu Tue Nov 11 12:35:13 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Nov 2003 12:35:13 -0500 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: <7N6dnUz1P9CKZTOiRVn-hQ@comcast.com> Message-ID: "Edward K. Ream" wrote in message news:vqvuscjbj6lmd4 at corp.supernews.com... > > Such a request is *NOT* a legitimate 'anti-junk-mail' measure. > > Yes, it is. Your request is unnecessary to the purported purpose and, to at least three people, obnoxious. Furthermore, I believe universal implementation of that system would be terrible, both socially and technically. > If you aren't willing to take 20 sec. to talk to me, I spent much more than 20 seconds writing you a polite note for your benefit. You are the one refusing to take even 5 seconds to look it. Or to use a decent, unobstrusive or miminal imposition filtering system. > then I'm not willing to talk to you. Bye. That is your right, and mine, and probably our mutual loss is some respects. ... > Edward K. Ream email: edreamleo at charter.net By posting your email address over and over, you are still inviting responses that you will not read. Not nice. At least warn people that they will have to fire up a browser a few days later and beg you to read their original message. Or simply give the URL of your 'correspondant registration' service and suggest that people register (or not) *before* writing. Terry J. Reedy From edreamleo at charter.net Sat Nov 8 11:26:17 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Sat, 8 Nov 2003 10:26:17 -0600 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: Message-ID: Conclusion All the power of Leo derives directly from the power, flexibility and dynamism of Python. But making structure explicit as Leo outlines do adds an important new dimension, literally and figuratively, to Python. Moreover, Leo's Find/Change dialog creates a new environment from which to run Python scripts. At long last the full power of the unification of code and data is becoming apparent. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From jepler at unpythonic.net Sun Nov 9 09:25:09 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 9 Nov 2003 08:25:09 -0600 Subject: Tkinter: spinbox command and percent substitutions In-Reply-To: References: Message-ID: <20031109142502.GA2242@unpythonic.net> You'll have to arrange for the Tk -command to contain %x and %y substitutions, and similarly for the -validatecommand. The sequence would look something like this: tkcmd = self.register(self.sbcmd) self.sb = Tkinter.Spinbox(self, command=(tkcmd, "%x", "%y")) ... def sbcmd(self, x, y): print x, y I don't have 8.4, so I can't test this out exactly. Jeff From aleaxit at yahoo.com Thu Nov 6 02:27:01 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 06 Nov 2003 07:27:01 GMT Subject: PEP 322: Reverse Iteration (REVISED, please comment) References: <5d83790c.0310281022.6264aa16@posting.google.com> <3f9ec63f$1@brateggebdc5.br-automation.co.at> <2259b0e2.0311052259.897e3ce@posting.google.com> Message-ID: <9Jmqb.422270$R32.13993451@news2.tin.it> Michele Simionato wrote: ... > So, only summing strings is disallowed, all the rest is allowed, but > there can be performance traps, for instance in summing lists. So, if Right. > 'sum' is only good at summing numbers, why this is not enforced? How? Sure, we could specialcase lists and tuples and array.array's and Numeric.array's and ... -- but that wouldn't really be right either: e.g. with tuples you can't do much better _easily_ (turning each into a list and doing a loop of extend isn't "easily" -- it's only warranted in some cases). Basically, sum is fine whenever the alternative is reduce(operator.__add__ ... or a loop of for item in sequence: result = result + item since it's defined to have exactly that semantics. Problem is mainly with cases in which we'd rather do for item in sequence: result += item which is slightly different semantics when result is mutable; or more specialized cases such as ''.join(sequence). > We are forbidden to sum strings, but then for the same reason we > should be forbidden to sum lists: there is some inconsistency here ... > care to explain the rationale for 'sum' again ? sum is basically to sum numbers. But in Python there's no way to tell precisely what IS "a number". We've special-cased strings because we _know_ people desperately want to sum bunches of them all of the time -- my original approach was to have sum detect the case and delegate to ''.join, but Guido thought that weakened sum's specificity to numbers and had me forbid it instead. I've recently proposed going for the performance trap by redefining the semantics as a loop of += -- but Guido isn't happy with that (user-visible change, some way or other, at least for sufficiently weird user-coded objects). I've also proposed adding optional abstract baseclasses similar to basestring to give various spots in Python a chance to detect "this user type is meant to be a number [it inherits from basenumber] / a sequence [from basesequence] / and so on", but again I've mostly seen reluctance about this on python-dev. So the issue is a bit in the air (for Python 2.4). Alex From stephendotboulet at motorola_._com Wed Nov 12 11:33:05 2003 From: stephendotboulet at motorola_._com (Stephen Boulet) Date: Wed, 12 Nov 2003 10:33:05 -0600 Subject: Leo + Python: the ultimate scripting tool: gui issues In-Reply-To: References: Message-ID: I see that allout.el is supplied with xemacs for windows. How does it get activated? Stephen Alexander Schmolck wrote: > Have you come across allout.el and speedbar.el (a seperate tree browser > window)? Emacs has several outlining facilities amongst which allout is the > best IMO (I already use it for some of my python code) -- integrated with > speedbar this would supply quite a bit of the core functionality that leo > offers (plus, of course plenty additional functionality, most importantly good > editing and search facilities). > > 'as From philh at invalid.email.address Fri Nov 7 13:48:25 2003 From: philh at invalid.email.address (phil hunt) Date: Fri, 7 Nov 2003 18:48:25 +0000 Subject: Assembler Parser/Lexer in Python References: <3fabc59e.42407448@news.dsl.pipex.com> Message-ID: On Thu, 06 Nov 2003 22:06:45 GMT, Simon Foster wrote: > >Anyone have any experience or pointers to how to go about creating >a parser lexer for assemble in Python. I was thinking of using PLY >but wonder whether it's too heavyweight for what I want. Anyone have >any thoughts? I've found SPARK useful: -- "It's easier to find people online who openly support the KKK than people who openly support the RIAA" -- comment on Wikipedia (Email: , but first subtract 275 and reverse the last two letters). From 3seasA at Tthreeseas.DOT.not Mon Nov 10 17:55:33 2003 From: 3seasA at Tthreeseas.DOT.not (3seas) Date: Mon, 10 Nov 2003 22:55:33 GMT Subject: "Autocoding Reloaded" (was Re: Matrix - Metaphors, Analogies and the REAL References: <3FB008DB.A4F3E01@engcorp.com> Message-ID: Peter Hansen wrote: > 3seas wrote: >> >> the project is in python code >> http://freshmeat.net/projects/victor1/ Actually the most up to date code is not teh archive but what you get by doing a wget on threeseas.net/vic/ excluding the .zip files. But then that might be what you did. As to the code: I wrote the IQ and ID command (a small part by another, who I sponsored for about a month to work on AROS during last summer. That small part we integrated into IQ to create teh ID command which also has a user file for adding tests for ID to use.) As to the Rest, that was produce by another who I hired thru rentacoder.com to produce from the specifications I wrote. There is still one command to write KE and the integration IQ and ID into the VIC. Though I do believe it is useful to have these two able to function also as stand alones. I do however plan to replace the html based help file for the AI,PK,OI,and SF commands with their IQ parsed on the fly help file. As I believe I can do this regardless of my OOP understanding level. As to Python OOP I am not that learned on it such that I can yet go thru the code I hired written to correct errors and make overall easier to use modifications. I did however markup all of the code to be IQ parseable and created a source.iq file that IQ can process to pares ALL the source. I believe the command would be: python ./IQ-ID/iq.py -k source.iq . . (on linux) from the directory where the main.py (main source) is. this while show you all the unique keys contained in the source. but using pattern matching arguements and without the -k option you can output the contents of keys that match. The full VIC will be able to set in motion dynamic automations, from simple to complex of any number of automation types, from simple user defined automations to more complex code generation AND compiling And Excution of generated code. Autocoding is just one thing a general automation tool can do and for such to be possible the underlying code fragnment database or vocabulary must be built. MS is going a step further by teh whole Common Language Infrastructure bit by unifying many programming languages thru Common Intermediate Language. I have no doubt there have been and continue to be arguements against this or that part of the VIC but no where will you find the integrated configuration of all the parts in a manner that provides such versatility as the VIC will. The command line interface is but just the like in teh history of computing, before the GUI came along. I know how to use a point and click interface to fully access the VIC, but that is down teh road and hopefully by the time we get there there will be more of a standard cross platform GUI library to use. Its not the objective to re-invent anything but rather to make the use and reuse of many things possible, including the dynamic reuse of code fragments to generate more complex code. And its not code predjuice either though to generate python thru it would require an indentation loop to keep track of proper indentation. I have done the research, wrote achievable specifications and code, put money into it paying a coder to write python code for it etc.... And I have even placed it under the GPL. As to those who have said to me in the past that my communication suck, It sure did seem to suck when I was communicating to a code writer.... Spamming my mailboxes..... that is just not right and really does show the nastiness of some playing king of the hill in this newsgroup. and if such acts are going to create a grading curve, it should be clear there will be lessor acts of negitivity towards me or the project than that of trashing out my mailbozes with absolutely unrelated viral spam. -- 3 S.E.A.S -- Virtual Interaction Configuration (VIC) Changing how we preceive and use computers email @ translate not to net, remove capitol letters, one . web @ http://threeseas.net From mabus at operamail.com Sun Nov 16 19:39:13 2003 From: mabus at operamail.com (sashan) Date: Mon, 17 Nov 2003 13:39:13 +1300 Subject: xml.dom - reading from a file Message-ID: Is the way to use DOM for an xml file as follows: 1) Read the file into a string 2) Call xml.dom.minidom.parseString(string) From scott_list at mischko.com Sat Nov 8 11:55:22 2003 From: scott_list at mischko.com (Scott Chapman) Date: Sat, 8 Nov 2003 08:55:22 -0800 Subject: Can I hook a "file" to a python script? In-Reply-To: <3hru71-7p3.ln1@valpo.de> References: <3hru71-7p3.ln1@valpo.de> Message-ID: <200311080855.22391.scott_list@mischko.com> On Saturday 08 November 2003 02:01, Mathias Waack wrote: > Scott Chapman wrote: > > I'd like a "file" on the Linux box to actually be the input and > > output > > of a Python script. Anything written to the file would be sent to > > a database and anything read from the file would come from the > > database. I know how to do the database end of this but I'm not > > sure if a script > > can be hooked to a "file" transparently. The script would probably > > have to be run as a daemon. I doubt there's enough magic in the > > Linux world to make it so that a read/write would actually launch > > the script. That'd be Ok. > > The solution is very easy. There are at least two ways. First the > easier one: create a named pipe using mkfifo(1) and start your > python script which should attach itself to one end of the pipe. The > second solution is bit more complex: you need a new device. The > device driver will only forward all input to your user space daemon > or read all output from it. This way your python script can be > started automagically each time someone accesses the device special > file. I understand named pipes to be "one-way" only. Is that correct? Scott From rodrigob at elo.utfsm.cl Wed Nov 12 19:15:23 2003 From: rodrigob at elo.utfsm.cl (Rodrigo Benenson) Date: Wed, 12 Nov 2003 21:15:23 -0300 Subject: looking for a name for a python SIP phone References: Message-ID: <3fb2c9b4$1_1@nova.entelchile.net> Were do it will be published ? I had from some time the idea to implement a free open source multiplatform Spyke system (www.spyke.com), using an already existing Distributed Hash Table code in python (Khashmir). The idea is to get a free decentralized internet telephony system, with a very low cost of devellopment .... Which voice encoding do you use ? Hmm, I have no cultural reference for the Monty Python show, but.... let me think.... PyPhone, the trivial one. Voice over Python: Voopy. PyTalk. Telython, the python telephone. just some, proposal, not very creative, but, something is something. RodrigoB. "Anthony Baxter" escribi? en el mensaje news:mailman.685.1068679064.702.python-list at python.org... > > So I've implemented a first cut at a pure-Python SIP (VoIP) phone, and > now I need a name for it. Off the top of my head, I can't think of any > Monty Python sketches involving a telephone - can anyone else? Other names? > > (As an aside, it's impressive (to me) that this can be done in python - > a bit of a 'bah' to those people who think that an interpreted language > is "too slow" for complex tasks) > > Yes, it will be released as open source. > > Anthony > From anton at vredegoor.doge.nl Sat Nov 8 08:36:19 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 08 Nov 2003 14:36:19 +0100 Subject: reduce()--what is it good for? References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> Message-ID: Alex Martelli wrote: >Of course you can memoize any pure function of hashable args. But >memoizing a recursive implementation of factorial has a nice property, >shared by other int functions implemented recursively in terms of their >values on other ints, such as fibonacci numbers: the memoization you do for >any value _helps_ the speed of computation for other values. This nice >property doesn't apply to non-recursive implementations. Maybe we need a better example because it is possible to use reduce on a function which has side effects. Anton. class _Memo: biggest = 1 facdict = {0 : 1, 1 : 1} def fac(n): def mymul(x,y): res = x*y _Memo.facdict[y] = res _Memo.biggest = y return res def factorial(x): b = _Memo.biggest if x > b: return reduce(mymul, xrange(b+1,x+1), b) return _Memo.facdict[x] return factorial(n) def test(): print fac(5) if __name__=='__main__': test() From michele.simionato at poste.it Wed Nov 19 13:28:27 2003 From: michele.simionato at poste.it (Michele Simionato) Date: 19 Nov 2003 10:28:27 -0800 Subject: Callable generators (PEP 288: Generator Attributes, again) References: <55688f89.0311180211.7ab1bc30@posting.google.com> <2259b0e2.0311180616.5980fabc@posting.google.com> Message-ID: <95aa1afa.0311191028.77aa02a3@posting.google.com> "Francis Avila" wrote in message news:... > I'm suggesting the PEP's functionality, not its syntax and semantics. My > contention is that the PEP regards generators as too class-like, when they > are more naturally considered as function-like. > > For example, your iterator class/instance would look like this: > > def iterator(x=1)(x): > yield x > yield x > > print iterator.next() # -> 1 > print iterator(5) # -> 5 > > The local name "x" is updated (according to the second parameter list in the > function definition) right after the yield of the previous call when > iterator is called, behaving like a state-persistent callable function. If > it's just "nexted", it behaves like a plain old iterator. I see what you mean, now. Still, the notation is confusing, since I do think an iterator as something which it obtained by "instantiating" a generator. On the other hand, your iterator(5) would not be a newly "instantiated" iterator, but the same iterator with a different parameter x. So, you would need a different syntax, as for instance iterator[5]. Still, I do think this would be confusing. The class solution would be more verbose but clearer. > Here's an efficient reversable generator: > > def count (n=0)(step=1): > while True: > yield n > n += step Yeah, it is lightweight, but a class derived from "Iterator" would be only one line longer, so I am not convinced. Also, people would start thinking that you can define regular functions with two sets of arguments, and this would generate a mess ... Michele From matt at satbp.com Fri Nov 28 16:00:23 2003 From: matt at satbp.com (Matthew A. Berglund) Date: Fri, 28 Nov 2003 21:00:23 GMT Subject: Binary number manipulation Message-ID: <20031128160051.37a304df.matt@satbp.com> Hello All! I am very new to python so I am working on some ass-umptions which may be incorrect (please forgive me). I am working on a problem that requires me to take 2 decimal integers, each of which represents half of a word. I need to slap these things together and get out another decimal integer. A couple of questions: 1. Is there a way to typecast a variable as a binary? 2. If 1 is no, does that mean that I need to do all the manipulation in some icky string format and then go back? I do see the bit-wise operations available and this looks like I need to simply perform these on my integers? Can it really be that simple? Thanks, Matt From 3seasA at Tthreeseas.DOT.not Tue Nov 11 11:37:56 2003 From: 3seasA at Tthreeseas.DOT.not (3seas) Date: Tue, 11 Nov 2003 16:37:56 GMT Subject: Matrix - Metaphors, Analogies and the REAL References: Message-ID: Gerhard H?ring wrote: > > Obviously, (s)he's not ready yet to be freed from the matrix. > > -- Gerhard There is another branch to this thread where the python code is talked about, should you be interested in that or helping with the project. I do have pet trolls and recommend you do not feed them. -- 3 S.E.A.S -- Virtual Interaction Configuration (VIC) Changing how we preceive and use computers email @ translate not to net, remove capitol letters, one . web @ http://threeseas.net From try_vanevery_at_mycompanyname at yahoo.com Sat Nov 15 01:09:38 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Fri, 14 Nov 2003 22:09:38 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> <84fc4588.0311140319.3778de15@posting.google.com> Message-ID: "Paul Foley" wrote in message news:m27k22mjwj.fsf at mycroft.actrix.gen.nz... > On Fri, 14 Nov 2003 17:51:49 -0800, Brandon J Van Every wrote: > > if it > > was printed 3 years ago and someone else printed something 1 year ago, I'm > > going to go with the latter. > > That's a pretty dumb policy, unless it's about something that's > actually likely to be out of date in 3 years. I'm a Windoze game developer. DirectX is *always* out of date, every year. Not that I've yet deigned to buy a book on it, but I have browsed the shelves occasionally. And I do note that several versions of Python have been shipped in the past 3 years, most recently 2.3. > Which is unlikely for anything of real value Prejudiced nonsense on your part. > (XML books are out of date before the ink is dry, of course). As are so many things in computer programming. Throwaway APIs are de rigeur. > When it has to do with computers, the best way to get up-to-date > information on the latest thing is likely to be to buy 30+ year old > Lisp books :-) You've gotta be kidding me. Even 12 years ago, "Computer Graphics: Principles and Practice" didn't teach texture mapping. Along came DOOM. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "We live in a world of very bright people building crappy software with total shit for tools and process." - Ed Mckenzie From rstephens at vectron.com Sun Nov 30 20:40:54 2003 From: rstephens at vectron.com (Ron Stephens) Date: 30 Nov 2003 17:40:54 -0800 Subject: Python Learning Foundation Message-ID: The newly rechristened Python Learning Foundation is a web site dedicated to the assistance of people learning the Python programming language. Features include: 1. Daily lists of new and recent Python-related web articles, Sourceforge projects, and Vaults of Parnassus listings. These are generated using Hans Nowak's Python web spider, mygale.py, and are automatically updated each day. (You can visit Han's interesting blog at zephyrfalcon ) 2. Now, there are also daily postings of new and recent web articles, Sourceforge projects and etcetera for four additional categories, Zope, Jython, Tkinter, and wxPython, as well as historical listings of web articles on these subjects. Other specific topics can be covered regularly upon user request. 3. Links to 76 online tutorials about Python and Python related subjects. 4. More than 28 reviews of books about Python. There are many other topics and features covered in the web site, and, of course, the best is yet to come. Please visit the Python Learning Foundation. From pmaupin at speakeasy.net Sun Nov 23 22:52:13 2003 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 23 Nov 2003 19:52:13 -0800 Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> <7xwu9svyny.fsf@ruckus.brouhaha.com> <7xvfpcowjt.fsf@ruckus.brouhaha.com> <653b7547.0311222346.b4d9e98@posting.google.com> Message-ID: <653b7547.0311231952.5abe71ab@posting.google.com> Alexander Schmolck wrote: > Well Stallman says the above wrong, have a look at how clisp became GPL. I think I was pretty upfront about how my opinion contradicts what Stallman says. My understanding is that clisp became GPL because Stallman claimed that its use of readline forced the author to release it under the GPL, and since the author was basically making free software anyway, and more concerned about the software than the license, he agreed to change the license fairly readily. Likewise, I believe at least one other software package (the non-GPLed version of Aladdin Ghostscript) has stopped using readline because of Stallman's position. As I mentioned in my earlier email, IMO the fact that nobody has gone to court with the FSF over readline has more to do with other factors than with the validity of the FSF's legal position on this issue. For another viewpoint, you might want to look at these two PDFs (which were written by the OSI's lawyer): http://www.rosenlaw.com/html/GPL.PDF http://www.rosenlaw.com/html/GL18.pdf Pat From bgailer at alum.rpi.edu Fri Nov 21 18:37:37 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 21 Nov 2003 16:37:37 -0700 Subject: Frustration with Boa Constructor In-Reply-To: References: <7T02VNBM37943.8988541667@Gilgamesh-frog.org> Message-ID: <6.0.0.22.0.20031121163428.0203f0d8@mail.mric.net> This is the 3rd time I've downloaded, installed and tried Boa. Each time I meet with one frustration or another. This time I'm trying to go thru the Getting Started, and find numerous places that the tutorial does not agree with the reality or I try something and it does not work. Has anyone had success with Boa Constructor? If so how did you learn it? The tutorial clearly is not the way I can learn it. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.538 / Virus Database: 333 - Release Date: 11/10/2003 From mis6 at pitt.edu Sun Nov 2 12:46:18 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 2 Nov 2003 09:46:18 -0800 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> <1589qvcdv9bni5fr8opactkgj9n5hecpj7@4ax.com> Message-ID: <2259b0e2.0311020946.2003322@posting.google.com> Stephen Horne wrote in message news:... > > Superfluid helium is a macroscopic phenomenon - it may be explained in > terms of QM effects, but that doesn't make it a quantum effect in > itself any more than more everyday macroscopic effects (which can also > be described in QM terms). If superfluid helium is your only clue, it > will tell you no more about quantum effects than e.g. lightening tells > you about the properties of an electron. It is true that superfluidity is described by an effective field theory which is not directly related to the properties of a single electron; but still it is a (non-relativistic) *quantum* field theory, so the fact that it is "quantum" is relevant. Things are different in ferromagnets, for instance, where a lot of properties can be derived from classical very unrealistic models (such as the Ising model) due to the universality property. But not ALL properties. Anyway, I do understand that you have in mind quantum effects related to the wave function collapse, and I don't think superfluidity is of big help on these issues, so I must agree with you on that point. Unfortunately :-( > It was quite a revelation to discover that the physics of the cosmos > were actually the same physics we experience on the ground. Worth repeating. > The centre of a black hole exists, in a sense, but we can never > observe it because it is inside the event horizon, and as time itself > stops at the event horizon (from the perspective of any outside > observer) there is even good reason for claiming that the space inside > the event horizon doesn't exist. > > >Michele is a better one for this topic. It is interesting to notice that the region *inside* the event horizon is a perfectly physical region and can be relatively well understood. For instance, an observer can fall inside the horizon and live relatively well if the black hole is large enough and the tidal forces are small enough; we can perfectly compute how much time s/he will live and what s/he will see. It is true that external observers cannot see the poor guy enter in the black hole, because of the infinite time dilatation, but this does not mean that the guy does not enter in the black hole, according to its proper time. There is only one point (of a set of points if the black hole is rotating) which we cannot understand, i.e. the singularity. Near the singularities general relativity fails and we don't know what happens. It is interesting to notice that Hawking proved that GR necessarely implies singularities: this means that we know for sure that GR is certainly not a complete theory of Physics ;) > I read a book about string and brane theory some time ago - I guess > possibly the same one, though it has vanished into book-borrowing > space as all the best books do so I can't tell you the title. > > Lots of theory about possible geometries and topologies of many > dimensional space-time and how they could change from one another. > They didn't address the issue of how they could change at all, given > that time existed within the geometry rather than outside of it, and > for that among other reasons my impression was that it was a > fascinating read that nevertheless left me with no more clue than I > had to start with. That's normal ;) > I would at least have appreciated a definition of supersymmetry, > rather than the usual 'its too abstract for your puny mind' copout. Supersymmetry is a much simpler concept than branes or strings: unfortunately it is still too abstract to explain, unless one has expertise in quantum field theory :-( Modern physics is so difficult than you can happily spend your entire life on a subject such as string theory and never understand it. That's life ! Michele Simionato From zunbeltz at wm.lc.ehu.es.XXX Fri Nov 21 06:20:13 2003 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 21 Nov 2003 12:20:13 +0100 Subject: plataform dependent code References: Message-ID: Rene Pijlman writes: > import sys > if sys.platform == 'win32': > pass > elif sys.platform == 'linux2': > pass Thanks. (so odbious) > > >I can't find any information about this in the net. > > You've got to be kidding. > no I've googled (is it a verb? :) platform dependent python in (alson in complang.python ) and i haven't been pointed to the library referend. I didn't search in the reference :( ,next time i'll not forgeto to search there Zunbeltz > -- > Ren? Pijlman -- Remove XXX from email: zunbeltz at wm.lc.ehu.esXXX From see_signature__ at hotmail.com Tue Nov 18 03:09:27 2003 From: see_signature__ at hotmail.com (Georgy Pruss) Date: Tue, 18 Nov 2003 08:09:27 GMT Subject: Too much builtins (was Re: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com><653b7547.0311121826.65b6b2d4@posting.google.com> Message-ID: "Andrew Dalke" wrote in message news:lJjub.4602$sb4.2551 at newsread2.news.pas.earthlink.net... | Georgy Pruss: | > Maybe, it's worth to have str(x,8) and str(x,16) instead of oct(x) and | hex(x) | > and make str() a true inverse function to int()? | | What then are the results of | str(30+44j, 16) | str(3.1415926, 8) | str([9, 8, 7], 8) | str("A", 16) | str({"A": 20}, 16) | ? | | Andrew | dalke at dalkescientific.com I guess, the same as for hex(30+44j) oct(3.1415926) oct([9, 8, 7]) hex("A") hex({"A": 20}) G-: From bokr at oz.net Thu Nov 6 11:27:14 2003 From: bokr at oz.net (Bengt Richter) Date: 6 Nov 2003 16:27:14 GMT Subject: prePEP: Decimal data type References: Message-ID: On Thu, 06 Nov 2003 08:22:15 GMT, Alex Martelli wrote: >Tim Peters wrote: > ... >> You do need to explicitly round (if desired) after * and /. Because of >> the high value attached to 100% conformance to imposed standards in >> accounting apps, I think it's a good thing that you're forced to round >> explicitly when the result of a calculation can't be represented exactly >> in the mandated format -- those are exactly the places where your app will >> fail to meet the requirements, so it's good to be aware of them. > >European Union directives (adopted as laws by member states) mandate >the rounding procedure to be used in computations involving Euros (round >to closest Eurocent, always round up on half-Eurocent results); they very >explicitly mention that this may give a 1-Eurocent discrepancy compared >to "exact" arithmetic, and give examples; they establish that such a 1-cent >discrepancy that comes from following exactly the prescribed rules is NOT >legal cause for any lawsuit whatsoever; they earnestly recommend that all >computing equipment and programs follow these same rules to avoid the huge >headaches that would result in trying to reconcile accounts otherwise. > >Thus, for most accounting programs intended to run within the EU (not just >in Euros: these provisions also apply to the other non-Euro currencies, as >far as EU law is concerned), I do NOT think it would be a good thing for >the programmer to have to remember to round explicitly -- the legal mandate >is about rounding rules and it's quite easy to avoid the "fail to meet the >requirements", as they seem designed to be easy to meet. I wonder how they deal with compound interest. E.g., may a contract for a loan express interest as mathematically continuous between payments? In that case does rounding from mathematically exact values occur only at payment times? Is the rounding only applied to the payment amount, so that the princal is decreased by the exact quantized payment, but the balance retains exactness? Or is requantization of all values mandated at each transaction? Is each step in a sum a separate transaction? What about the rules for pre-tax-calculation subtotals vs accumulating actual receipt stated tax amounts? I remember as a kid bugging store clerks to sell me two candies separately to stay under the minimum taxable price threshold twice rather than exceed it once and pay the extra penny ;-) ISTM these things are 'way beyond the concern of a math package per se, yet a math package that is intended to support programming of a business/rule/law-abiding application would have to make it easy to express in program source what the unambiguous intent is, and not have the math be playing unexpected tricks with the values. IMO to have rounding/precision applied sub-expression by subexpression is a recipe for unpleasant surprises. It would be like applying snap-to-grid rules in a drawing package at every internal intermediate math subexpression evaluation step of the implementation. BTW, does this mean expressions can't be run through optimizers that might e.g., hoist a subexpression out of a loop and thereby change how many times a rounding effect happens? What about advice to eager programmers who want to do the same optimization by hand? Must they be advised? ISTM programmers will not want to face these issues in internal implementation, and will instead turn up precision to close-enough-to-exact, and then just round when they print or interact with databases etc., ajusting ad hoc to correct infractions of rules revealed in testing. Chances are that's what they would wind up doing anyway, using step-wise-rounding-enforcing math. > >Whether Decimal itself allows an optional rounding-policy (including of >course "no rounding" as a possibility) is one issue (I guess that might >violate some ANSI or IEEE standard...?) but I most surely do want to be >able to use such policies in whatever arithmetic type underlies Money -- >so I hope Decimal is at least designed so that _subclasses_ can easily >provide such customized rounding (e.g., feature-testing for a __round__ >specialmethod, not defined in the baseclass Decimal if need be, but >offering the needed hook for subclasses to add the functionality). > Agreed -- that something is needed to make defining and coding special rules on top of the math base easy. I was thinking subclassing too. OTOH, casting about for the meaning of "context" in this PEP context (;-), I think you could also develop an implementation convention around a separate Context class, that would provide instances as customized attribute-name-space contexts, using __[gs]etattr__ overrides and/or properties, maybe with a metaclass to make parameterized customization easy to write. Using this sort of thing, you could cause property/attribute retrieval to return rule-enforcing wrapper objects with money quantities inside, and any statements and math expressions written in terms of those would be defined by the wrappers, and assignments would be defined by the context object whose attribute space was being assigned to. So long as people are willing write stuff like, e.g., e.total and e.tax for total and tax values they want operated upon subject to, e.g., custom Euro rules, IWT that could work. But I think it's hard to anticipate what will work out slick, so some alternative implementation sketches for a realistic use case would help clarify. Better to concentrate on powerful orthogonal primitives and test them against a reference problem than provide too much of what amounts to speculative app macros, IMO. Regards, Bengt Richter From fredrik at pythonware.com Tue Nov 18 11:01:55 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Nov 2003 17:01:55 +0100 Subject: for what are for/while else clauses References: <1069091155.3fb909533f7c8@mcherm.com> Message-ID: Michael Chermside wrote: > According to this experiment, the only way to get "executed else clause" > to print is to set exitViaBreak to True. So I really don't understand what > you are claiming. Seems to me that the execution of the else does NOT > depend on the status of the loop condition at exit. That's not what your program shows, though: if you set "exitViaBreak" to true, your program sets the loop condition to false *before* it enters the loop. In other words, your experiment shows that the else clause runs when the loop condition is found to be false, and that it only runs in that case. Maybe you should read the C code, after all? Or maybe this quote from a popular python book might help: "Both the while and for statement may optionally have a trailing else clause. The statement or statements after the else execute when the loop terminates naturally (at the end of the for iterator or when the while loop condition becomes false), but not when the loop terminates prematurely (via break, return, or an exception). (the author seems to have rebooted since he wrote that, though.) From imcmeans at telus.net Sun Nov 9 04:13:03 2003 From: imcmeans at telus.net (Ian McMeans) Date: 9 Nov 2003 01:13:03 -0800 Subject: Newbie question 2 References: Message-ID: <7f9e1817.0311090113.3c8abe15@posting.google.com> That exception probably exists in some namespace, doesn't it? Try bsddb.db.DBNotFoundError [snip] > > Traceback (most recent call last): > > File "C:\Python23\phone.py", line 118, in -toplevel- > > dele(dn,dp) > > File "C:\Python23\phone.py", line 70, in dele > > except (DBNotFoundError, NameError): > > NameError: global name 'DBNotFoundError' is not defined > > > > How can it give me an error and then not allow me to enter that error in > my > > Except()? > > > > Thanks for your help! > > > > > > From jroznfgre at jngpugbjreQBGbet.cy Sun Nov 2 19:05:49 2003 From: jroznfgre at jngpugbjreQBGbet.cy (JZ) Date: Mon, 03 Nov 2003 01:05:49 +0100 Subject: round() problem? References: <334bqv4q3gi2s7mi219nl32h560r56bsih@4ax.com> <3FA59369.52006A7A@alcyone.com> Message-ID: On Sun, 02 Nov 2003 15:29:45 -0800, Erik Max Francis wrote: >Um, why would you think that's wrong? All is OK. I canceled this message but you were faster than news servers. -- JZ ICQ:6712522 From gafStopSpamData at ziplink.stopallspam.net Wed Nov 12 13:00:31 2003 From: gafStopSpamData at ziplink.stopallspam.net (G.A.) Date: Wed, 12 Nov 2003 18:00:31 GMT Subject: Check of a Page About Python References: <3FAE6776.4040609@ithcorp.com> Message-ID: On Tue, 11 Nov 2003 18:46:12 +0100, Anastasios Hatzis wrote: >Indeed my English isn't >that good, thus the information given on this page really needs a check-up. Your English looks pretty good to me. In the third sentence beginning "Many features, " there should be no comma after "features". In the same sentence,"exchangeble" needs an e after the g. First sentence, second paragraph, delete the word "especially." Second sentence, instead of "... as well as ...", split it into two sentences by ending the first part at "calls and libraries." The the second part could be "In addition, new modules are easily written in C or C++." In the bullet list, Syntax and Variety should be lower case. Most of these are the sort of typos that even native speakers make. Gary From Mike at DeleteThis.Geary.com Tue Nov 4 22:01:50 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 4 Nov 2003 19:01:50 -0800 Subject: New to Python - Compiled Language? References: Message-ID: > > ... there is a tool called py2exe that you may want to look into > > in order to bundle your program into an executable on Win32. > > (http://starship.python.net/crew/theller/py2exe/) > I think that would be very useful, thank you. :) > > When I say compiled language, I do mean a language like C++ which is > transformed into machine code by a compiler. > > I was under the impression that Python had no such compiler, and that > the end user of my programs would be required to install the Python > Interpreter. Is that true in most cases? Um, did you look at the link above? :-) Python compiles to bytecode, not to machine code. But that doesn't mean the end user needs to install a Python interpreter. > Also, can Python support Linked Lists? I believe someone said in one > of the other emails that Python doesn't support pointers. Lists are a native Python type. They're one of the things it does best--you don't need to implement linked lists yourself with pointers. -Mike From rainerd at eldwood.com Fri Nov 14 21:55:10 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Sat, 15 Nov 2003 02:55:10 GMT Subject: Python's simplicity philosophy References: <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: Douglas Alan wrote: > Q: How do I sum a sequence of numbers? In three lines: x = 0 for element in seq: x += element In two lines: > A: from operator import add > reduce(add, seq) Unless seq is empty, in which case you need this: from operator import add reduce(add, seq, 0) In one line: x = sum(seq) And that is why 'sum' is a worthwhile part of the Python standard library and 'reduce' is not: using 'sum' is significantly shorter than using a for loop, while using 'reduce' is not. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From jasvo77 at gmx.net Wed Nov 12 07:36:22 2003 From: jasvo77 at gmx.net (Jan S. Voges) Date: Wed, 12 Nov 2003 13:36:22 +0100 Subject: Problem with tkinter References: <57df7d36.0311120358.3a2676c1@posting.google.com> Message-ID: Hi! ropebu at web.de (rolf peter) wrote: >So the questions is: how to configure python to use Tk. IIRC the package "tcl-devel" isn't installed by default, but nessesary before compiling python. hth Jan From __peter__ at web.de Mon Nov 24 03:05:31 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Nov 2003 09:05:31 +0100 Subject: Newbie here... getting a count of repeated instances in a list. References: Message-ID: Amy G wrote: > I might like to know not only that they are over the threshold, but what > their actual count is. Generate a list of (domain, frequency) tuples: def filter_domains2(domains, threshold=10): result = [(d, f) for d, f in domains.iteritems() if f >= threshold] result.sort() return result And use it like so: for dom, freq in filter_domains2(domain_histogram, threshold): print dom, "->", freq Peter From aahz at pythoncraft.com Thu Nov 6 10:16:54 2003 From: aahz at pythoncraft.com (Aahz) Date: 6 Nov 2003 10:16:54 -0500 Subject: prePEP: Decimal data type References: Message-ID: In article , Alex Martelli wrote: >Tim Peters wrote: >> >> You do need to explicitly round (if desired) after * and /. Because of >> the high value attached to 100% conformance to imposed standards in >> accounting apps, I think it's a good thing that you're forced to round >> explicitly when the result of a calculation can't be represented exactly >> in the mandated format -- those are exactly the places where your app will >> fail to meet the requirements, so it's good to be aware of them. > >European Union directives (adopted as laws by member states) >mandate the rounding procedure to be used in computations involving >Euros (round to closest Eurocent, always round up on half-Eurocent >results); they very explicitly mention that this may give a 1-Eurocent >discrepancy compared to "exact" arithmetic, and give examples; they >establish that such a 1-cent discrepancy that comes from following >exactly the prescribed rules is NOT legal cause for any lawsuit >whatsoever; they earnestly recommend that all computing equipment and >programs follow these same rules to avoid the huge headaches that would >result in trying to reconcile accounts otherwise. Yeah, but *what* do you round? If you purchase five items in a store, does tax get applied to each item individually or to the total? There are lots of similar cases, so rounding must still be at least partially explicit. >Whether Decimal itself allows an optional rounding-policy (including >of course "no rounding" as a possibility) is one issue (I guess that >might violate some ANSI or IEEE standard...?) but I most surely do want >to be able to use such policies in whatever arithmetic type underlies >Money -- so I hope Decimal is at least designed so that _subclasses_ >can easily provide such customized rounding (e.g., feature-testing >for a __round__ specialmethod, not defined in the baseclass Decimal >if need be, but offering the needed hook for subclasses to add the >functionality). Once again, I suggest that you read Cowlishaw. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From peter at engcorp.com Wed Nov 5 07:54:13 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 05 Nov 2003 07:54:13 -0500 Subject: from python1.5.2 to pytghon2.2.2 References: <3ef16536.3234041@news.marelli.it> Message-ID: <3FA8F2F5.4447BFF@engcorp.com> Alberto Mantovani wrote: > > I have a lot of scripts written in python1.5.2 that I have to bring in > python2.2.2 , someone could give me some informations about the sintax > differences between the two versions?. > Are there some tools that can do this automatically? It's probably adequate to read in detail each of the What's New? pages at http://www.amk.ca/python/ . -Peter From ville.spammehardvainio at spamtut.fi Mon Nov 17 14:23:00 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 17 Nov 2003 21:23:00 +0200 Subject: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <8hfsb.7707$nz.895@newsread2.news.pas.earthlink.net> Message-ID: Donn Cave writes: > > > Well, bah! There are precious few constructs in this world that are > > > clearer and more readable than > > > > > > reduce(add, seq) > > > > I asked my non-programmer girlfriend what she thinks your construct > > does - she didn't know. She immediately understood what sum(seq) does. > not support any solution for that problem.) It's hard to > understand, just ask my girlfriend! (Great. By the way, what > does she think of list comprehensions, generators, etc.?) I was merely arguing that 'reduce' is not more readable or intuitive than 'sum', which was the argument of OP. > Go ahead and get rid of reduce, that sounds like a good idea to me. I don't think reduce should be altogether removed, it just shouldn't be in stdlib. And neither should sum, btw. > The reason though is just that it's not very useful in the context > of a language like Python, and it seems to confuse people who draw > the conclusion that Python must be some kind of functional programming > language. This will be a wake-up call on that score. I wouldn't mind Python getting more influence from functional realm, as Python seems to me to be *the* hybrid language that can pull the FP thing while still remaining practical and intuitive (and delightfully non-academic). -- Ville Vainio http://www.students.tut.fi/~vainio24 From martin at v.loewis.de Wed Nov 26 00:44:59 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 26 Nov 2003 06:44:59 +0100 Subject: Creating a Python installer in win32 References: <2XVwb.40137$Fv8.32356@twister01.bloor.is.net.cable.rogers.com> Message-ID: "martin z" writes: > Hey, all. I'll get to the point: project for class, got most of my needs > figured out, just unsure about one detail: this is a large-scale design > course, so it has to be a complete win32 app. That means a standalone > installer. I can't just say "go fetch Python, then run this .py file". > Anybody know how to set such a thing up? I recommend to use a Python binary distribution mechanism, such as installer: http://www.mcmillan-inc.com/install1.html Regards, Martin From skip at pobox.com Tue Nov 18 12:43:52 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 18 Nov 2003 11:43:52 -0600 Subject: recommendations for python web programming tools In-Reply-To: References: Message-ID: <16314.23128.746475.525530@montanaro.dyndns.org> Matthew> I looked a little at Zope, and it looks like it has a huge Matthew> learning curve. Is that true? For most people, yes. Matthew> How long would it take for a person that's written lots of CGI Matthew> scripts to get up to speed on Zope? Awhile. Skip From see_signature__ at hotmail.com Sat Nov 29 22:47:38 2003 From: see_signature__ at hotmail.com (Georgy Pruss) Date: Sun, 30 Nov 2003 03:47:38 GMT Subject: Bug in glob.glob for files w/o extentions in Windows Message-ID: On Windows XP glob.glob doesn't work properly for files without extensions. E.g. C:\Temp contains 4 files: 2 with extensions, 2 without. C:\Temp>dir /b * aaaaa.aaa bbbbb.bbb ccccc ddddd C:\Temp>dir /b *. ccccc ddddd C:\Temp>python Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import glob >>> glob.glob( '*' ) ['aaaaa.aaa', 'bbbbb.bbb', 'ccccc', 'ddddd'] >>> glob.glob( '*.' ) [] It looks like a bug. Georgy -- Georgy Pruss E-mail: 'ZDAwMTEyMHQwMzMwQGhvdG1haWwuY29t\n'.decode('base64') From testa at allos.sytes.net Fri Nov 14 14:43:56 2003 From: testa at allos.sytes.net (F.G.Testa) Date: Fri, 14 Nov 2003 17:43:56 -0200 Subject: asyncore/asynchat Message-ID: Hi! Is there a way to access a specific connected socket when using a derived asyncore.dispatcher and derived asynchat.async_chat? class AcmeServer(asyncore.dispatcher): def __init__(self, port): self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.bind(("", port)) self.listen(5) def handle_accept(self): conn, addr = self.accept() AcmeChannel(self, conn, addr) def handle_close(self): print 'Server closed' def handle_error(self): print 'Server error' How do I access the underlying list/map/array of AcmeChannel? Thank you. From ktilton at nyc.rr.com Sat Nov 1 13:01:56 2003 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Sat, 01 Nov 2003 18:01:56 GMT Subject: Explanation of macros; Haskell macros In-Reply-To: References: <87brs2tjut.fsf@memetrics.com> Message-ID: Joachim Durchholz wrote: > Lisp-the-language is a quite pretty lean-and-mean KISS language. The > stuff that's built on top of it (macros, readers, dispatch mechanisms, > etc. etc.) is neither lean nor KISS Do what I did (well, not /you/, but someone else might): don't use fun stuff until you are ready for it. Took me a couple of weeks before I started writing macros, longer before I used the MOP, longer still before nifty use of special variables and then symbol macros. etc etc. The thing is, as a developer of serious applications, I appreciate and make good use of just about everything in CL. I would so totally not like to have to reinvent all that stuff myself --I have applications to write!-- or end up with a kenny-specific environment so no one else could ever run my code. Gotta go do my first read macro... :) kenny -- http://tilton-technology.com Why Lisp? http://alu.cliki.net/RtL%20Highlight%20Film Your Project Here! http://alu.cliki.net/Industry%20Application From reply.in.the.newsgroup at my.address.is.invalid Mon Nov 17 02:27:17 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 17 Nov 2003 08:27:17 +0100 Subject: Python Database Objects (PDO) 1.2.0 Released References: Message-ID: <8rtgrvkl8vae90116u3opgdn2inias1ti4@4ax.com> Bryan J Gudorf: >PDO, an open source python module for interfacing with RDBMS (SQL >databases), has now reached 1.2.0! I just browsed the documentation, but I don't quite understand what advantages PDO offers over using DBAPI directly. A resultset object looks very similar to a cursor. What are the advantages IYO? -- Ren? Pijlman From jtanis at charter.net Tue Nov 25 19:20:08 2003 From: jtanis at charter.net (James Tanis) Date: Tue, 25 Nov 2003 19:20:08 -0500 Subject: wxPython - wx package (new style wxPython?) In-Reply-To: References: Message-ID: <1069806008.24577.31.camel@localhost.localdomain> Bah, I think they are just over-glorifying the change. In my mind, it's the same exact thing. The only real different is when you "from wxPython.wx import *" it reads everything into your local namespace which is traditionally considered not the best thing to do. I really have no idea if the "transition" when finished will remain backwards compatible, but I'm guessing from the description of the implementation that it is. BTW, In the future you may want to use a real email address so that you can receive an answer. On Tue, 2003-11-25 at 19:01, Logan wrote: > Would you recommend to use the wx package of wxPython? > > >From the documentation: > > Provides a way to drop the wx prefix from wxPython objects by > dynamically loading and renaming objects from the real wxPython > package. This is the first phase of a transition to a new style > of using wxPython. For example: > > import wx > class MyFrame(wx.Frame): > ... > > instead of: > > from wxPython.wx import * > class MyFrame(wxFrame): > ... > > What does 'this is the first phase of a transition to a new style > using wxPython' in the above mean? Will this new style become the > only way to use wxPython in future releases? > > Thanks in advance for any answers. > > -- > mailto: logan at phreaker(NoSpam).net From SEE_AT_THE_END at hotmail.com Fri Nov 7 04:37:21 2003 From: SEE_AT_THE_END at hotmail.com (Georgy Pruss) Date: Fri, 07 Nov 2003 09:37:21 GMT Subject: PEP 289: universal and existential operators References: <5d83790c.0310231158.65595858@posting.google.com> <9f76ee00.0311051257.45461381@posting.google.com> Message-ID: If it's a vote, I'm voting for 'all' and 'any'. They are short, natural and symmetric. G-: > > [Jess Austin] > > ...It seems like the consensus is "all" and "any". > From for_usenet2000 at yahoo.de Tue Nov 4 13:01:49 2003 From: for_usenet2000 at yahoo.de (Daniel Schüle) Date: Tue, 4 Nov 2003 19:01:49 +0100 Subject: static? + some stuff References: Message-ID: [...] > a, b, c and my_id *are* class attributes. They are actually inherited by just to adjust myself to the Python's terminology is the word "member" not widely used in Python? is it better to say "attributes"? (for both member functions and member variables) > instances of foo, but declaring them this way makes them class attributes. You > should have done: > > class foo: > cnt = 0 > def __init__(self, c=0): > foo.cnt += 1 > self.a = self.b = None > self.c = c > self.my_id = foo.cnt > (...) i think i've got it the only thing bothering me is that you cant see(less readability) from .. cnt = 0 .. is "cnt" considered to be used as "static" or not what if i would write ... foo.cnt += 1 #static and later in one of member functions self.cnt = 1 #non static or issues such usage an error .. and one more question :) from you code above i dont see the declarations of c, my_id ... is it sufficient just to write self.c=0 instead of doing it the way i did in my original posting (where i put them additional at the top for the readability)? but do the both ways express logical the same thing? > Attributes do not need to be *declared* at the top of the class in Python as in > C++ or Java: initializing them in the __init__ method is enough, and is probably > the safest way to handle them. as I figured out from tests, one has to initalize every variable with something at least with None (and that's fine so) is there a need to differentiate between assignment and initialization? (like in C++) btw in C++ you can also declare member variables at the bottom indeed that's my favorite style there, but since i am new to Python i found it more readable (dont ask me why) to place them at the top i am sure there are must be some "coding styles" in use around .. pointers in this direction are very approciated [...] > for i in attr: > print type(getattr(tmp, i)) exactly this :) Thank you and all others for the answears -- Daniel ps: i hope my english is understandable, if not .. just ask me what i ment ;) From sencion at alcatel.es Thu Nov 27 10:05:15 2003 From: sencion at alcatel.es (Alfonso Esteban Gonzalez Sencion) Date: Thu, 27 Nov 2003 16:05:15 +0100 Subject: Validating XML with Schema in python? Message-ID: <1069945516.274492@slbhw0> Hallo all Does any one know how can I validate an XML file using schemas in python. Regards From a at a.invalid Fri Nov 7 03:26:44 2003 From: a at a.invalid (Timo Virkkala) Date: Fri, 07 Nov 2003 10:26:44 +0200 Subject: [OT] Parables and barbarians In-Reply-To: References: Message-ID: Ben Finney wrote: > On Fri, 07 Nov 2003 03:43:32 GMT, JanC wrote: > >>And then [the doubling parable] came to the barbaric Western world, >>together with the chess game itself... ;-) > > Meh. I far prefer the game of go these days. Go is imperfect. Go with Hex (or Nash, as it was originally known, after it's inventor John Nash). =) -- Timo Virkkala From edreamleo at charter.net Sat Nov 8 11:16:14 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Sat, 8 Nov 2003 10:16:14 -0600 Subject: Leo + Python: the ultimate scripting tool #1 References: Message-ID: Reasons why Leo and Python work so well together: 1. You can execute Python scripts directly from anywhere in a Leo outline. The body text of any node in Leo outline may contain any Python script. The Execute Script commands executes this script in a pristine environment. However, it is trivial to get access, _from within any script_, to all the data in the present outline. For example: the following script prints all the headlines in the outline in which the script is embedded. from leoGlobals import c # Get access to all data in the present outline. c = top() # Get the "commander" associated with the topmost outline. v = c.rootVnode() # Get the root node of the outline. while v: ..print v.headString() ..v.threadNext() # Move to the next node in "threading" order. For that matter, scripts can access any data anywhere on your hard drive, or all the data available on the web, for that matter. You knew that, of course, but this "innocent" fact will be important later. As a result, it becomes very easy to experiment with new scripts from within Leo. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From djones at shcorp.com Sun Nov 9 13:27:41 2003 From: djones at shcorp.com (Dan Jones) Date: 09 Nov 2003 13:27:41 -0500 Subject: raw string from mmap.read() possible? Message-ID: <1068402461.11458.33.camel@shdj> Hello all, I'm writing a webcam app to display video from a video4linux device. I'm having trouble with the function to convert the video from yuv420p format to rgb. Its a C function that I wrapped for use in python. Here's whats happening: WIDTH=320 HEIGHT=240 yuvframe = mmap.read(WIDTH*HEIGHT*3) rgbframe = yuv.yuv2rgb(WIDTH, HEIGHT, yuvframe) At this point it gives a typeerror: argument 3 must be string without null bytes, not str. I did some testing to see whats going on. This call also generates the typeerror: rgbframe = yuv.yuv2rgb(WIDTH, HEIGHT, "\0\0\0\0") but if I send it a raw string it doesn't complain: rgbframe = yuv.yuv2rgb(WIDTH, HEIGHT, r"\0\0\0\0") I'm assuming this is happening because C interprets NULL as the end of the string. Is there a way to get a raw string directly from the mmap.read() call or do I have to do a conversion after the read? If I have to convert it, what would be the fastest way to do it? I need to get at least 5-10fps. Any help much appreciated. Thanks, Dan From jegenye2001 at fw.hu Fri Nov 14 14:35:08 2003 From: jegenye2001 at fw.hu (Jegenye 2001 Bt) Date: Fri, 14 Nov 2003 20:35:08 +0100 Subject: Python busting out References: Message-ID: Lovely story about the coolness of Python and the PHB effect... Mikl?s Vepxistqaosani wrote in message news:hU6tb.10805$fA2.2555214 at news4.srv.hcvlny.cv.net... > At my firm -- which must remain anonymous, I guess -- I'm the only > Pythoneer. We are strongly encouraged to use only "Approved Technologies". > [snip] > So who needs books when you can offer performance? > From newsgroups at jhrothjr.com Fri Nov 21 07:26:00 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 21 Nov 2003 07:26:00 -0500 Subject: Details on exceptions References: <3fbd7509$0$1749$5a62ac22@freenews.iinet.net.au> <3fbd7c7c$0$1746$5a62ac22@freenews.iinet.net.au> <3fbd8e56$0$1755$5a62ac22@freenews.iinet.net.au> Message-ID: "Rene Pijlman" wrote in message news:l1mrrvonmkbmmss8r8egf82bhqvbmn01ge at 4ax.com... > Derek Fountain: > >except IOError, (errno, strerror): > > > >The target is a tuple of 2 variable names so how can it bind "the exception > >object" to them? The documentation for try/except says that "the > >exception's parameter is assigned to the target". So what, exactly, is an > >"exception's parameter"? > > "For an except clause with an expression, that expression is evaluated, > and the clause matches the exception if the resulting object is > ``compatible'' with the exception. An object is compatible with an > exception if it is either the object that identifies the exception, or > (for exceptions that are classes) it is a base class of the exception, or > it is a tuple containing an item that is compatible with the exception." > http://www.python.org/doc/current/ref/try.html#try > > I think it has to do with the introduction of exceptions-are-classes in > 1.5, and backwards compatibility of older code: "This works because the > tuple-unpack semantics have been loosened to work with any sequence on the > right-hand size (see the section on Sequence Unpacking below), and the > standard exception classes can be accessed like a sequence (by virtue of > their __getitem__ method, see above)." > http://www.python.org/doc/essays/stdexceptions.html > > I'd say don't do it. Use exception objects and catch them as objects. I believe the actual answer is that what's assigned is the value of the 'args' attribute, which is what is specified on the throw statement. In this case, the args attribute is a tuple of two values - see the discussion of Exception EnvironmentError (which is the base class for IOError) in the Library Reference. In this case, I'd probably agree: I'd capture the actual exception because it probably contains additional data like the file name. John Roth > > -- > Ren? Pijlman From max at cNvOiSsiPoAnMtech.com Mon Nov 10 15:31:45 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Mon, 10 Nov 2003 20:31:45 GMT Subject: Matrix - Metaphors, Analogies and the REAL In-Reply-To: References: Message-ID: > Rue, Timothy timrue at mindspring.com Are you suggesting we should all send him a 'short' email? Yeah? good idea! Maybe I will get my computer to do that for me :) From pmetzger at bellsouth.net Mon Nov 24 12:12:54 2003 From: pmetzger at bellsouth.net (Paul Metzer) Date: Mon, 24 Nov 2003 11:12:54 -0600 Subject: Why should input(prompt="hello:") fail? In-Reply-To: <37ba82ff.0311240831.6e0dfba7@posting.google.com> Message-ID: <006701c3b2ae$33ed28e0$f2fea8c0@HoS> Input is for gathering user input. Something like: d = Input('enter your data:') It will then ask the user for the data and pause and then set the data to what ever variable you give it. In this case d. if you did a print d you would then echo what you entered in. To answer your question, the problem is the "prompt=". It's taking that as a keyword, which input just doesn't have need for, since it's just there to take user input in a console app. If you are new to python, I would highly recommend you picking up a copy of the python 2.1 bible. It's not the cheapest book in the world, but it's a really good place to start. Not to mention it's the only book I have found that has anything at all on wxPython. ======================================================================== ================================================== "Seek for the Sword that was broken: In Imladris it dwells; There shall be counsels taken Stronger than Morgul spells. There shall be shown a token That Doom is near at hand For Isildur's Bane shall waken, And the Halfling forth shall stand." -- From The Lord of The Rings "The Fellowship of the Ring" J.R.R. Tolkien ======================================================================== ================================================== > -----Original Message----- > From: python-list-bounces+pmetzger=bellsouth.net at python.org > [mailto:python-list-bounces+pmetzger=bellsouth.net at python.org] On Behalf > Of zhi > Sent: Monday, November 24, 2003 10:32 AM > To: python-list at python.org > Subject: Why should input(prompt="hello:") fail? > > Really confused, when I use keyword style argument as following: > > >>> input(prompt="hello") > > Traceback (most recent call last): > File "", line 1, in -toplevel- > input(prompt="hello") > TypeError: input() takes no keyword arguments > > While the library reference says the function is: input( [prompt]) > so, it should work.:( > > I am using python 2.3 for windows. > Have anyone tried this? > I am new to python, please help me, thanks. > -- > http://mail.python.org/mailman/listinfo/python-list From python473 at yahoo.com Thu Nov 13 19:10:36 2003 From: python473 at yahoo.com (John Howard) Date: 13 Nov 2003 16:10:36 -0800 Subject: python a bust? Message-ID: <9eabe547.0311131610.4dd7819c@posting.google.com> I've sent several messages over the last year asking about python - Who teaches python? Is python losing steam? etc. I have noticed, eg, the declinng number of books at my local borders. The last time I visited a borders (last week), there was 1 (sic) book about python on the shelve compared to dozens on perl & java! On my last inquiry about who teaching python, I got two, maybe three, responses. I really want to see python succeed! It's the best language I've seen. I see a lot on www.python.org about development, but little on usage. I sent a message to someone on the python site (I forget who - I know, no excuse) about what I've done done on a site (grades, web application, web registration, etc). No reponse. Sorry to ramble, but I wanted to say a lot, but not have to go into a lot of detail. From philh at invalid.email.address Fri Nov 7 13:38:03 2003 From: philh at invalid.email.address (phil hunt) Date: Fri, 7 Nov 2003 18:38:03 +0000 Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <3fa6a75e$0$12666$fa0fcedb@lovejoy.zen.co.uk> <23891c90.0311070355.1de4184c@posting.google.com> Message-ID: On 7 Nov 2003 03:55:56 -0800, Paul Boddie wrote: >philh at invalid.email.address (phil hunt) wrote in message news:... >> On Wed, 05 Nov 2003 17:23:25 +0000, Richie Hindle wrote: >> > >> >Your website (http://www.totalrekall.co.uk) says "The GPL version would be >> >free for non-commercial use", which is a contradiction. >> >> Not at all. The website says: >> >> ================================================================== >> We are thinking of releasing the Linux version Rekall under a duel >> licensing scheme. There would be a free for non-commercial use GPL >> version and the normal commercial version. > >Well, given the history of Rekall, combined with TheKompany's problems >with selling GPL software because people apparently demanded the >source code for free without buying anything, it's hard to know >whether the developers have misinterpreted the GPL or are trying to >layer their own incompatible stipulations on top. > >> The GPL would not include any kind of support whatsoever, therefore >> you would need to take out a support subscription. >> The GPL version would be free for non-commercial use. > >You have to ask yourself the question: if your knowledge of the GPL >was sketchy or non-existent, how would you interpret that last >sentence? > >[Rest of notice cut] > >> There's nothing innacurate or contradictory in that statement. After >> all, the GPL *is* "free for non-commercial use"; it just happens to >> be free for commerical use as well -- and the website doesn't say >> that it isn't, it just omits to mention that it is. > >Isn't this known as being "economical with the truth", Absolutely. > or is it just >downright contradictory? It's like saying that "nude bathing is >allowed but you aren't allowed to get wet", only to explain such a >ridiculous statement away by then saying that "they just forgot to >mention that you are allowed to get wet as well". No. AFAICT, it never makes two statements of the forms X and not-X. -- "It's easier to find people online who openly support the KKK than people who openly support the RIAA" -- comment on Wikipedia (Email: , but first subtract 275 and reverse the last two letters). From tjreedy at udel.edu Tue Nov 18 19:50:49 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Nov 2003 19:50:49 -0500 Subject: True inconsistency in Python References: <3FB8847F.6CB1BECA@alcyone.com> <3FB92086.9CBD0761@alcyone.com> <8qhirvgi2sf5l3vkfocq65mcb94c6pbb9s@4ax.com> <7rhjrvgefdpfkm15divsor9e3iktl0falh@4ax.com> Message-ID: <2IqdnVvoQ973IyeiRVn-hg@comcast.com> "Ron Adam" wrote in message news:7rhjrvgefdpfkm15divsor9e3iktl0falh at 4ax.com... > On Mon, 17 Nov 2003 23:40:52 -0500, "Terry Reedy" > wrote: > > >In 2.2.2+, you only need to not change them and to not work with a > >psycopath. > > Many people are starting to learn programming with python as their > first computer language. I wouldn't refer to them as a psychopath. Neither would I. I was thinking of the following scenario. You are part of a programming group. You write module ronad, to be imported by danor written by 'Dan Oreo'. Psycho writes unrelated module 'sneaky' with import ronad ronad.True, ronad.False = False, True perhaps disguised. You get blamed for the 'bug' that you did not write and cannot find. [Prohibiting this scenario (import module and mask builtins there in) has been suggested. I believe it was once approved and is still under consideration but the change has the problem that there seem to be legitimate uses.] > They may one day write programs that save peoples lives. They have to > start someplace. Many people using python will not be professional > programmers but enthusiast and hobbiests, or web page programmers, > or ..... in other words, a very large and diverse group. People often post code redefining builtings like file and list, and get reminders not to do so. I cannot remember anyone accidentally overwriting True or False. ... > I'm not sure what your point is here, but using PyChecker sounds like > a good suggestion. That suggestion was my final point. Ignore the warm-up pitch. Terry J. Reedy From francisgavila at yahoo.com Fri Nov 28 04:45:31 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Fri, 28 Nov 2003 04:45:31 -0500 Subject: Extract double in binary file References: Message-ID: Dennis Lee Bieber wrote in message ... >Pascal fed this fish to the penguins on Thursday 27 November 2003 01:07 >am: >> >> Some precisions: >> 0.00 > 00-00-00-00-00-00-7F-00 >> 1.00 > 00-00-00-00-00-00-00-81 >> 2.00 > 00-00-00-00-00-00-00-82 >> 3.00 > 00-00-00-00-00-00-40-82 >> 4.00 > 00-00-00-00-00-00-00-83 >> >> 10.00 > 00-00-00-00-00-00-20-84 >> 1000.00 > 00-00-00-00-00-00-7A-8A >> >> 1.11 > 14-AE-47-E1-7A-14-0E-81 >converting exponents excess 81... > > 0 1 00 00 00 00 00 00 00 > 1 1 00 00 00 00 00 00 00 > 1 1 40 00 00 00 00 00 00 > 2 1 00 00 00 00 00 00 00 > 3 1 20 00 00 00 00 00 00 That is a bizarre format, and of course I had to implement it. (Even C is more pleasant in Python!). It works for the cases given, but do find out where the sign bit is for the mantissa. (This code assumes it's the MSB of the mantissa.) Also tease out the NaN and +-Infinity cases. --- Code --- #! /usr/bin/env python # by Francis Avila # # Decode a peculiar binary floating point encoding # used by 'multilog', an old dos spreadsheet. import struct _known = (('0.00', '\x00\x00\x00\x00\x00\x00\x7F\x00'), ('1.00', '\x00\x00\x00\x00\x00\x00\x00\x81'), ('2.00', '\x00\x00\x00\x00\x00\x00\x00\x82'), ('3.00', '\x00\x00\x00\x00\x00\x00@\x82'), ('4.00', '\x00\x00\x00\x00\x00\x00\x00\x83'), ('10.00','\x00\x00\x00\x00\x00\x00 \x84'), ('1000.00','\x00\x00\x00\x00\x00\x00z\x8a'), ('1.11', '\x14\xaeG\xe1z\x14\x0e\x81')) def _test(): tests = [(str(float(i)),str(dectofloat(j))) for i,j in _known] results = [expect==got for expect,got in tests] failed = [tests[i] for i, passed in enumerate(results) if not passed] if failed: return failed else: return 'Passed' def bin(I): """Return list of bits of int I in little endian.""" if I < 0: raise ValueError, "I must be >= 0" bits = [] if I == 0: bits = [0] while I>0: r = (I & 0x1) if r: r = 1 bits.append(r) I >>= 1 bits.reverse() return bits def binaryE(n, exp): """Return result of a binary n*10**exp. As n*10**exp is to decimal, so binaryE(n, exp) is to binary. """ return sum([2**(exp-i) for i,bit in enumerate(bin(n)) if bit]) #Add special cases here: SPECIAL = {'\x00\x00\x00\x00\x00\x00\x7f\x00':0.0} def dectofloat(S): """Return float value of 8-byte 'decimal' string.""" if S in SPECIAL: return SPECIAL[S] # Convert to byteswapped long. N, = struct.unpack('>56, N&~(0xffL<<56) exp -= 0x81 # Exponential part is excess 0x81 (e.g., 0x82 is 1). msign = mant & (0x80L<<48) # MSB of mantissa is sign bit. 0==positive. if not msign: msign = 1 else: msign = -1 mant |= (0x80L<<48) # Add implied 1 to the MSB of mantissa. # Now, binary scientific notation: return float(msign * binaryE(mant, exp)) From mhammond at skippinet.com.au Fri Nov 21 19:25:58 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 22 Nov 2003 11:25:58 +1100 Subject: win32gui_dialog problem? In-Reply-To: References: Message-ID: Tim Roberts wrote: > I'm running Python 2.3 and win32all-155 on Windows 2000. The > win32gui_dialog.py sample in win32\demos dies with this: > > C:\Apps\Python23\Lib\site-packages\win32\demos>python win32gui_dialog.py > Fatal Python error: This thread state must be current when releasing > > abnormal program termination > > C:\Apps\Python23\Lib\site-packages\win32\demos> > > It dies at the end of DemoWindow._DoCreate when calling CreateWindow. I'm > boggled. Is this a known problem? Yes, it is a known problem. It is fixed in later win32all versions. Mark. From skip at pobox.com Mon Nov 10 17:29:19 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 10 Nov 2003 16:29:19 -0600 Subject: how to reference custom codec in a package? Message-ID: <16304.4415.165149.622961@montanaro.dyndns.org> I wrote a simple codec which strips accents from latin-1 characters (e.g., maps '?' to 'e'). If it lives in a package how do I refer to it? For example, what should this statement look like x = unicode(x, "latin1").encode("latscii") if latscii.py lives in the spambayes package? This seems to work: x = unicode(x, "latin1").encode("spambayes.latscii") but is that the right way to do it? Thx, Skip From fjh at cs.mu.oz.au Sun Nov 2 23:13:31 2003 From: fjh at cs.mu.oz.au (Fergus Henderson) Date: Mon, 03 Nov 2003 04:13:31 GMT Subject: Paging Mr. Rettig [ws Re: Explanation of macros; Haskellmacros] References: <87brs2tjut.fsf@memetrics.com> <4wuaj84x5.fsf@franz.com> <4vfq23i2m.fsf@franz.com> Message-ID: <3fa5d5e7$1@news.unimelb.edu.au> prunesquallor at comcast.net writes: >Duane Rettig writes: > >> Marcin 'Qrczak' Kowalczyk writes: >> >>> On Sun, 02 Nov 2003 02:01:58 -0800, Duane Rettig wrote: >>> >>> > With this much openness, it doesn't seem unreasonable >>> > to expect a debugger to be able to use such information to make macros >>> > and the forms they expand into completely debuggable and steppable at >>> > any desired level. >>> >>> Does any debugger do this? >> >> Most Lisp debuggers will do this with compiled code. I know of none which >> do this to compiled code without recompilation. > >MIT Scheme (which we all know is not Common Lisp) keeps around enough >debug information to determine the source code being executed at each >step in the compiled code. I don't recall if there is a compiled code >stepper per se, but crawling down the stack in compiled code shows the >source code that was being evaluated. Including macros invocations? When you say "source code", do you really mean source code, or do you mean the results of macro-expansion? If I have a function foo whose body invokes a macro bar which calls a function baz, can I get a "stack trace" or equivalent which shows me the line in the definition of bar which invokes baz, and the line in the definition of foo which invokes bar? Can I see the bindings of the parameters of bar? (It would be great if I could, and there's no serious practical obstacle AFAIK, but I don't know of any debuggers that actually do that.) -- Fergus Henderson | "I have always known that the pursuit The University of Melbourne | of excellence is a lethal habit" WWW: | -- the last words of T. S. Garp. From gerrit at nl.linux.org Fri Nov 21 10:07:04 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Fri, 21 Nov 2003 16:07:04 +0100 Subject: Question about Objects - repost with correct email account In-Reply-To: References: Message-ID: <20031121150704.GA3881@nl.linux.org> bas68 wrote: > >>>> x = Test("Microsoft Sucks") > >>>> x.getSomething > >> > >>>> x.something > >'Microsoft Sucks' You aren't calling getSomething. Try: x.getSomething() yours, Gerrit. -- 109. If conspirators meet in the house of a tavern-keeper, and these conspirators are not captured and delivered to the court, the tavern-keeper shall be put to death. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From mikael.lexen at spam.no.volvo.com Mon Nov 10 09:26:55 2003 From: mikael.lexen at spam.no.volvo.com (=?ISO-8859-1?Q?Mikael_Lex=E9n?=) Date: Mon, 10 Nov 2003 15:26:55 +0100 Subject: Problem with McMillans Installer Message-ID: <0fNrb.2779$uv1.2214@nntpserver.swip.net> Hi I have the following code fileName="test.txt" inputFile=file(fileName,'r') b = unicode(inputFile.read(), 'utf-8') inputFile.close() outputFile=file(fileName,'w') print >> outputFile, b.encode('iso-8859-1') outputFile.close() This code works ok. Then I use the Installer and made a --onefile "binary". The building process is also ok but when I try to execute the program I get the following error c:\python\siebel>convert "copy of test.txt" Traceback (most recent call last): File "", line 18, in ? LookupError: no codec search functions registered: can't find encoding I change to --onedir build and get the same result. I did some tests and found that if I put the "encodings" directory (from ".../python22/lib" directory) in the "--onedir" directory everything works ok . So my question is how can I tell the Installer to get the "encodings" directory in the build process? /Mikael From hungjunglu at yahoo.com Thu Nov 6 00:19:38 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 5 Nov 2003 21:19:38 -0800 Subject: Pure Aspect-Oriented Program: an example Message-ID: <8ef9bea6.0311052119.4f5ab5d6@posting.google.com> Hi, I have been looking into AOP (Aspect-Oriented Programming) for sometime, now. I frankly don't like the syntax of any of the approaches I have seen so far. I am kind playing around with some ideas, and maybe write up an article later. AOP is not just buzzword. It's not just callback, it's not just Ruby's MixIn, it's not just Python's metaclass, it's not just C++'s template. AOP can be implemented/considered as a subset of metaprogramming... an important subset that stands on its own. AOP deserves its name, because one really can think and program in "aspects" instead of "objects". That being said, I have never seen an example of purely aspect-based program. So, I thought I'd write up one. Here it is, and let's get some feedback. thanks, Hung Jung -------------------- Suppose you have to implement a checking account that allows withdrawal of money. Your first simple implementation may look like: class Account { real balance method withdraw(amount) { this.balance = this.balance ? amount } } A program that withdraws money may look like: account = new Account() ... amount = 100 account.withdraw(amount) In order to simplify the discussion, in the following I will omit all initialization code details, and assume that variable values have been properly assigned elsewhere. Also notice that everything is in pseudocode, I am not using any particular language as base. After you have implemented the program, your bank manager comes and tells you there are constraints to the withdrawal of money. For instance, an account maybe disabled. In OOP, you would modify your Account class to: class Account { real balance bool enabled method withdraw(amount) { if not this.enabled raise AccountDisabledException this.balance = this.balance ? amount } } Now, stop thinking in OOP. Let us try to think in AOP. //--------------------------------------------------- class Account { real balance method withdraw(amount): this.balance = this.balance ? amount } //--------------------------------------------------- aspect AccountStatus { bool enabled codeblock check_status { if not this.enabled: raise AccountDisabledException } method withdraw(...) { this.check_status this.withdraw.code } } //--------------------------------------------------- endow Account with AccountStatus The general idea is to have the concerns implemented outside the object. We have added a new feature to the account (namely, the account status,) without having to tweak the original code of the account. Notice that we have three parts to the above code: a class definition, an aspect definition, and a final part to endow the aspect to the class. The last part is also known as the "aspect weaver". Let us proceed to the next step. Say, there is a maximum daily withdrawal limit. //--------------------------------------------------- class Account { real balance method withdraw(amount) { this.balance = this.balance ? amount } } //--------------------------------------------------- aspect AccountStatus { bool enabled codeblock check_status { if not this.enabled: raise AccountDisabledException } method withdraw(...) { this.check_status this.withdraw.code } } //--------------------------------------------------- aspect WithdrawalLimit { real daily_limit real withdrawn_today codeblock check_and_update_withdraw { new_withdrawn_today = this.withdrawn_today + amount if new_withdrawn_today > this.daily_limit: raise WithdrawalLimitExceededException &inner_code this.withdrawn_today = new_withdrawn_today } method withdraw(...) { this.check_and_update_withdraw { ... &inner_code = this.withdraw.code ... } } } //--------------------------------------------------- endow Account with AccountStatus endow Account with WithdrawalLimit Notice the usage of a hook (also known as pointcut): &inner_code. In general, a code block or a method can contain one or many hooks. Hooks allow future enhancement of code. There are two implicit hooks: the before and the after hooks. But for readability of AOP code, in our approach we treat named hooks very differently from implicit hooks. Ruby users should notice that a code block here can contain multiple hooks, and that the direction of hooking process is kind of opposite to Ruby's MixIn. The above way of programming of course takes longer to write. But, the advantage is in the degree of decoupling (or "separation of concerns") that is achieved. Say, one day, we want to eliminate the feature on withdraw limit, it is as simple as commenting out one single line of code: endow Account with AccountStatus //endow Account with WithdrawalLimit The same is true if one day we want to eliminate the account status feature: //endow Account with AccountStatus endow Account with WithdrawalLimit Also, once the concerns are separated, it is easier to modify the aspects individually. A careful reader would point out that we may want to check the account status before checking withdrawal limit. Notice also that we have applied two aspects in sequence. But we can pre-compose two aspects into one, and apply the composed aspect just once. //--------------------------------------------------- aspect AccountAspects inherits AccountStatus, WithdrawalLimit { method withdraw(...) { this.check_status this.check_and_update_withdraw { ... &inner_code = this.withdraw.code ... } } } //--------------------------------------------------- endow Account with AccountAspects At this point you may say: "Hey! We started with a non-trivial class but we could have started with an empty class, and endow the balance-calculating feature as an aspect, too." Bingo! Now you are thinking in AOP. //--------------------------------------------------- class Account { } //--------------------------------------------------- aspect BalanceKeeping { real balance method withdraw(amount) { this.balance = this.balance ? amount } } //--------------------------------------------------- aspect AccountStatus { bool enabled codeblock check_status { if not this.enabled: raise AccountDisabledException } method withdraw(...) { // this meta-method is overriden later this.check_status this.withdraw.code } } //--------------------------------------------------- aspect WithdrawalLimit { real daily_limit real withdrawn_today codeblock check_and_update_withdraw { new_withdrawn_today = this.withdrawn_today + amount if new_withdrawn_today > this.daily_limit: raise WithdrawalLimitExceededException &inner_code this.withdrawn_today = new_withdrawn_today } method withdraw(...) { // this meta-method is overriden later check_and_update_withdraw { ... &inner_code = this.withdraw.code ... } } } //--------------------------------------------------- aspect AccountAspects: inherits BalanceKeeping, AccountStatus, WithdrawalLimit { method withdraw(...) { check_status check_and_update_withdraw { // this meta-method overrides ... &inner_code = this.withdraw.code ... } } } //--------------------------------------------------- endow Account with AccountAspects print Account.codeString() Notice that we have started with a bare class with no attributes. All the features of the class Account have been implemented by aspects, instead of interfaces or base classes. You may complain: the code is now too hard to read and follow. But that actually is a problem of IDE (Integrated Development Environment). For more advanced IDEs, editing aspects actually should not be bad at all. It's almost like editing the header and footer information in a Microsoft Word document. At any rate, the last statement above would print out the code for the "aspected class", which may look something like: class Account { real balance bool enabled real daily_limit real withdrawn_today method withdraw(amount) { if not this.enabled: raise AccountDisabledException new_withdrawn_today = this.withdrawn_today + amount if new_withdrawn_today > this.daily_limit: raise WithdrawalLimitExceededException this.balance = this.balance ? amount this.withdrawn_today = new_withdrawn_today } } A good IDE/compiler/debugger can provide additional information on where each code line or code block comes from, hence making debugging and editing a snap. But we don't need to get into that discussion, now. What have we learned? We have learned that: 1. We can write a purely-AOP program. 2. Aspect inheritance can be used to compose derived aspects. 3. A new type of object: "codeblock", becomes the fundamental building block of programs. So, in general we have to consider the (data, codeblock, method) trio when building classes or programs. A method consists of its "header/prototype" and a reference to its codeblock. Also, in a real program, most codeblocks would be anonymous. 4. Despite of its innocent look, the code specifying an aspect contains disguised meta-programming instructions. Codeblock-based AOP actually is more suitable in programming languages powered with meta-programming features. Also, (data, codeblock, method) are all supposed to be virtual and overridable. Data overriding does not do anything, if the data is already present. Codeblock overriding does not present problem. The main problem is with method overriding. If the new method refers to the existing method, there is a problem as how to deal with the names and who will hold reference to the old method once the new method is in place. For the AOP practitioners, this means that the "before" and "after" advices can be implemented more easily, where as the "around" advice is trickier. A possible solution is to "decorate" the name of the old implementation. Here I only present a possible syntax of the "around" advice. class C { method f() { return 3 } } aspect A { method f_before_A = f method f(...) { print 'begin around-advice' result = this.f_before_A() print 'end around-advice' return result } } endow C with A c = new C() print c.f() //------ output begin around-advice end around-advice 3 One thing I have not mentioned is pattern matching for method names. An aspect may affect many or all the methods in a class. In that case, the name of the methods should be listed, or wildcards (possibly regular expressions) must used to pattern-search for them. Possible syntax variations are: aspect A { method (...) for f in f1, f2, f3 { } } aspect B { method (...) for f matching 'f*' { } } Another thing that I have not mentioned is that aspects can be endowed to different classes. For instance, if later we have checking accounts and savings accounts, we can apply the same aspect to both classes. That's what other people refer to as "cross-cutting". ... That's all for now. From aleax at aleax.it Thu Nov 6 09:30:30 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 06 Nov 2003 14:30:30 GMT Subject: Please explain the meaning of 'stealing' a ref References: <7h3wuagiagy.fsf@pc150.maths.bris.ac.uk> <56gkqvcjhgvb6gn31v6458ghk95u6bn1er@4ax.com> Message-ID: Most of this discussion seems to be veering into English (and natural language in general) and style issues, farther and farther away from Python. Still, in as much as Python docs are written in English, I guess it might still be appropriate here. Like most authors, I have very strong opinions on style, nuances, fine points of connotation as well as denotation in phrasing, and language in general. Developed in long praxis as well as reflection about all of these issues, and honed in long, bitter fights with editors and co-authors, these opinions are unlikely to change very easily...;-) Christos TZOTZIOY Georgiou wrote: ... >>> The missing part IMO is what "owning a reference" means. I understand >> >>Hmmm... what if the text was transliterated into "Owning a reference >>means you have to dispose of it properly" from the current "When a >>function owns a reference, it has to dispose of it properly"? The current >>expression and my suggested rewording are meant to convey just the >>same meaning, but perhaps the rewording is more immediately obvious >>to some non-native speakers of English (I'm a non-native speaker myself, >>but sometimes I have trouble gauging what problems others may have). > > For other people (if any) that have similar to my questions, all the > information about 'owning', 'borrowing' and 'stealing' references is in > the sections 1.2.1-1.2.2 of the "Python/C API reference", but first have > a good grasp of the tutorial "Extending and Embedding the Python > interpreter", subsections 1.10.1-1.10.4 . So what about my proposed transliteration of "when X, Y" into "X means Y"? This is similar to (e.g.) changing "when somebody owns a property outright, they can sell it" to "owning a property outright means you can sell it" -- essentially equivalent in normal English usage, but perhaps more specific or clear to non-natives? >>> This text is obviously clear, and the misconception was my fault: since >>> references are just pointer variables at the C level, and I never had a >>> concept of a function (or a program) 'owning' its variables, >>> automatically my brain converted the word 'reference' to 'reference to >>> python object' to 'python object'. That's it. >> >>Ah. So there may be no fix for this -- we can't get any more explicit, >>but if your brain converts this to "we talk of owning python objects, >>never of owning objects" there's really nothing we can do:-(. > > You use present tense for 'converts' above, but I assume you meant to > use past tense, since this is what I did in the previous paragraph. > Unusual of you to miss details. Like I said, the text is clear; it > needs no fix in the case of owning references|objects. I don't think I missed any details: I was talking about making the docs clearer to _other_ (future) readers, as opposed to borrowing Guido's time machine to retroactively change them so they might be clearer in the past, so the "your brain converts" in my sentence is (clearly, in context) a typical case of "generic you"; feel free to mentally transliterate it to "if some generic and hypothetical reader's brain converts". Using the tense "converted" in such a sentence would mean one's having vague regrets about the unchangeable (save for the time machine) past, not a particularly interesting subject; I'm focused on how to make things better in the future. >>> The word "exceptions" implies "exception to the previous statement". >> >>Yes, to the statement terminated by the semicolon - the one saying that >>few functions steal references. >> >>> IIUC "exceptions" should be changed to "examples". >> >>Yes, this is surely a reasonable change, if it clarifies the text for some >>readers. > > Since you agree (and make more specific) that 'exceptions' means > 'exception to the statement terminated by the semicolon', and since > neither PyList_SetItem nor PyTuple_SetItem are exceptions to the few > functions that steal references, doesn't that make the choice of the > word 'exceptions' unreasonable (as in exactly the opposite of what was > meant)? It's not a matter of simple clarification. No, the use of the word 'exceptions' is anything but unreasonable, except in as much as each natural language has its typical foibles which might, abstractly, be considered "unreasonable" if judging natural languages from completely inappropriate viewpoints (in this case, I'd use exactly the same phrasing in Italian or French, so I'm going to staunchly defend the perfect reasonableness of normal English usage). The statement "Few people do that" is semantically equivalent to "most people don't do that", it's just a smoother and more natural way of expression; in _either_ case, when one continues by mentioning people as "exceptions", it's then just as reasonable as any other idiomatic construction -- and perfectly clear in context -- that the "exceptions" are the (few) people who _do_ "do that". In an alternative phrasing such as "I don't like any ice-cream brand; the few exceptions are... [mention of some brands]", the statement after the semicolon would _contradict_ the one before the semicolon, which (at least in English and Italian) doesn't sound good (although in _spoken_ language this construct would astonish nobody, it should really be edited when found in _written_ form). When considering how to edit this, I would _definitely_ want to keep the word "exceptions" (if I knew I could count on good command of the language on readers' parts) because its connotations are _just right_: whenever I mention an exception, a reader is inherently attraced to think of a general rule -- and in this case the reader finds the rule right before that semicolon, reinforcing exactly the "rule/exceptions" message I am trying to send. So, rather than changing the part after the semicolon, I look for a way to weaken the assertion before the semicolon, which was here stated as "absolute rule". "I don't like most ice-cream brands" and "I like very few ice-cream brands" are semantically equivalent, but I prefer the second: all other things being equal, an assertion phrased in the positive form is easier for the reader than one phrased in the negative; and the second form is smoother. The semantics equivalence of the two forms guarantees against any problem with what follows after the semicolon: in either case, that part is going to be read as "the few exceptions [[to the general rule just stated]] are" -- and _the general rule just stated is *the same* in either case_, which is the point. All that's in discussion, therefore, is whether to make the whole expression not quite as strong and obvious to native readers (missing out on the helpful connotation "exceptions" --> "general rule") for the purpose of potentially clarifying things for those readers who, on seeing "exceptions", do NOT immediately "read the unwritten words" ``to this general rule''. Unfortunately "examples", for exactly the same readers who DO get the right connotations from "exceptions", brings the WRONG connotation here: "examples" leads to "reading the unwritten words" ``OF this general rule''. But the general rule is that normally functions *do NOT* steal references, and yet the alleged ''examples'' are _NOT_ "examples of this general rule", they are in fact the _exceptions_ to this general rule. This means the connotations become, from just right, to just wrong _for native readers_, and makes the whole suggested change problematic. > Either the word 'exceptions' should be changed, or it should be changed > to 'notable exceptions to abovementioned functions are exceptions, and which domain is not "'few > functions steal references", since the functions do steal references>' There's no such general concept as "exceptions to a domain", but rather "exceptions to a general rule". The _general rule_ *IS* "normally functions don't steal references" (expressed in the preferable positive form). Redundantly repeating exactly what you're referring to in each case is of course a possibility (I'm not very attuned to it since the editors, quite rightly, would never tolerate such mostly-wasted wordiness in e.g. magazine articles or Nutshell books, but a reference manual can be weighed by other criteria). Given that there _is_ no ambiguity (for the mostly-intended audience of people with the right level of idiomatic command of the language) I doubt I can defend such redundancy, though (particularly not being enthusiastic about it:-). > The previous two paragraphs were written only because your 'if it > clarifies the text for some readers' seems to ignore the fact you > yourself stated two paragraphs above in 'Yes, to the statement...' I hope I clarified this abundantly, and thank you for forcing me to think the issues through in such detail as needed to argue against your contention -- I "instinctively knew" that what you said was entirely wrong, but explaining exactly how and why meant I had to analyze and reason in depth about the whole issue. It's funny -- though I'll never have the easy command of a native speaker, of course, yet 40+ years of constant practice of English do seem to have given me _some_ "reflex" reactions (in this case, the fact that the applicable idioms _are_ just about the same in Italian does, of course, also help:-). > If the python documentation had a terminology dictionary, how would > 'stealing', 'borrowing' and 'owning' a reference be defined in a concise > and absolutely clear way? I seem to not be able to write these > definitions, although I would like to. The concept of "owning a reference" is the crucial one. "Stealing" is just one way to permanently transfer ownership, "borrowing" means no transfer of ownership takes place, and these meanings are so close to those in everyday language that the "terminology dictionary" would have few problems, I believe. So, focusing on ownership, and foregoing the concision that would probably be required in a dictionary, we might say: """ Ownership pertains to references, never to objects (objects are not owned: they are always shared). "Owning a reference" means being responsible for calling Py_DECREF on it when the reference is no longer needed. Ownership can also be transferred, meaning that the code that receives ownership of the reference then becomes responsible for eventually decref'ing it when it's no longer needed. """ plus, perhaps, pointers to the various appropriate sections in the "extending and embedding" tutorial and API reference that deal with this concept. Really, the true meaning of "reference ownership" is _operational_ -- the "responsibility of eventually decref'ing (unless the ownership is transferred)" _together_ with the rules for how and when ownership (i.e. responsibility to eventually decref) is transferred. Alex From dman at dman13.dyndns.org Mon Nov 24 16:52:48 2003 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Mon, 24 Nov 2003 21:52:48 GMT Subject: Delete common entries between two dictionaries References: <4Guwb.7197$9O5.6638@fed1read06> Message-ID: <97ba91-169.ln1@dman13.dyndns.org> On Mon, 24 Nov 2003 13:24:17 -0800, Amy G wrote: > I have received such good help on this message board. I wonder if I > might not get a little more help from you on this. > > I am at the point where I have two dictionaries, with information of > a domain and a frequency of that domain. > > Now that I have the two, I want to delete each entry from one that > the two have in common, leaving only those that are unique to the > dictionary? This would be great for sets, if a set adequately models your data. (with two sets, this would simply be (s1-(s1&s2))) > Say I have a dictionary called domains_black and another > domains_white... Did you want to define equality by key or by (key, value) pair? for key in domains_white.keys() : if key in domains_black: del domains_black[key] for key in domains_white.keys() : if key in domains_black and domains_white[key] == domains_black[key] : del domains_black[key] -D -- He who scorns instruction will pay for it, but he who respects a command is rewarded. Proverbs 13:13 www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From fredrik at pythonware.com Sun Nov 30 13:02:03 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 30 Nov 2003 19:02:03 +0100 Subject: pil bug? References: Message-ID: John Smith wrote: > Hello, I don't know if this is a bug or not, but when you convert an image > from one mode to another, the object's filename gets lost in the conversion > process. the filename attribute is only valid for image objects that are created from files. From http Wed Nov 19 22:13:05 2003 From: http (Paul Rubin) Date: 19 Nov 2003 19:13:05 -0800 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <3FBB805D.40A8DA75@engcorp.com> <3FBBA68A.6D819C5C@engcorp.com> <7xd6bop2sm.fsf@ruckus.brouhaha.com> <3FBC305B.D63AF472@engcorp.com> Message-ID: <7xwu9v68ce.fsf@ruckus.brouhaha.com> Peter Hansen writes: > I guess the point is then that rotor is in a dangerous middle ground, > where it looks better than it really is. Either way it's the wrong > thing for someone to use, whether they want strong or weak encryption. Yes, that's a good summary. From vze4rx4y at verizon.net Sat Nov 1 12:51:04 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sat, 01 Nov 2003 17:51:04 GMT Subject: PEP 322: Reverse Iteration (second revision, please comment) References: Message-ID: [Raymond] > > * the sample implementation now clearly shows a check for a custom > > reverse method and a guard against being applied to a mapping. [Paul Moore] > I stumbled over this, as using the existence of has_key to reject > mappings seemed odd. Surely even without this check, the sample > implementation would fail on a mapping, with a KeyError at the yield? Without a guard for mappings, the following would behave strangely: d = {0:'zero', 1:'one', 3:'three'} Peter Otten pointed-out that some user defined mappings have __contains__ rather than has_key, so the existence of a "keys" may make a better check. > > * added sample output for enumerate.__reversed__ to show > > how a custom reverse method would work > > Are you proposing to add such a custom reverse method to enumerate? Yes, that has been requested more than once. However, it was listed in the PEP mainly to give a clear example of how a custom reverse could work. > > * explained why the function is proposed as a builtin and why attachment > > to another module or type object is not being considered further. > > This was very useful. It may not convince everyone, but it helped me > see your point of view a little better. Thanks. > > Also, please take a look at the revrange() alternative to see if you > > prefer it or not. > > Not really. It feels too much like a special case. > > Overall, I'm +0 going on +1 (the main reason I'm not +1 is the fact > that I have no code that would actually *use* this feature at > present...) Noted. Raymond From adalke at mindspring.com Thu Nov 13 16:16:32 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 13 Nov 2003 21:16:32 GMT Subject: checking for ASCII character References: Message-ID: Greg Krohn: > If it needs to be ASCII, the simplest way is probably: > > if ord(character) in range(65, 91): > or if character in string.ascii_uppercase: ... Andrew dalke at dalkescientific.com From python at meyer-luetgens.de Wed Nov 19 17:46:07 2003 From: python at meyer-luetgens.de (=?ISO-8859-1?Q?Jan-Erik_Meyer-L=FCtgens?=) Date: Wed, 19 Nov 2003 23:46:07 +0100 Subject: strange behaviour of sum() In-Reply-To: References: Message-ID: Ben wrote: > I'm trying to figure out how how complex map, filter and reduce work > based on the following piece of code from > http://www-106.ibm.com/developerworks/linux/library/l-prog.html : > > bigmuls = lambda xs,ys: filter(lambda (x,y):x*y > 25, combine(xs,ys)) > combine = lambda xs,ys: map(None, xs*len(ys), dupelms(ys,len(xs))) > dupelms = lambda lst,n: reduce(lambda s,t:s+t, map(lambda l,n=n: > [l]*n, lst)) > print bigmuls((1,2,3,4),(10,15,3,22)) > Hi all, I've played with this example, also. I'd rewritten the example using zip() and sum(), when I've noticed a quirk of the sum() function. # keep pairs whose product is greater than 25. bigmuls=lambda xs,ys:filter(lambda (x,y): x*y>25, combine(xs, ys)) # compute the cross product of two lists. # combine([1,2],[3,4]) --> [(1, 3), (2, 3), (1, 4), (2, 4)] combine=lambda xs,ys:zip(xs*len(ys), dupelms(ys, len(xs))) # duplicate elements of lst n times. # dupelms([1,2], 3) --> [1, 1, 1, 2, 2, 2] dupelms=lambda lst,n:sum(map(lambda element,n=n:[element]*n, lst),[]) I'd ran into trouble when I've used sum() naively: sum([ [1], [2], [3] ]) results in: TypeError: unsupported operand type(s) for +: 'int' and 'list' A peek in the language reference: sum(sequence[, start]) Sums start and the items of a sequence, from left to right, and returns the total. start defaults to 0. The sequence's items are normally numbers, and are not allowed to be strings. The fast, correct way to concatenate sequence of strings is by calling ''.join(sequence). Note that sum(range(n), m) is equivalent to reduce(operator.add, range(n), m) New in version 2.3. As we can see: sum(seq, start) is equivalent to reduce(operator.add, seq, start) but: sum(seq) is not equivalent to reduce(operator.add, seq) because: start of sum() defaults to 0. So we must set the start value explicit to the neutral element for the addition: sum([ [1], [2], [3] ], []) The other strange behaviour is: sum(['my', 'pet', 'fish', 'eric'], '') results in: TypeError: sum() can't sum strings [use ''.join(seq) instead] If there is a special treatment for strings, why doesn't sum() use ''.join(seq) itself, instead of telling me that I should use it? But in fact sum() should call operator.add(), even for strings: from types import StringType class MyString(StringType): # __metaclass__ = type def __init__(self, value): StringType.__init__(self, value) def __str__(self): return StringType.__str__(self) def __add__(self, other): return MyString(str(self) + ' ' + str(other)) my = MyString('my') pet = MyString('pet') fish = MyString('fish') eric = MyString('eric') # different output (with intent): print my + pet + fish + eric # --> my pet fish erik print ''.join([my, pet, fish, eric]) # --> mypetfisheric # two quirks for sum(), here: # 1. does not work, because MyString is a subclass of string # 2. result have an extra unwanted space (if it would work) print sum( [my, pet, fish, eric], MyString('') ) I would treat this quirks as unpythonic, cause the behaviour of the sum() function is not generic and not intuitive. Will this be fixed in future releases of python? From tzot at sil-tec.gr Tue Nov 4 08:38:07 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 04 Nov 2003 15:38:07 +0200 Subject: Please explain the meaning of 'stealing' a ref References: <7h3wuagiagy.fsf@pc150.maths.bris.ac.uk> Message-ID: On Tue, 4 Nov 2003 12:32:22 GMT, rumours say that Michael Hudson might have written: >Christos "TZOTZIOY" Georgiou writes: > [my attempting to implement attribute caching] > >Are you aware of the cache-attr-branch (think it's called that) in >CVS? Obviously, not :( [my question about what "stealing means"] > >This *really* should be explain in the API reference or the extended >and embedding manual somewhere... have you looked there? Oh, definitely, ext/refcountsInPython.html is the page I believe. I can understand the second paragraph, but I wanted some reasoning. For example, you call a function that its API specifies that it "steals" a reference to its argument; therefore, you got to incref in advance and decref afterwards yourself. What's the reason? Efficiency for simplicity of the function? If yes, why not enclose the function call in a incref / decref cycle and then export the enclosing function in the API? Such stuff I wanted to know. Also, "borrowing" and "stealing" are the same thing? I just think that "beautifying" terminology at the C level is more confusing than helpful. PS Thanks KefX and Edward for your replies. I'll check the branch. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Nov 8 09:44:42 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 08 Nov 2003 15:44:42 +0100 Subject: Inter-Process comunication In-Reply-To: References: Message-ID: <3fad015a$0$58714$e4fe514c@news.xs4all.nl> Zunbeltz Izaola wrote: > I want something like to send a signal each time the data is changed > to execute DrawPlot(). I'm no proffesional programmer and i don't know > wich technique is the best, signals, theread, anothero one ... > Any sugestions? Have a look at Pyro, http://pyro.sourceforge.net You could stick your DrawPlot() method in a Pyro object and call it -remotely- from the process/thread that generated new data to plot. --Irmen From joconnor at cybermesa.com Tue Nov 18 10:58:31 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Tue, 18 Nov 2003 08:58:31 -0700 Subject: recommendations for python web programming tools In-Reply-To: References: Message-ID: Matthew Wilson wrote: >I am about to start designing a web application for my office intranet. >It is pretty simple: we need a way to track conversations with contacts >and a way to update contact information. > >I could do it all in PHP or perl-mason, but I really like python's >syntax and I have the time to learn something new. I've never used any >of the web stuff for python. I need something that is easy and quick to >learn. I need support for connection to MySQL, simple user >authentication based on passwords, and either a templating system, or >the ability to embed python code in html, like PHP. I already have >Apache installed and running on a Red Hat linux box. > >I don't need the most high-performance system. We have 8 users at the >most that will be logging in simultaneously. > >All recommendations are welcome. > > If you want something simple and focused, I have both some simple username/password and templating libraries I use for python web work. Contact me offline if you're interested Take care, Jay From eric.brunel at pragmadev.N0SP4M.com Mon Nov 10 10:51:26 2003 From: eric.brunel at pragmadev.N0SP4M.com (Eric Brunel) Date: Mon, 10 Nov 2003 16:51:26 +0100 Subject: Undo class References: Message-ID: Mickel Gr?nroos wrote: > Hello everybody > > I'm developing a tool in Tkinter and would like to add Undo and Redo > commands to my Edit menu. Does somebody know if anybody has implemented > standard Undo/Redo as a Python module? I could not find any info with > Google on the matter. On what king of widget? If it's a Text, you can use the native tk undo/redo features: create the Text widget with the option undo set to 1, then use the methods edit_undo() and edit_redo(). These are tk 8.4 features, so it may not work for Python versions older than 2.3 (it doesn't work with 2.1; don't know about 2.2) For other widgets, I doubt there can be a generic mechanism to manage the undo/redo functions for you: after all, only you can tell what actions should be able to be undone or redone. But I'd be really happy if someone can prove me wrong! HTH anyway. -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From alex at this-is-not-a-real-email-address.com Fri Nov 7 14:47:47 2003 From: alex at this-is-not-a-real-email-address.com (Alexandre Rogers) Date: Fri, 07 Nov 2003 20:47:47 +0100 Subject: [newbie] GTK+/QT/Tkinter ? In-Reply-To: References: Message-ID: Tim Ronning wrote: > Hi there > > One alternative you could try is FLTK with the pyfltk wrapper. It's > multiplatform, pure GPL GUI toolkit. FLTK comes with "Fluid" a really > nice and easy gui builder. The output of Fluid can be converted to > python via flconvert which is a tool for pyfltk. > I'm trying FLTK out now, and beeing a beginner like you, I find it > quite easy to work with. > You could still use Eric, it's a great code editor. It has some bugs > though, but thats another story. > > FLTK: http://www.fltk.org/ > pyfltk: http://pyfltk.sourceforge.net/index.html > > Best regards > Tim R. > Thank you very much! FLTK & Fluid look great, though I can't install pyfltk (it halts during compilation and prints out it doesn't like ld -lGL... anyway, this is not the place for, I'll try the mailing list). Many thanks again, Alex From bkc at Murkworks.com Wed Nov 12 11:45:12 2003 From: bkc at Murkworks.com (Brad Clements) Date: Wed, 12 Nov 2003 11:45:12 -0500 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: <7N6dnUz1P9CKZTOiRVn-hQ@comcast.com> Message-ID: _ "Nick Vargish" wrote in message news:m3brrhliid.fsf at tanelorn.bandersnatch.org... > "Terry Reedy" writes: > There are several ways to communicate as the leader of an open-source > project. Including posting in the source forge forum that was setup for that purpose, rather than emailing the author directly, or posting in c.l.p > One is of condescending arrogance, to wit, "My time is so > important that you must jump through hoops to speak to me." The other > is one of helpful cooperation. "Thanks, I'm really busy right now, > I'll address the issue you raised as soon as I can." Nick, While I don't know you, I've read your posts in this forum and found them all to be reasonable. I'm surprised that you expressed your opinion in such harsh terms this time. > It's left as an excercise to the reader which category I see Edward's > tactic falling into. :^) Some time ago I sent email to Edward and I received the "you must confirm you're a human" thing. True, I thought it was annoying and in fact did not immediately do anything about it. However we all have Spam issues and while I wouldn't have taken Edwards approach to solving my spam problems, I eventually expended 30 seconds to "suplicate myself to his spam software" and get my message through. I don't think it's supplication to the author, just his anti-spam guard dog. I don't see Edwards statement (paraphrased) "if you want me to take time to solve your problem, take a moment to confirm your a human" as arrogance, just a fact of life. Rather than writing to the author, you could just post in the Leo specific forum, where your post could be answered by Edward or other users, and the ensuing thread would be archived for other folks to later benefit from. From emile at fenx.com Sun Nov 2 10:53:09 2003 From: emile at fenx.com (Emile van Sebille) Date: Sun, 2 Nov 2003 07:53:09 -0800 Subject: Python from Wise Guy's Viewpoint References: <3F994597.7090807@ps.uni-sb.de> <1j5o61-co2.ln1@ID-7776.user.dfncis.de> <9eso61-mu7.ln1@ID-7776.user.dfncis.de> <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <8yn6gmic.fsf@comcast.net> <1xssqozs.fsf@comcast.net> Message-ID: "Joachim Durchholz" asks: > prunesquallor at comcast.net wrote: > > Neel Krishnaswami had a wonderful explanation in article > > > > Sorry, that link doesn't work for me, I don't know the proper syntax for > news: links, and I couldn't type one in even if I knew it. > I prepend: http://groups.google.com/groups?selm= in this case yielding http://groups.google.com/groups?selm=slrnbplpv6.ikr.neelk at gs3106.sp.cs.cmu.edu Emile van Sebille emile at fenx.com From newsgroups at jhrothjr.com Mon Nov 17 19:41:28 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 17 Nov 2003 19:41:28 -0500 Subject: Origin of the term "first-class object" References: <8ef9bea6.0311171335.356a7af6@posting.google.com> Message-ID: "Rainer Deyke" wrote in message news:wHcub.227649$Tr4.672235 at attbi_s03... > John Roth wrote: > > For example, in Python both classes and functions are > > objects (there are no second class citizens in Python...) > > I would consider variables to be second-class citizens. You can change > their value, delete them, and get at the object to which they refer, but you > can't do much else with them. I think I'd disagree with that. In fact, except for the optimization within function bodies, I can't think of anything I can't do with a name that I might want to. John Roth From jenny_edmondson at hotmail.com Mon Nov 24 23:25:51 2003 From: jenny_edmondson at hotmail.com (Jenny Edmondson) Date: Tue, 25 Nov 2003 14:25:51 +1000 Subject: re.compile Message-ID: Hi, What does re.compile("(.+)<(.+)>(.+)") do? Regards, Jenny From aahz at pythoncraft.com Thu Nov 6 15:40:23 2003 From: aahz at pythoncraft.com (Aahz) Date: 6 Nov 2003 15:40:23 -0500 Subject: prePEP: Decimal data type References: Message-ID: [BTW, Facundo, you proably need quote-printable most of the time to deal with Spanish, but it adds a lot of cruft (left in below) when dealing with plain English. If you could figure a way to disable that, it'd be a big help.] In article , Batista, Facundo wrote: >This message is in MIME format. Since your mail reader does not understand >this format, some or all of this message may not be legible. > >------_=_NextPart_001_01C3A494.06BF20D0 >Content-Type: text/plain; > charset="iso-8859-1" >Content-Transfer-Encoding: quoted-printable > >Aahz wrote: > >#- > Enter the context stack. >#-=20 >#- Well, sure. And it won't be hard to add given that Decimal=20 >#- will already >#- need to track thread-specific Context. But modules changing Context >#- will still need to explicitly push and pop Context because=20 >#- usually you >#- will just want to replace the current Context. > >OK. So, as long Decimal comply with the "a Context per thread" item, = >it's >everything allright? For the most part, though you'll need to add the Context stack at some point. That can be left for later, once we see how Decimal gets used in practice; Guido's idea may work better. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From peter at engcorp.com Thu Nov 20 10:37:23 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Nov 2003 10:37:23 -0500 Subject: regular expression to extract text References: Message-ID: <3FBCDFB3.E01417E1@engcorp.com> Mark Light wrote: > > Hi I have a file read in as a string that looks like below. What I want to > do is pull out the bits of information to eventually put in an html table. > FOr the 1st example the 3 bits are: > 1.QEXZUO > 2. C26 H31 N1 O3 > 3. 6.164 15.892 22.551 90.00 90.00 90.00 > > ANy ideas of the best way to do this - I was trying regular expressions but > not getting very far. > > Thanks, > > Mark. > > """ > Using unit cell orientation matrix from collect.rmat > NOTICE: Performing automatic cell standardization > The following database entries have similar unit cells: > Refcode Sumformula > > ------------------------------------------ > QEXZUO C26 H31 N1 O3 > 6.164 15.892 22.551 90.00 90.00 90.00 > ------------------------------------------ > ARQTYD C19 H23 N1 O5 > 6.001 15.227 22.558 90.00 90.00 90.00 > ------------------------------------------ > NHDIIS C45 H40 Cl2 > 6.532 15.147 22.453 90.00 90.00 90.00 """ I don't think you've given enough information here. Are those "bits" supposed to be kept intact, complete with internal spacing, or are you doing more manipulation of them? What is the definition of the "bits"? Specifically, is bit 1 "the first non-space token after a line of hyphens"? Is bit 2 "everything on the line after bit 1, with leading and trailing spaces stripped"? Is bit 3 "everything on the following line, with leading/trailing spaces stripped"? Those definitions roughly fit what you describe, and if that's all you need, the solution should be pretty trivial, without having to use regular expressions which would be overkill in this case. From claird at lairds.com Wed Nov 12 14:11:05 2003 From: claird at lairds.com (Cameron Laird) Date: Wed, 12 Nov 2003 19:11:05 -0000 Subject: Automating FTP file transfers References: Message-ID: In article , Limey Drink wrote: >Thanks very much for the help guys I now know how to connect using python >ftp library and I am happy with this but... > >Just wondering about the bigger picture with regards to sys admin scripts, >in your opinion, is creating these type of system administration scripts >preferable/easier than using say bash scripts, or DOS .bat scripts ? > >Because I don't have alot of experience of sys admin and shell scripting I'm >just wondering if I am applying Python for one of its intended uses doing >these type of scripts. > >IMHO i would rather learn and stick with Python than to learn all the >different scripting languages as it is cleaner and more powerful and also if >the script is written correctly it seems could be cross platform. > >Just wondering if you think I should be trying to execute the in built OS >programs such as FTP etc. calling them from python or should I be using the >libraries that come with Python such as FTPlib and say if I wanted to send >email should I be using the SMTP lib rather than say executing the mail >program in unix and passing arguments from a Python script. > >It would hear interesting to hear your views on this as it would be nice if >I can gain from others experience and not make the same mistakes. . . . Yes. That is, I take very seriously this question of what tools are best for sysads; I'll be running a series on the subject most of next year in *System Administration* magazine. My short answer (to which I might return later in the week) is that, yes, Python makes a great vehicle, particularly be- cause its networking is so much easier *and* more potent than what bash, .bat, and so on offer. While there are counter-arguments, I think you'll find Python quite satisfy- ing, and you will *not* be tempted to return to bash and friends. -- Cameron Laird Business: http://www.Phaseit.net From shlomme at gmx.net Fri Nov 14 04:25:44 2003 From: shlomme at gmx.net (Torsten Marek) Date: Fri, 14 Nov 2003 10:25:44 +0100 Subject: [OT] Re: guten tag In-Reply-To: References: Message-ID: Necati Agirbas schrieb: > Betreff: SCHULBESCHEINGUNG F?r Frau DERYA AGIRBAS, wohnhaft > novalissstr.42 in 51147 K?ln geb.26.05.1981 (k?ln) Lehrgangsbezeichnung: > T193! > > > Guten Tag auch den Damen und Herren, > > Versuche sied Heute Morgen Sie in der Schule telefonisch zuerreichen, aber > Ihre telefon anlage wird ja installiert! > > Mein name ist hanife agirbas, schreibe Sie aus folgendem grund an meine > schwester DERYA AGIRBAS hat ihre schule bis zu den Sommer ferien dieses > Jahres 2003 besucht, und wir ben?tigen eine Schul -Bescheinigung > f?r das Jahr 2002. > > Wenn Sie es f?r heute fertig stellen k?nnten w?hren wir ihnen sehr dankbar. > > bitte um Ihre r?ckantwort, > > mfg > hanife agirbas > > Looks like a hidden message... Anyway, lets stick to Bateson: An Information is a difference that makes a difference. From jjl at pobox.com Tue Nov 11 07:07:55 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Nov 2003 12:07:55 +0000 Subject: response time References: <1jSrb.2419$9_.105379@news1.tin.it> <87d6bzetsz.fsf@pobox.com> <3FB01787.529425BC@engcorp.com> Message-ID: <87u15bf6qs.fsf@pobox.com> Peter Hansen writes: [...] > Strange, but based on a relatively mundane thing: the frequency (14.31818MHz) > of the NTSC color sub-carrier which was used when displaying computer output > on a TV. This clock was divided by 3 to produce the 4.77MHz clock for the [...] > in time-keeping, which then counted on every edge using a 16-bit counter > which wrapped around every 65536 counts, producing one interrupt every > 65536/(14.31818*1000000/12) or about 0.5492 ms, which is about 18.2 ticks [...] That doesn't explain it AFAICS -- why not use a different (smaller) divisor? An eight bit counter would give about 0.2 ms resolution. John From jimmy at retzlaff.com Tue Nov 25 07:18:04 2003 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Tue, 25 Nov 2003 04:18:04 -0800 Subject: import _winreg does not work. How do I fix? Message-ID: John Sellers wrote: > Miki Tebeka wrote: > > There is no _winreg on cygwin, only on "true" win32 python. > > If you must use cygwin you can either patch _winreg to work for you or > > use cygwin's regtool (try regtool --help) > > Sounds reasonable, but if what you say is true, I am surprised that not > all Python 2.3.2 releases are not equal. > > How good is your information? Is it authorative? While Miki's information may or may not be authorative, it does appear to be true. Python has different modules available on different platforms. See http://www.python.org/doc/current/modindex.html for a list of modules. The modules with one or more platforms in parenthesis next to them are platform specific. _winreg is documented as being a Windows specific module. As far as Python is concerned, cygwin is a Unix platform, not a Windows platform. As evidence of this try importing modules which the Python documentation calls Unix specific and modules called Windows specific on cygwin Python and on Windows Python: Python 2.2.3 (#1, Jun 19 2003, 12:10:13) [GCC 3.2 20020927 (prerelease)] on Cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import crypt >>> crypt >>> import _winreg Traceback (most recent call last): File "", line 1, in ? ImportError: No module named _winreg And on "true" Win32 Python: Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import _winreg >>> _winreg >>> import crypt Traceback (most recent call last): File "", line 1, in ? ImportError: No module named crypt If you don't like Miki's suggestion of using regtool, then you could run win32 Python side-by-side with cygwin Python and use an IPC mechanism to communicate between the two. Jimmy From prouleau at impathnetworks.com Mon Nov 17 23:20:34 2003 From: prouleau at impathnetworks.com (Pierre Rouleau) Date: Mon, 17 Nov 2003 23:20:34 -0500 Subject: Is RAII possible in Python? In-Reply-To: <4_utb.21936$IK2.1678737@news20.bellglobal.com> References: <4_utb.21936$IK2.1678737@news20.bellglobal.com> Message-ID: Pierre Rouleau wrote: > As much as I love Python, I sometimes find myself wishing Python > supported the RAII idiom (resource acquisition is initialization) that > is available in C++, the emerging D language, and others. > > In some situations (like controlling non-memory resources) it is nice to > be able to create an object that will execute some code on its > destruction. For example, an object that controls access to a critical > section: the creation of the object calls the function required to enter > the critical section, and the __del__() calls the function required to > exit the critical section. If an exception occurs while the code is > insinde the critical section managed by the object, the the object's > __del__() is automatically called and the critical section exited. > > AFAIK, the call of __del__() method on object destruction is not > garanteed to be called when the interpreter exists. Is this true? > > Is the __del__() mehod of an object garanteed to be called when a > function exists normally or is forced to exit by an exception? > > Is RAII available in Python? > Thanks to all that posted a reply. To summarize those replies, in Python 2.3 the 'calling' code is responsible to provide protection with the try/finally clause, as in (atken from pep 310): the_lock.acquire() try: .... finally: the_lock.release() PEP-310 (http://www.python.org/peps/pep-0310.html) proposes a more condensed syntax using a new keyword (with). I have seen some PEP310 discussion on comp.python.devel and I hope PEP310 will be implemented in the next version of Python (2.4) as written on the PEP-310 page. Where can we find out about the state of a PEP and whether it's going to get implemented? Thanks! Pierre From jfranz at neurokode.com Tue Nov 18 20:54:04 2003 From: jfranz at neurokode.com (Jon Franz) Date: Tue, 18 Nov 2003 20:54:04 -0500 Subject: Fw: Python Database Objects (PDO) 1.2.0 Released Message-ID: <01ce01c3ae40$02f3d4e0$7401a8c0@voidmk9> > Sounds good, if you can update/insert back into the DB by the same > dictionary then I'm sold. I'll go check it out. :) Not yet :) Now that we've got a lot of supported DB modules, we're planning on adding such features for the next major release. 2 weeks or so. ~Jon Franz NeuroKodeLabs, LLC From cedmunds at spamless.rochester.rr.com Thu Nov 6 23:03:27 2003 From: cedmunds at spamless.rochester.rr.com (Cy Edmunds) Date: Fri, 07 Nov 2003 04:03:27 GMT Subject: Why does changing 1 list affect the other? References: <8ufjqvc24b7o1v0c32p2cpv7us32gtsdic@4ax.com> Message-ID: "Ben Finney" wrote in message news:slrnbqm579.i5n.bignose-hates-spam at iris.polar.local... > On Fri, 07 Nov 2003 03:00:29 GMT, Cy Edmunds wrote: > > "Ben Finney" wrote: > >> What you probably want os to take a *copy* of the list object, and > >> bind 'secondlist' to that new object. This occurs automatically for > >> some types (e.g. scalars) but not lists or dicts or other structured > >> types. > > > > I used to think this too: different types work differently. Now I > > think that the only difference is that some types are immutable. > > Your examples aren't showing this: > > > Consider: > > > >>>> x = 5 > >>>> y = x > >>>> print x, y > > 5 5 > >>>> x = 4 > >>>> print x, y > > 4 5 > > Creating a new integer object, 4, and binding 'x' to that. > > >>>> x = [5] > >>>> y = x > >>>> print x, y > > [5] [5] > >>>> x = [4] > >>>> print x, y > > [4] [5] > > Creating a new list object, [4], and binding 'x' to that. > > > Scalars and lists work the same! And yet: > > For binding to a new object, sure. The difference was the conceptual > "modify" operation: > > >>> x = [ 1, 2, 3 ] > >>> y = x > >>> print x, y > [1, 2, 3] [1, 2, 3] > >>> x[0] = 55 > >>> print x, y > [55, 2, 3] [55, 2, 3] > > There's no equivalent for integer objects, because they're not mutable. > I think we're in agreement, though I may have been remiss in failing to > distinguish the extra operations available to mutable types. I think you were remiss in saying: "What you probably want os to take a *copy* of the list object, and bind 'secondlist' to that new object. This occurs automatically for some types (e.g. scalars) but not lists or dicts or other structured types." Scalars do NOT automatically make a copy. Try this: >>> x = 5 >>> y = x >>> print x is y True y is second reference to the immutable value 5, not a copy. -- Cy http://home.rochester.rr.com/cyhome/ From a.schmolck at gmx.net Tue Nov 18 12:48:34 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 18 Nov 2003 17:48:34 +0000 Subject: Can this be written more concisely in a functional style References: <92c59a2c.0311171648.6360213d@posting.google.com> <92c59a2c.0311172340.544faac6@posting.google.com> <698f09f8.0311180259.bdd4359@posting.google.com> Message-ID: tweedgeezer at hotmail.com (Jeremy Fincher) writes: > jcb at iteris.com (MetalOne) wrote in message news:<92c59a2c.0311172340.544faac6 at posting.google.com>... > > Maybe my post was not clear. > > I want a means to test if there exists an element in the list that > > satisfies a predicate. > > Sure there is. The code that you showed was an excellent way to do > so. > > > Actually, when I word it that way, I guess what I want is PEP 289, > > universal and existential qualifiers. > > > > I guess I'll have to wait. > > Why? Why not just stuff the code you wrote into an appropriately > named function and use that? > > Anyway, here are more efficient implementations: > > def any(p, seq): > """Returns true if any element in seq satisfies predicate p.""" > for elt in itertools.ifilter(p, seq): > return True > else: > return False Another alternative (also works for python2.2, but is likely to be slower): def some(predicate, *seqs): iterables = map(iter, seqs) try: while 1: boo = predicate(*[iterable.next() for iterable in iterables]) if boo: return boo except StopIteration: return False 'as From ahmad at bitbuilder.com Thu Nov 20 10:45:37 2003 From: ahmad at bitbuilder.com (Ahmad Baitalmal) Date: Thu, 20 Nov 2003 07:45:37 -0800 Subject: "python exe" and "py plugins" In-Reply-To: References: Message-ID: Thomas Heller wrote: >>That works fine in linux or uncompiled on windows, but with py2exe, it >>can't find the "services" folder. > > > You should be a bit more specific here - what do you mean by "it can't > find the services folder" ? > I figured out that's what is happening. py2exe used to package my "services" package because it was imported normally. But now I do a folder lookup to find all subfolders in my sys.executable + '/services' folder and exec("import %s" % foldername ) each subfolder. That's why py2exe can't package those packages when its building. And I'm doing it that way because the set of plugins are not known ofcourse, that's why I do this dynamic discovery at runtime. This will work, but it feels a bit patchy to me, is there a way in python to say "here is the path to folder x, recursevily import all packages you find in there"? py, pyc, pyd also? Thx, ahmadster From jdhunter at ace.bsd.uchicago.edu Wed Nov 26 20:46:50 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 26 Nov 2003 19:46:50 -0600 Subject: invert dictionary with list &c In-Reply-To: (Des Small's message of "Wed, 26 Nov 2003 17:06:53 GMT") References: Message-ID: >>>>> "Des" == Des Small writes: def count(l): d = {} [d.setdefault(w, 0) += 1 for w in l] return d This code raises a SyntaxError. The standard idiom for counting all the elements in a list with a dictionary is def count(l): d = {} for w in l: d[w] = d.get(w,0) + 1 return d I think the basic rule of thumb is to use the setdefault approach for mutable objects (list, dict) and the get approach for immutable elements (strings, ints, floats, tuples). Also, many here would find using list comprehensions while ignoring their return value, as you did in '[d.setdefault(w, 0) += 1 for w in l]' to be an abuse of list comps. At least I've been admonished for doing so, and so I must now admonish you to continue the cycle of violence. Des> Is this the pythonic way to do such things? Ideally I'd like Des> to write them as one liners, but I can't see how. I think that striving for one-liners is not pythonic. Most python coders value readability over compactness. It's more important to write an appropriately named function that works and is readable and efficient than it is to write a one liner. John Hunter From jzsmith at optonline.net Wed Nov 26 14:51:06 2003 From: jzsmith at optonline.net (John Z. Smith) Date: Wed, 26 Nov 2003 14:51:06 -0500 Subject: How to call functions with list and keyword arguments? References: Message-ID: Thanks. I didn't event know that's legal syntax. Just checked the tutorial and reference manual but didn't find it. Could you point me to it? Thanks again. "anton muhin" wrote in message news:bq2iog$ak8$1 at news.peterlink.ru... > John Z. Smith wrote: > > Hi, > > I want to subclass a class (more precisely, optparse.Option). that looks > > like > > > > class Option: > > def __init__(self, *opts, **attrs): > > do_something() > > > > > > I want to do something in my __init__ and and also call Option.__init__. > > Then I don't know how to pass the arguments. For example, > > > > class MyOption: > > def __init__(self, *opts, **attrs): > > do_my_own_thing() > > Option.__init__(self, opts, attrs) > > > > does not work (and you know why). I figured out some very ugly ways to do > > this > > but I believe there should be an elegant way to pass the argments to > > superclass. > > > > > > > > Option.__init__(self, *opts, **attrs) should work. BTW, some purists > recommend to use super ;) > > hth, > anton. > From mwh at python.net Mon Nov 24 13:30:11 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 24 Nov 2003 18:30:11 GMT Subject: 2.2.2 Annoyance References: Message-ID: "Mikl?s" writes: > Michael Hudson wrote in message > news:m3r7zxzukb.fsf at pc150.maths.bris.ac.uk... > > "Jegenye 2001 Bt" writes: > > > > > According to the manuals of Python 2.2.2, passing a slice object to > > > __getitem__ is all right and should work... > > > > Really? Where does it say that? > > Python Reference Manual, > 3.3.4 Emulating container types > (Release 2.2.2, documentation updated on October 14, 2002. ) > """ > __getitem__(self, key) > Called to implement evaluation of self[key]. For sequence types, the > accepted keys should be integers and slice objects. Note that the special > interpretation of > """ I think this is talking about implementing __getitem__, not calling it directly. Historically these things have been quite different, though they are becoming less so. > > > For Python 2.3 passing a slice object to __getitem__ does work though. > > > > Yes. Do you have a good reason for sticking to 2.2? > > > Yes, see my previous post on this. I haven't had the time to read all posts to this ng for some time... > (That site wants to stay with 2.2 for the time being.) OK. > Actually I patched the code to circumvent this and I haven't tried 2.2.3 as > for this yet. (I didn't know about 2.2.3 until Terry's response..) 2.2.3 will not make any difference on this point. Cheers, mwh -- ARTHUR: Don't ask me how it works or I'll start to whimper. -- The Hitch-Hikers Guide to the Galaxy, Episode 11 From magnus at thinkware.se Thu Nov 27 18:19:28 2003 From: magnus at thinkware.se (Magnus Lyck?) Date: 27 Nov 2003 15:19:28 -0800 Subject: for what are for/while else clauses References: <258fd9b8.0311220938.3210484c@posting.google.com> Message-ID: <258fd9b8.0311271519.153f573d@posting.google.com> aahz at pythoncraft.com (Aahz) wrote in message news:... > In article <258fd9b8.0311220938.3210484c at posting.google.com>, > Magnus Lyck? wrote: > > > >On the other hand, I only think it's in the case of a break > >in block that... > > > >while condition: > > block > >else: > > print "Loop finished" > > > >...will behave differently than... > > > >while condition: > > block > >print "Loop finished" > > > >So, unless you use a break in the block, the else statement is just > >noise: an extra line of code and additional whitespace for the > >following statement(s). > > While technically correct, I don't think you could claim that it's "just > noise" in this example: > > try: > for ORlist in includes: > try: > for filter in ORlist: > for field in curr_fields: > for item in record[field]: > if match(item, filter): > raise Found > else: > raise NotFound > except Found: > continue > except NotFound: > continue > else: > result.append(record) First of all, I'm not sure it's a good idea to use exceptions like a poor (rich?) man's GOTO like this. :) If you persist, I'm not so sure your code is clearer than: try: for ORlist in includes: try: for filter in ORlist: for field in curr_fields: for item in record[field]: if match(item, filter): raise Found raise NotFound except Found: continue except NotFound: continue else: result.append(record) With the else clause on the for loop, just after the if statement, you are bound to confuse people. I would guess that most people who casually looked at that code would think that you had made an indentation mistake. Some would probably "correct" it. From stephan.diehlNOSPAM at gmx.net Mon Nov 24 12:10:27 2003 From: stephan.diehlNOSPAM at gmx.net (Stephan Diehl) Date: Mon, 24 Nov 2003 18:10:27 +0100 Subject: Bug or Feature? References: <2259b0e2.0311240603.549943b3@posting.google.com> Message-ID: Duncan Booth wrote: > Stephan Diehl wrote in > news:bpt5do$nls$04$1 at news.t-online.com: > >> Although, the question was more along the line, if (in the light of >> the principle of least surprise) this behaviour makes sense. >> My private opinion would be, that the usefullness of builtin types as >> real types would be much better, if they were safe under inheritance. >> > There are some tradeoffs here. > > I think that the majority of users would say that the speed of operations > using 'int' is more important than the ease of inheriting from them. If > you can make the 'int' operations work this way, but keep them at least as > fast as they are today, then there may be a case for changing the > behaviour. O.K., since the stuff I'm concerned about here is of no relevance for 99.9 % of all python programmers, execution speed is a very valid reason for this (and I'll consider this behaviour as a feature :-) > > The other problem though is that this would break backwards compatibility. > For example if any code were to currently add booleans, it would suddenly > get a boolean result. The (untested) code below, currently counts how many > items in a list are greater than a specified value, but under your scheme > it would return a boolean. > > def HowManyGreaterThan(aList, aValue): > return reduce(operator.add, [ x > aValue for x in aList ]) Which, of course, would bring us to the discussion if a bool should be a subtype of int (and since this was decided long ago, it should not be discussed, of course) > > I think what would be most useful would be new subclasses of int etc. > which have the properties you desire, but you can write them yourself > easily enough. > > What rules, BTW, are you proposing for operations between two separate > subclasses of int? e.g. given your mod7 class, and a corresponding mod9 > class should this print 3, 6, 24 or throw an exception? > > x = mod7(3) > y = mod9(8) > print x*y > > and does this do the same? > > print y*x > tough question. I'd probably throw an exception. thanks for your input Stephan From jjl at pobox.com Fri Nov 7 07:30:15 2003 From: jjl at pobox.com (John J. Lee) Date: 07 Nov 2003 12:30:15 +0000 Subject: Why does this choke? References: Message-ID: <87wuac1huw.fsf@pobox.com> S Kemplay writes: > I wrote a script to choose random dates for a statistics assignment. > I only need to choose 30 dates from one year with no leap years and it works > fine. However I tested with different numbers of dates. It hangs from 450 up. > I only need 30 dates but it would be good to know why it hangs. (My coding > probably has something to do with it :)) [...] > if (day, month) in dates: > continue [...] This looks like the culprit. I bet it really hangs from 366 up . John From eldada at mdstud.chalmers.se Fri Nov 28 14:05:11 2003 From: eldada at mdstud.chalmers.se (Ali El Dada) Date: Fri, 28 Nov 2003 20:05:11 +0100 Subject: newbie : using python to generate web-pages References: Message-ID: <3FC79C67.8B88B82C@mdstud.chalmers.se> i think you want HTMLgen from: http://starship.python.net/crew/friedrich/HTMLgen/html/main.html worked fine for me :) cheers, ali dada From peter at engcorp.com Mon Nov 3 14:24:24 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Nov 2003 14:24:24 -0500 Subject: Does python always need to compile ENTIRE program before it can start to run it??? References: Message-ID: <3FA6AB68.FBBA8E93@engcorp.com> Christian Seberino wrote: > > I can achieve something similar to Python's automatic compilation > in C/C++ by making a script that compiles and runs my program like this: > > make ; myprogram > > I am trying to think of an advantage Python has over this hack.... > > Is it true that unlike C/C++ that Python programs can start executing > before compilation is COMPLETELY done??? I think so but I'm not sure. Yes, this is true. Assuming (as would be the case in any serious program) your code is broken into appropriate modules, only the first module loaded is compiled prior to its execution. Other modules are compiled on an as-needed basis, as they are imported for the first time. Also note that Python has automatic caching of the compiled code in a .pyc file, and recompilation occurs only if the timestamp of the source .py file is different than that stored in the .pyc file. In essence, the above "hack", as you so aptly call it, has *no* advantages over Python's approach, and Python makes it all transparent anyway so you don't even need to worry about it. -Peter From http Fri Nov 21 22:25:44 2003 From: http (Paul Rubin) Date: 21 Nov 2003 19:25:44 -0800 Subject: can't figure out syntax prob References: <1AAvb.15633$I27.11112@newssvr29.news.prodigy.com> Message-ID: <7x1xs15bk7.fsf@ruckus.brouhaha.com> "python newbie" writes: > File "OregonBackup.py", line 23 > def __init__(self,fg) You need a colon there: def __init__(self,fg): .... From pmaupin at speakeasy.net Mon Nov 24 23:30:52 2003 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 24 Nov 2003 20:30:52 -0800 Subject: Use of GPLed Python extension modules References: <653b7547.0311230957.69e5cdbc@posting.google.com> Message-ID: <653b7547.0311242030.412ee394@posting.google.com> Andreas Kostyrka wrote: > Well, the big "difference" between C libraries, and Python modules is > that C libraries usually consist of .h files, which get included in > your "dynamically" linked program. That wouldn't be that bad, but .h > files often contain macros and/or inlined function, which makes every > client of the library include some part of the sourcecode of the > library. > > Python modules OTOH include only my name, so there is no "code" > leaked into my program. > > If you read the interviews of the FSF Lawyers with this in your head, > it just makes much more sense (yeah, by using readline you are > including it, well at least parts, in your program). Well, that does make it read a bit more sensibly, but that is not really what they are saying. The GPL FAQ on the FSF site talks about dynamically interpreted languages, and even states very explicitly that "A consequence is that if you choose to use GPL'd Perl modules ... you must release the program in a GPL- compatible way." As another example, the email exchange leading up to the GPLing of clisp is quite instructive. Personally, I don't find "my lawyer made me do it" particularly compelling, especially since that was tried after "but if I let _you_ do it, then _anybody_ can get away with it" but I suppose it _could_ have happened that way: http://cvs.sourceforge.net/viewcvs.py/*checkout*/clisp/clisp/doc/Why-CLISP-is-under-GPL?rev=HEAD It may be true, as Daniel Berlin opines, that the FSF would have some chance of convincing a judge of the correctness of this position. However, the copying of small interface portions necessary for interoperability has been ruled in some cases to be "fair use". Even if you were worried that this was an issue, you could, in a few hours, engineer a "clean-room" implementation of the header files. This would involve someone reading them, describing in his own words the bare minimum that was necessary to reconstruct an interoperable .h file, and passing this description to someone else to reimplement. As you pointed out, Python's dynamicity makes not using the original source even easier. This is true in some cases even if the GPLed library is in C -- you might be able to interface with it via calldll, and not even use any .h file description of the program in your system. But, as the GPL FAQ makes clear, and as many other of Stallmans' writings make clear, in the opinion of at least some at the FSF you would be violating the GPL if you were to do this. As I have posted elsewhere, I have read several things which indicate that this may not be true (at least if you are not actually distributing the GPLed software along with your program). The only things I have seen which indicate that it may be true are Richard Stallman saying that it's true (without giving a good deep explanation why) and other people saying "Well, of _course_ it's true! The GPL FAQ says so!" As long as everybody (probably correctly) agrees that it's not worth it to provoke the FSF, then it doesn't really matter to the FSF whether their position is legally defensible or not, because obviously their position is having the desired effect if nobody wants to test it in a courtroom. The reality that some people are running scared of the "viral" nature of the GPL is actually viewed as beneficial by Stallman and others who aren't busy trying to get work done with both free and non-free software in a corporate environment complete with conservative lawyers and bosses. Pat From marc.lentz at ctrceal.caisse-epargne.fr Thu Nov 20 03:26:19 2003 From: marc.lentz at ctrceal.caisse-epargne.fr (marco) Date: Thu, 20 Nov 2003 09:26:19 +0100 Subject: wxpython : wxDc and Refresh() = flash References: <3fbbb373$0$578$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: > > Juste a simple question about the DC in wxpython ... > > > > I've made a wxWindow class, where i need to paint myself the content. > > so i've added an evt_paint() to draw in the wxPaintDC ... > > It works like a charm !! superb > > > > To trigg the painter event, in some codes, i use the Refresh() method > > It works greatly ! > > Two points > 1) you would do well to subscribe to the wxPython news group, they > specifically handle wxPython related issues and you will have a better > shot at getting the right answer. > > http://wxpython.org/maillist.php sure ... and i've already subscribe to it > 2) In the demos supplied by wxPython, see the wxScrolledWindow example. > They show how to use a double buffering screen that will help prevent > the flashing screen when it is being redrawn. Just look for > > if BUFFERED: > > in the code. If you don't have access to this, I'll send it to you. > > Brian thanx a lot ... i've got the demo, and got access to the code ... (i use it a lot, but never see an example to disabled this flashed rendering) i will use it ... thanx for your answer ... From sombDELETE at pobox.ru Sun Nov 30 05:21:32 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sun, 30 Nov 2003 13:21:32 +0300 Subject: sorting dictionary keys? References: <3fc91af5$0$28610$636a55ce@news.free.fr> <3fc935da$0$28643$636a55ce@news.free.fr> Message-ID: "Bruno Desthuilliers" wrote in message news:3fc935da$0$28643$636a55ce at news.free.fr... > Serge Orlov wrote: > >> > >>Which is one of the main PITA in Python IMHO :( > >>(not the fact that it sort in place, the fact that it does not return self). > >> > > > > > > > > def sort(lst): > > lst.sort() > > return lst > > > > Which is pretty ugly and adds a useless function call. Why ugly? It adds the functionality you asked for, it doesn't use any magic, it's readable. I have goodies.py module for personal stuff like that. > > I just can't understand *why* the BDFL made this choice. The answer is the FAQ section of the Python web site. -- Serge. From peter at engcorp.com Mon Nov 10 13:59:50 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Nov 2003 13:59:50 -0500 Subject: Matrix - Metaphors, Analogies and the REAL References: Message-ID: <3FAFE026.7EF6F2F5@engcorp.com> 3seas wrote: > > If you are not interested, then don't bitch, its a short message. Then don't bitch about my reply, either... > http://www.matrixcommunity.org/cgi-bin/ultimatebb.cgi?ubb=get_topic;f=8;t=000918 > > I don't know if that link got broken. The word "Python" appears nowhere on that page, according to a simple search, so it seems likely this is an off-topic post, in addition to being rather cryptic. From piet at cs.uu.nl Sun Nov 9 08:58:35 2003 From: piet at cs.uu.nl (Piet van Oostrum) Date: 09 Nov 2003 14:58:35 +0100 Subject: Does python always need to compile ENTIRE program before it can start to run it??? References: Message-ID: >>>>> "James Kew" (JK) wrote: JK> "John Roth" wrote in message JK> news:vqdamhn2pq1qaf at news.supernews.com... >> I've never >> gotten a satisfactory explanation of why it doesn't save the compiled >> version of the top level script, but then, I've never really looked >> into it. It's just curious. JK> I've always wondered that too. The top-level script _might_ be standard JK> input or command-line, but it seems to me that it often (usually?) is a .py JK> which _could_ be stashed into a .pyc. And then? Next time you call again python script.py, not script.pyc. That's the difference with import: import says `import script', not `import script.py'. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From fpetermaas at netscape.net Fri Nov 7 04:28:01 2003 From: fpetermaas at netscape.net (Peter Maas) Date: Fri, 07 Nov 2003 10:28:01 +0100 Subject: Unicode Hell In-Reply-To: <2SmdnSziee5L0DaiU-KYhg@is.co.za> References: <2SmdnSziee5L0DaiU-KYhg@is.co.za> Message-ID: Stuart schrieb: > What I really want to do is replace a field place holder with those values. > So if we have a string > cReplaceString = "I want to replace #here#" > I'd like to replace the #here# with the values of a (or ?????) # assign a unicode literal (u"...") to cReplaceString: cReplaceString = u"I want to replace #here#" cNewString = cReplaceString.replace(u"#here#",u"????") Perhaps you have to ecncode the chineses characters like \uabcd whith a,b,c,d as hex digits. My editor has problems with chinese characters. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From fmiville at sympatico.ca Sat Nov 1 22:08:58 2003 From: fmiville at sympatico.ca (=?iso-8859-1?Q?Fran=E7ois=20Miville=2DDech=EAne?=) Date: Sat, 01 Nov 2003 22:08:58 -0500 Subject: It's still I, Miville Message-ID: <3FA4754A.7496499@sympatico.ca> You say in the definition of mappings that at present Python has only one type of it, the dictionnary. I suggest another one, the sparse array, where absence of key would mean not absence of element but presence of a default-value element, such as zero for sparse arrays in the mathematical sense. This would enable the use of mapping with the distributive operators as I just suggested them in a previous e-mail. I will be pestering you with my suggestions from time to time. You say Python is an evolving language, prove it. To take on another subject, an object-oriented language such as yours should explicitly tackle the Microsoft Office constructs, which even though their actual binary coding is hidden from the public, are in principle defined as hierarchically-embedded objects, and just for the sake of legal definition Microsoft is liable to give the object-oriented definition of the products its programs churn out. VBasic does a bad job with them (when it is functioning), you can do a better one. I personnaly don't like that much Office, but will it or not we are stuck with their products for at least a decade. Your product is free (although profitable), VBasic is not. You should intrude into Microsoft's domain right at this place. People are rightly scared when they hear of VBasic, so they are turned off from programming altogether, prefering to let the Microsoft monsters do all kinds of jobs by the means of commands far more difficult to master than learning a language. Your language appears in a calculator fashion, the user is reassured and feels empowered. It is like a toy in his hands. If he could play with Microsoft objects with this toy, he would tackle many jobs far more easily than at present. From claird at lairds.com Fri Nov 7 14:18:45 2003 From: claird at lairds.com (Cameron Laird) Date: Fri, 07 Nov 2003 19:18:45 -0000 Subject: [newbie] GTK+/QT/Tkinter ? References: Message-ID: In article , Alexandre Rogers wrote: . . . >Is there an IDE/GUI builder for Tkinter ? . . . "Idle is the Python IDE built with the Tkinter GUI toolkit." It's part of the standard distribution. There are several others. Apparently there's not yet a Wiki page dedicated to the topic, though there should be. -- Cameron Laird Business: http://www.Phaseit.net From francisgavila at yahoo.com Sun Nov 30 02:19:17 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 30 Nov 2003 02:19:17 -0500 Subject: Importing from a file to use contained variables References: Message-ID: Jeff Wagner wrote in message ... >On 29 Nov 2003 21:04:25 GMT, bokr at oz.net (Bengt Richter) wrotf: > >What is a generator maker? My advice is not to play around with this until you get the basics down, because generators and generator functions embody a number of very advanced concepts. I make it sound scary, but really all it is is this: def count(): #Defines a generator factory. n = 0 while n < 10: yield n n += 1 mycounter = count() #Gets a generator instance from the factory. mycounter.next() # returns 0. for i in mycounter: print i, # prints "1 2 3 4 5 6 7 8 9" Generators are a strange mix of functions and classes: using the 'next' method of a generator, execution advances to the next "yield" statement, where it then "returns" whatever's to the right of the 'yield'. When the generator hits a real or implied 'return', it raises a StopIteration exception, and stops for good. The 'for' statement and other things like list() all use these next() and StopIteration things implicitly. This behavior is part of the "generator protocol", and anything that implements it can be used as a generator. Generators are nifty because they are very fast, use very few resources, and can make many complex state-related problems easier to code. They're relatively new to Python--few languages have anything like them at all. They're not a must-have, but they are very useful. Now stay away from them until you know what you're doing. ;) -- Francis Avila From http Sat Nov 1 11:50:32 2003 From: http (Paul Rubin) Date: 01 Nov 2003 08:50:32 -0800 Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0310312008.ce341ea@posting.google.com> <87r80sdyb1.fsf@pobox.com> Message-ID: <7xn0bg6njb.fsf@ruckus.brouhaha.com> jjl at pobox.com (John J. Lee) writes: > It's hard to see how somebody (apparently) falsely claiming the > bankruptcy of a company can be described as behaving honestly. The claim that I see is that: Basically, the answer is TKC is bankrupt. TKC's team of developers have not been paid for over 5 months (some even longer). The word "bankrupt" is qualified by the word "basically" which I take to mean that TKC is out of money but there has not yet necessarily been a legal filing of bankruptcy. On the other hand, the claim that the dev team hasn't been paid for >= 5 months is specific and either true or false. Are you saying that the claim is false and that the developers have actually been paid within the past 5 months? From radam2 at tampabay.rr.com Sat Nov 1 13:29:55 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Sat, 01 Nov 2003 18:29:55 GMT Subject: My first Python program.. Calculating pi geometrically. References: <3fa39a91$0$58703$e4fe514c@news.xs4all.nl> Message-ID: On Sat, 01 Nov 2003 12:35:45 +0100, Irmen de Jong wrote: >Ron Adam wrote: > >> Doing it geometrically was strictly a learning exercise. And I did >> learn quite a bit by doing it. > >And you only scratched the surface of what Python offers you :-) >While it's nice to hear that you learned a lot by making this >arithmetic python program, it certainly is not the most >inspiring thing that Python is capable of... > >I even think you learned more about calculating Pi than you >did about programming in Python ;-) > >--Irmen The challenging parts were, figuring out how to do the calculation without using sin or cos, (nice geometry refresher), getting the gmpy module to work and how to set the precision, and working out by trial and error the precision calculation. If there is a formula to convert digits of precision to bits of precision, I'd like to know. And the last was to figure out how to use the clock and timedelta functions. Other interesting things I learned was how to convert to and from stings, use slices, and for-in loops are very fast for small lists, but can eat up a lot of memory, hit the swap file and be extremely slow for large lists. For-in loops aren't suited for everything. And yes, before I started, I did not know how to calculate pi. So you are right about that. ;-) That was an interesting subject in it self. Overall, it was a very good learning project. _Ron From tweedgeezer at hotmail.com Wed Nov 5 09:46:00 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 5 Nov 2003 06:46:00 -0800 Subject: PEP 289: universal and existential operators References: <5d83790c.0310231158.65595858@posting.google.com> Message-ID: <698f09f8.0311050646.8767d19@posting.google.com> austin at smartobject.biz (Jess Austin) wrote in message news:... > This is great. I'd like to request that alltrue() and anytrue() be > renamed forall() and exists(), repsectively. While these are the mathematical names, I've almost always seen them named "all" and "any" in the various (mostly functional) programming languages I've seen them in. Exists() also has the problem that to less mathematically-minded people (or Perl programmers :)) it isn't exactly clear what it's checking for. Certainly, one would expect a generator expressions like "x%y for y in xrange(2, math.sqrt(x))" to "exist," since we can see it in the code and look at it with our own eyes. I think these names also read somewhat more clearly: # Check if someone is yelling: if all(str.isupper, line.split()): print "Must be a flamewar." and: # Check if someone yelled at all: if any(str.isupper, line.split()): print "Someone yelled." I believe both these examples are more easily readable with "all" and "any" than they would be with "forall" and "exists." Jeremy From try_vanevery_at_mycompanyname at yahoo.com Wed Nov 12 20:58:21 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Wed, 12 Nov 2003 17:58:21 -0800 Subject: What do you think of this Python logo? References: Message-ID: Ok, enough comments have passed by, that I'll break silence and offer some insights into the thought process behind this logo. I first wanted to get initial reactions without moving anyone's opinions in any particular direction. Kevin Ollivier wrote: > > Have you considered trying a design with a slithering snake? (Like on > O'Reilly's Python Library Reference.) Yes, we have. There are 3 kinds of snakes we have considered: 1) realistic snakes 2) abstract graphical snakes 3) cute, cuddly snakes For general marketing purposes, we rejected (1) because a lot of Judeo-Christians fear and loathe snakes. We don't want them mixing up Python with their antipathy to snakes. Please note that fear of snakes is not a universal; Hindus, for instance, like snakes quite a bit. We should be able to sell many Python products and services in India. :-) We rejected (3) because one of our goals is to make a logo that Suits respond favorably to. Suits do not respect cutesy wootsy stuff, they will reject such technologies as "not serious." Here, it is important to realize that Suits and Techies have profoundly dissimilar tastes. Techies love Nerf rockets and Muppet marketing; Suits loathe it. This leaves us with (2), snakes as abstract design elements. If we use them at all. I do believe that marketing campaigns should be directed at Techies, Suits, and Educators, that all of these bases need to be covered to grow Python's user base as much as possible. But, they should be separately focused campaigns, and the Python logo should appeal to all of these parties. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA Brandon's Law (after Godwin's Law): "As a Usenet discussion grows longer, the probability of a person being called a troll approaches one RAPIDLY." From s.meyer at technology-network.de Thu Nov 6 09:10:49 2003 From: s.meyer at technology-network.de (Sebastian Meyer) Date: Thu, 06 Nov 2003 15:10:49 +0100 Subject: Strange problems with encoding References: <7h31xslhb6e.fsf@pc150.maths.bris.ac.uk> Message-ID: On Thu, 06 Nov 2003 13:39:25 +0000, Michael Hudson wrote: > "Sebastian Meyer" writes: > >> Hi newsgroup, >> >> i am trying to replace german special characters in strings like >> str = re.sub('?', 'oe', str) > > 1) str is the name of a builtin -- often a bad idea to use that as a > variable name. it was only the example name for the variable, be sure that dont use any builtins as variable names maybe not a good example ... thanks for the hint > > 2) I presume `str' is a unicode string? Try writing the literal as > u'?' instead (and adding the appropriate coding cookie to your > source file if using Python 2.3). Or I guess you could write it > > u'\N{LATIN SMALL LETTER O WITH DIAERESIS}' i ll try and report back... > > Cheers, > mwh From gk_2345 at yahoo.com Wed Nov 5 23:05:53 2003 From: gk_2345 at yahoo.com (George Kinney) Date: Wed, 5 Nov 2003 23:05:53 -0500 Subject: newbie: question about "__repr__" References: <6143ac23.0311051814.4d9908f@posting.google.com> Message-ID: <0Njqb.1668$mv2.13366@cletus.bright.net> "chenyu" wrote in message news:6143ac23.0311051814.4d9908f at posting.google.com... > Hi, > I have read others' code for study, and found one built-in function > "__repr__". Could anyone give me an simple example for explaining > "when and how" to use it. The customary use of __repr__ is for it to return a string that can be passed to eval() and re-create the object. So for a class 'foo' that takes one string in its __init__, __repr__ might return "foo('astring')". From rkoenig at ginko.de Mon Nov 17 16:02:03 2003 From: rkoenig at ginko.de (Reinhard Koenig) Date: Mon, 17 Nov 2003 22:02:03 +0100 Subject: Python 2.3, win32all-157, AttributeError: wdFormatText References: <5244802.0310192318.76e2310f@posting.google.com> Message-ID: <3FB9374B.F27E4F07@ginko.de> Hello, I needed the display statement for demonstration purposes only. You are right, that ordinarily I have to assign the result to a variable. The solution is that the makepy utility generated a wrong file name for the Microsoft Word object library resp. Python looked for a wrong name. The part after 'x' (00020905-0000-0000-C000-000000000046x409x8x0.py) was wrong. Now all works fine with win32all-163 resp. ActivePython2.3.2-132. Reinhard Koenig Bob Gailer wrote: > > At 01:18 AM 10/20/2003, Reinhard Koenig wrote: > > >Hello, > > > >I' m using Python 2.3, win32all-157 under W2K. I've applied the makepy > >utility for the Word 8.0 object library. I now receive: > > > >Python 2.3.1 (#47, Sep 23 2003, 23:47:32) [MSC v.1200 32 bit (Intel)] > >on win32 > >Type "help", "copyright", "credits" or "license" for more information. > > >>> import win32com.client > > >>> win32com.client.Dispatch("Word.Application") > > > > Shouldn't you assign the result of the Dispatch to a variable, then > reference that variable in subsequent code? > >>> app = win32com.client.Dispatch("Word.Application") > [snip] > > Bob Gailer > bgailer at alum.rpi.edu > 303 442 2625 > > -------------------------------------------------------------------------------- > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.525 / Virus Database: 322 - Release Date: 10/9/2003 From for_usenet2000 at yahoo.de Mon Nov 3 11:53:19 2003 From: for_usenet2000 at yahoo.de (Daniel Schüle) Date: Mon, 3 Nov 2003 17:53:19 +0100 Subject: None References: Message-ID: thank you all for answears From peter at engcorp.com Sat Nov 1 15:18:25 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 01 Nov 2003 15:18:25 -0500 Subject: Py2exe still won't run References: Message-ID: <3FA41511.47DB7A5D@engcorp.com> Ray wrote: > > OK I'm clueless.. > How do you run py2exe on windows, I've tried the dos prompt and get > 'python not recognized', also tried python prompt and got a 'syntax > error' message Can you post the *exact* error messages you actually got? Don't try to simplify or translate, as that only makes the effort to help you harder. In fact, just use copy-and-paste to put the precise text into your email. By the way, it seems likely you don't have the directory containing python.exe in your PATH environment variable. None of this would be a py2exe problem, merely one running Python itself. Check the FAQ entry http://www.python.org/doc/faq/windows.html#how-do-i-run-a-python-program-under-windows for more information to help you get started. -Peter From aleaxit at yahoo.com Sat Nov 1 10:50:02 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 01 Nov 2003 15:50:02 GMT Subject: prePEP: Decimal data type References: Message-ID: John Roth wrote: > Lots of comments in line. See especially the comment > about *NOT* wanting limited precision, as envisioned > in the referenced decimal *floating point* standards. ... > Since we've got infinite precision integer arithmetic, going to > limited precision decimal arithmetic is, IMNSHO, a step backwards. There may be a niche for a Rational data type, but in MHO it cannot take the place of a limited-precision-decimal (fixed or float). I suggest you think of a separate PEP to propose Rational (check the existing and rejected ones first, there may be some that are relevant) rather than attacking this one. I think Guido will never accept rationals becoming as widespread as they were in ABC (the default noninteger type) and is on record as saying that. The performance implications of the fact that summing two rationals (which take O(M) and O(N) space respectively) gives a rational which takes O(M+N) memory space is just too troublesome. There are excellent Rational implementations in both pure Python and as extensions (e.g., gmpy), but they'll always be a "niche market" IMHO. Probably worth PEPping, not worth doing without Decimal -- which is the right way to represent sums of money, a truly major use case in the real world. (Facundo, I think you should include these considerations in the PEP to explain why you're NOT going for rationals.) >> if otherType is a string: >> >> g. an exception is raised >> h. otherType is converted to Decimal >> i. Decimal is converted to string (bizarre, huh?) > > The "other type" should be handled in the same way the decimal() > constructor would handle it. I think this total breach with Python tradition would be a terrible mistake. 23+"43" is NOT handled in the same way as 23+int("45"), and a VERY good thing that is too. It's a completely different thing for a user to EXPLICITLY indicate they want construction (conversion) and to just happen to sum two objects one of which by mistake could be a string. (Facundo, perhaps it's worth it for the PEP to point this out explicitly, too; part of a PEP's purpose is to record the highlights of the discussion and design choices that had to be made). Alex From magnus at thinkware.se Thu Nov 27 18:03:46 2003 From: magnus at thinkware.se (Magnus Lyck?) Date: 27 Nov 2003 15:03:46 -0800 Subject: Python bug? Named parameters in recursive calls sometimes confuses python? Message-ID: <258fd9b8.0311271503.c134a25@posting.google.com> Something really strange is happening to me (sometimes). I'm using Python 2.3.2 on NT 4.0 as well as win32all-157, adodbapi and db_row. During a recursive call to a method, it seems Python messes up its variable bindings once in a while. Suddenly, one of several local variables gets rebound to the object it was bound to one step up in the recursion. The relevant part of the code looks like this with print statements that show the problem. This problem only seems to occur for certain input to my program. Note that I print the same variables and object IDs three times, and suddenly, a variable has changed its binding (without any reassignment) to the value it had one level up in the recursion. def recursiveCopy(self, table, column, old_val, new_val): # Fetch row from source database print "1. Column %s (%i) Table %s (%i)" % (column, id(column), table, id(table)) sql = "SELECT * FROM %(schema)s.%(table)s WHERE %(column)s = ?" rows = self.src_fetch(sql, params=(old_val,), table=table, column=column) # I use "sql % kwargs" in a method called by src_fetch print "2. Column %s (%i) Table %s (%i)" % (column, id(column), table, id(table)) for row in rows: # Replace foreign key with value for target DB print "3. Column %s (%i) Table %s (%i)" % (column, id(column), table, id(table)) row[column] = new_val # <= This is where it crashes. # What's interesting is the print above before the crash. # row is a db_row.IMetaRow instance instance. # We need primary key values for recursive find # Only bother for table with a single p.k. parent_p_key_cols = self.getPK(table) if len(parent_p_key_cols) == 1: parent_p_key_col = parent_p_key_cols[0] oldId = row[parent_p_key_col] newId = self.insertIntoTarget(table, row) for child_table, column in self.getDepTables(table, parent_p_key_col): self.recursiveCopy(child_table, column, oldId, newId) The output looks like this: 1. Column G06_PERS_INTRID (9282024) Table TGANST (9282768) 2. Column G06_PERS_INTRID (9282024) Table TGANST (9282768) 3. Column G06_PERS_INTRID (9282024) Table TGANST (9282768) 1. Column G60_ANSTID (9283512) Table TGANSTOV (10002536) 2. Column G60_ANSTID (9283512) Table TGANSTOV (10002536) 1. Column G08_ANSTID (10003232) Table TGANSTU (10002920) 2. Column G08_ANSTID (10003232) Table TGANSTU (10002920) 3. Column G08_ANSTID (10003232) Table TGANSTU (10002920) 1. Column G15_ANSTID (10002704) Table TGBELOPP (10003184) 2. Column G15_ANSTID (10002704) Table TGBELOPP (10003184) 1. Column G45_ANSTID (10002752) Table TGLED (9282672) 2. Column G45_ANSTID (10002752) Table TGLED (9282672) 1. Column G46_ANSTID (10002728) Table TGLON (10002512) 2. Column G46_ANSTID (10002728) Table TGLON (10002512) 3. Column G46_ANSTID (10002728) Table TGANST (9282768) <= N.B. Table magically morphed. Traceback (most recent call last): File "D:\NYPONVerktyg\Test\masterexport\get_person.py", line 364, in ? main() File "D:\NYPONVerktyg\Test\masterexport\get_person.py", line 336, in main move() File "D:\NYPONVerktyg\Test\masterexport\get_person.py", line 254, in move transfer.start(pnr) File "D:\NYPONVerktyg\Test\masterexport\get_person.py", line 181, in start self.recursiveCopy(table, column, old_pnr, new_pnr) File "D:\NYPONVerktyg\Test\masterexport\get_person.py", line 164, in recursiveCopy self.recursiveCopy(child_table, column, oldId, newId) File "D:\NYPONVerktyg\Test\masterexport\get_person.py", line 154, in recursiveCopy row[column] = new_val File "D:/NYPONVerktyg/Test/masterexport\db_row.py", line 526, in __setitem__ self.fields.__setitem__(key,value) File "D:/NYPONVerktyg/Test/masterexport\db_row.py", line 370, in __setitem__ setattr(self, i, value) File "D:/NYPONVerktyg/Test/masterexport\db_row.py", line 456, in __setattr__ super(IFieldsBase, self).__setattr__(key.lower(),value) AttributeError: 'irow_fields' object has no attribute 'g46_anstid' Note that the 'table' variable (which is bound to a unicode object) changed value from TGLON to TGANST and id from 10002512 to 9282768. I.e. we seem to have jumped up one step in the stack. But the 'column' variable stayed unchanged, so we haven't popped the stack frame either! Actually, it's even more weird. The table TGLON is empty, so self.src_fetch ought to have returned an empty 'rows' variable, in which case we wouldn't go into the loop, and would never see 'print "3. ...' Even though "print 2" says TGLON, it seems TGANST is what got into the call of self.src_fetch, and since DB2 didn't complain, it seems column actually have the value G06_PERS_INTRID at that time (???). (Alternatively, we also reverted to a previous rows-object?) If I change the variable names to avoid "column=column" etc like this... def recursiveCopy(self, table_, column_, old_val, new_val): # Fetch row from source database print "1. Column %s (%i) Table %s (%i)" % (column_, id(column_), table_, id(table_)) sql = "SELECT * FROM %(schema)s.%(table)s WHERE %(column)s = ?" rows = self.src_fetch(sql, params=(old_val,), table=table_, column=column_) ...the problem seems to go away. (But it only occurred for some input anyway. Maybe it just moved...) From see_signature__ at hotmail.com Wed Nov 19 01:31:24 2003 From: see_signature__ at hotmail.com (Georgy Pruss) Date: Wed, 19 Nov 2003 06:31:24 GMT Subject: Too much builtins (was Re: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com><653b7547.0311121826.65b6b2d4@posting.google.com> <37xub.23208$C14.952050@twister.southeast.rr.com> Message-ID: <07Eub.26516$C14.1106803@twister.southeast.rr.com> "Andrew Dalke" wrote in message news:HdDub.5445$sb4.4376 at newsread2.news.pas.earthlink.net... | Georgy Pruss: | > BTW is there some Python's equivalents to C's strspn, strcspn, strpbrk, | > which return a leading sub-string, entirely [not] consisting of characters | > of some char.set; and something like strtoul which parses the string and | > returns the number and the position where the scan ended? | | Not directly. In Python those are most often done with regexps. | Eg, | | import re | def strspn(s, t): | # kinda slow way to construct the pattern, but it does correctly | # handle the '-' and ']' cases. Usually one would write the regexp | # directly and not try to get close to the C API. | pat = re.compile("(" + "|".join(map(re.escape, t) + ")*") | m = pat.match(s) | if not m: | return 0 | return m.end() Yes, thanks. Especially with regex'es it's just a matter of a minute or two. I miss those C functions though. G-: | <...> | Andrew | dalke at dalkescientific.com From dietrich at zdome.net Tue Nov 18 17:26:30 2003 From: dietrich at zdome.net (Dietrich Epp) Date: Tue, 18 Nov 2003 14:26:30 -0800 Subject: Reading a Bitstream In-Reply-To: <6250403b.0311180728.4e4c1d10@posting.google.com> References: <6250403b.0311180728.4e4c1d10@posting.google.com> Message-ID: <42012D2A-1A16-11D8-BC3A-0003934ACDEC@zdome.net> On Nov 18, 2003, at 7:28 AM, Miki Tebeka wrote: > Hello Dietrich, > >> Are there any good modules for reading a bitstream? Specifically, I >> have a string and I want to be able to get the next N bits as an >> integer. Right now I'm using struct.unpack and bit operations, it's a >> bit kludgy but it gets the right results. > Have you looked at 'array' and 'xdrlib.Upnacker'? Both of those look like they're aligned to byte boundaries. Am I mistaken? The file I'm reading has fields ranging from 1 to 32 bits wide, and they are packed bit-to-bit. I guess I'll write my own module. From martin at v.loewis.de Fri Nov 28 01:29:21 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 28 Nov 2003 07:29:21 +0100 Subject: Python bug report on SF, what now? References: <3fc660c2$0$1492$e4fe514c@news.xs4all.nl> <87ekvtmlj5.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) writes: > > It will be noticed automagically. As it has a patch associated, you > > should have submitted it as a patch, though - some of us (including > > myself) give patches higher priority, as they indicate that the > [...] > > Same for wishlist items with patches? Or should they go in RFE > (Requests For Enhancement)? Same for wishlist items: They wouldn't be just wishes, but they would be new features. If the new feature is not universally accepted, you might need to write a PEP, too. Regards, Martin From news at grauer-online.de Wed Nov 26 13:50:40 2003 From: news at grauer-online.de (Uwe Grauer) Date: Wed, 26 Nov 2003 19:50:40 +0100 Subject: kinterbas db column type In-Reply-To: References: Message-ID: Gandalf wrote: > >>>> i need to know the database column types returned by kinterbasdb. >>>> Implicit type conversion is i nice thing to have, but it hides the >>>> real types in the database. >>>> So how could i get this information? >>> >>> >>> >>> RDB$RELATIONS - this stores table information >>> RDB$FIELDS - this is for the fields (here you have the RDB$FIELD_TYPE >>> field) >>> RDB$RELATION_FIELDS - connects relations to fields >>> >> Does this mean, that the kinterbasdb isn't DB-API 2.0 compliant? >> > It is DB-API 2.0 compilant. I'm sorry, maybe I misunderstood you. This > is a way > to get the column types in InterBase inside. Do you want to know the > Python types > in the row returned by .fetch()? > > Sorry Gandalf, more explanation: It's different from other modules cause it does a implicit type conversion to the Python-types. So for a DATETIME-column in mysql you get a type_code 12 (which is indeed DATETIME in MySQLdb) but in kinterbasdb you get t_tuple. This does not help me very much since the information i need is different from what i get. Uwe From aahz at pythoncraft.com Wed Nov 5 19:35:25 2003 From: aahz at pythoncraft.com (Aahz) Date: 5 Nov 2003 19:35:25 -0500 Subject: Food at Pycon References: Message-ID: In article , Kendall Clark wrote: >On Sun, Nov 02, 2003 at 01:55:48AM -0500, Aahz wrote: >> >> I'm saddened that you chose not to write a balanced post about the >> subject, so here is some additional information for people: > >Balanced or not, I have to agree with Laura. The food at PyCon earlier >this year was awful, especially for those of us who are >vegetarian. While, as a vegetarian, I'm used to getting treated like a >2nd class citizen at geek conferences, the vegetarian options at PyCon >were terrible. Of course, this is just about the only bad thing I can >say about the conference, but since the subject has come up... Well, given the forcefulness of Laura's non-vegetarian comments, I doubt you can fairly claim that you were being treated as a second-class citizen this time. ;-) >Now I live in DC, near to the conference site, and will certainly be >at the next one; I'd appreciate the chance to not subsidize other >people's food consumption which I find morally problematic. Or, if I >do have to subsidize them, I'd at least like to have something I can >eat which is tasty and inoffensive. More seriously, I think almost everyone who goes to a conference ends up subsidizing some activity that others want and they don't. We can certainly make more effort to accomodate a variety of food needs, but given the wide variety of needs that I'm aware of, I doubt we'll cover everything. Here's what we probably have to deal with in dietary restrictions: low-fat, low-carb, vegetarian, vegan, kosher, wheat-free. That doesn't even count the people who dislike what we provide but don't actually have a "food need" (like Laura). But I think that providing food is overall a social good for a conference because of the convenience factor in promoting conversation. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From reply.in.the.newsgroup at my.address.is.invalid Fri Nov 21 04:25:46 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 21 Nov 2003 10:25:46 +0100 Subject: Details on exceptions References: <3fbd7509$0$1749$5a62ac22@freenews.iinet.net.au> <3fbd7c7c$0$1746$5a62ac22@freenews.iinet.net.au> <3fbd8e56$0$1755$5a62ac22@freenews.iinet.net.au> Message-ID: Derek Fountain: >except IOError, (errno, strerror): > >The target is a tuple of 2 variable names so how can it bind "the exception >object" to them? The documentation for try/except says that "the >exception's parameter is assigned to the target". So what, exactly, is an >"exception's parameter"? "For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is ``compatible'' with the exception. An object is compatible with an exception if it is either the object that identifies the exception, or (for exceptions that are classes) it is a base class of the exception, or it is a tuple containing an item that is compatible with the exception." http://www.python.org/doc/current/ref/try.html#try I think it has to do with the introduction of exceptions-are-classes in 1.5, and backwards compatibility of older code: "This works because the tuple-unpack semantics have been loosened to work with any sequence on the right-hand size (see the section on Sequence Unpacking below), and the standard exception classes can be accessed like a sequence (by virtue of their __getitem__ method, see above)." http://www.python.org/doc/essays/stdexceptions.html I'd say don't do it. Use exception objects and catch them as objects. -- Ren? Pijlman From usenet at soraia.com Mon Nov 24 13:45:37 2003 From: usenet at soraia.com (Joe Francia) Date: Mon, 24 Nov 2003 18:45:37 GMT Subject: Database connectivity In-Reply-To: References: Message-ID: SectorUnknown wrote: > I've written a database (Access mdb) front-end using Python/wxpython/and > ADO. However, the scope of the project has changed and I need to access > the same data on an MSSQL server. Also, the front-end needs to be cross- > platform (Windows and Linux). > > Does anyone have any suggestions on what database connectivity I should > use? I've looked at mxODBC and wxODBC briefly, but am not sure what is > the best way to go. > > BTW, although I would love to move away from the MSSQL server, that's > not going to change. Besides mxODBC, I know of two others: Windows only: http://adodbapi.sourceforge.net/ Cross-platform: http://sourceforge.net/projects/pymssql/ Peace, Joe From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Thu Nov 13 10:25:14 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Thu, 13 Nov 2003 18:25:14 +0300 Subject: source code of a function object In-Reply-To: <5167rv812n95t978ie9spciso2ru2cojuj@4ax.com> References: <5167rv812n95t978ie9spciso2ru2cojuj@4ax.com> Message-ID: Fernando Rodriguez wrote: > Hi, > > Is ti possible to get the source code of a given function object? O:-) > > TIA I'm not an expert, but I'd say that mostly yes, however: def foo(): pass bar_code_block = compile('def bar(): pass', '', 'exec') exec bar_code_block import inspect assert 'foo' in locals() print inspect.getsource(foo) assert 'bar' in locals() print inspect.getsource(bar) Python2.3: def foo(): pass Traceback (most recent call last): File "source.py", line 13, in ? print inspect.getsource(bar) File "D:\Python23\lib\inspect.py", line 549, in getsource lines, lnum = getsourcelines(object) File "D:\Python23\lib\inspect.py", line 538, in getsourcelines lines, lnum = findsource(object) File "D:\Python23\lib\inspect.py", line 408, in findsource raise IOError('could not get source code') IOError: could not get source code Therefore, I'd suggest that you can get source code of functions that are not created with eval/exec etc. of course, you cannot get source code of C functions (e.g. most of builtins, I suppose). regards, anton. From Kyler at news.Lairds.org Tue Nov 4 08:13:27 2003 From: Kyler at news.Lairds.org (Kyler Laird) Date: Tue, 04 Nov 2003 13:13:27 GMT Subject: Selling Python Software References: <3FA614DA.E88331E2@alcyone.com> Message-ID: <55kk71-g3e.ln1@jowls.lairds.org> Alex Martelli writes: >> It's always possible to decompile programs compiled to machine code, as >> well, you know. Ultimately, every software developer must defend >> himself with licenses and legal means, not technical ones. >...unless said SW developer keeps the extremely precious parts of his >SW safely on a network server under his control (yes, it IS possible >to technically secure that -- start with an OpenBSD install...:-) and >only distributes the run-of-the-mill "client-oid" parts he doesn't >particularly mind about. I can imagine the "client-oid" part being a simple shell script that just runs SSH (perhaps with some tunnel commands for database connections). Especially for a command-line app, this seems like an *easy* and complete answer. Heck, for some situations, it might even be considered the final product. It'd be a snap for the developer to maintain. --kyler From theller at python.net Thu Nov 20 10:10:33 2003 From: theller at python.net (Thomas Heller) Date: Thu, 20 Nov 2003 16:10:33 +0100 Subject: best Wx editor References: Message-ID: "Jason Tesser" writes: > What is the best overall ide studio that can be used to develop > crossplatform apps (win,linux,mac) for python? XEmacs. Thomas From jjl at pobox.com Tue Nov 25 06:58:14 2003 From: jjl at pobox.com (John J. Lee) Date: 25 Nov 2003 11:58:14 +0000 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <7xad6sb7cd.fsf@ruckus.brouhaha.com> <87smkjw55g.fsf@pobox.com> <7xy8ubdl1f.fsf@ruckus.brouhaha.com> <87smkitutw.fsf@pobox.com> Message-ID: <8765h8y814.fsf@pobox.com> mlh at furu.idi.ntnu.no (Magnus Lie Hetland) writes: > In article <87smkitutw.fsf at pobox.com>, John J. Lee wrote: [...] > How about using rot13? At least it's build-in ;) Built in to emacs, too, unfortunately (though I've admitted all this probably doesn't matter, see my earlier post). > Wasn't the Adobe encryption for eBooks (which Sklyarov was imprisoned > for "cracking") something close to rot13? [...] That was XOR, I think. John From wilkSPAM at OUTflibuste.net Fri Nov 28 06:38:45 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Fri, 28 Nov 2003 12:38:45 +0100 Subject: python-dev Summary for 2003-10-16 through 2003-11-15 References: Message-ID: <87fzg82056.fsf@blakie.riol#flibuste.net> "Brett C." writes: > python-dev Summary for 2003-10-16 through 2003-11-15 > ++++++++++++++++++++++++++++++++++++++++++++++++++++ > This is a summary of traffic on the `python-dev mailing list`_ from > October 16, 2003 through November 15, 2003. 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 twenty-eighth and twenty-ninth summaries written by Brett > Cannon (does anyone even read this?). Yes we do, you could ask this question in the end of the summary ;-)... And thanks also do rst-docutils, it's very clear. -- Wilk - http://flibuste.net From frr at easyjob.net Thu Nov 20 09:00:03 2003 From: frr at easyjob.net (Fernando Rodriguez) Date: Thu, 20 Nov 2003 15:00:03 +0100 Subject: good book on multithreaded programming with Python References: Message-ID: On Wed, 19 Nov 2003 13:34:29 -0000, claird at lairds.com (Cameron Laird) wrote: >In article , >Fernando Rodriguez wrote: >>Hi, >> >>Any recommendation for a good book on multithreaded programming with Python? > . > . > . >Do you *really* want > concurrent programming with Python >or > programming with Python's threads >or > Python programming with low-level threads >or > ...? An introduction to general concurrent programming concepts, using python for the examples. From http Mon Nov 17 15:07:30 2003 From: http (Paul Rubin) Date: 17 Nov 2003 12:07:30 -0800 Subject: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <8hfsb.7707$nz.895@newsread2.news.pas.earthlink.net> Message-ID: <7x65hiahdp.fsf@ruckus.brouhaha.com> Ville Vainio writes: > I wouldn't mind Python getting more influence from functional realm, > as Python seems to me to be *the* hybrid language that can pull the FP > thing while still remaining practical and intuitive (and delightfully > non-academic). Python sometimes seems to go out of its way to thrwart the use of functional style. Look at list.sort returning None, for example. From bignose-hates-spam at and-benfinney-does-too.id.au Thu Nov 13 00:27:25 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 13 Nov 2003 16:17:25 +1050 Subject: True inconsistency in Python References: Message-ID: On Wed, 12 Nov 2003 19:42:27 -0800, Scott Chapman wrote: > There seems to be an inconsistency here: Yes. The inconsistency is in expecting all Boolean truths to be the same value. The object True will evaluate as a Boolean truth. The object False will not evaluate as a Boolean truth. This doesn't mean that there are no other values that will or won't evaluate as Boolean truth. You many want to read the PEP that led to the creation of the 'bool' type (and True and False objects): In short: Testing the Boolean truth of an expression is done with 'if', not with value-comparison operators. -- \ "bash awk grep perl sed, df du, du-du du-du, vi troff su fsck | `\ rm * halt LART LART LART!" -- The Swedish BOFH, | _o__) alt.sysadmin.recovery | Ben Finney From domma at procoders.net Wed Nov 19 16:59:32 2003 From: domma at procoders.net (Achim Domma) Date: Wed, 19 Nov 2003 22:59:32 +0100 Subject: PIL and jpg -> png conversion, do I really need java for this??? References: Message-ID: Hi Vincent, after a lot of problems with our server, I just got the PythonMagick website up and running again. If PNGs generated from ImageMagick work, it might be of help to you. Just have a look: http://www.procoders.net/pythonmagick regards, Achim From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Nov 27 15:38:25 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 27 Nov 2003 21:38:25 +0100 Subject: Python bug report on SF, what now? Message-ID: <3fc660c2$0$1492$e4fe514c@news.xs4all.nl> Hi I've submitted a bug report on Sourceforge (http://sourceforge.net/tracker/?func=detail&aid=839496&group_id=5470&atid=105470) but am wondering what to do next? Should I have assigned it to somebody, or will it be noticed 'automagically'...? Sorry for being ignorant in this matter... --Irmen. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Nov 27 15:26:31 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 27 Nov 2003 21:26:31 +0100 Subject: Python is used in Cyan's 'URU Ages of Myst' Message-ID: <3fc65df8$0$1494$e4fe514c@news.xs4all.nl> Hello, some trivia for whom it may concern: I've just downloaded and played the demo of Cyan's new game "URU Ages of Myst". Wonderful-game-but-crappy-controls yadda yadda, but that's not the subject here. I noticed that they're using Python in the game, probably to script the game engine :-) (There is a Python folder in the game install directory and it contains a packed python plus two extension modules). --Irmen de Jong. From newsgroups at jhrothjr.com Mon Nov 17 17:59:24 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 17 Nov 2003 17:59:24 -0500 Subject: PEP 321: Date/Time Parsing and Formatting References: <20031117161752.GA17615@nl.linux.org> Message-ID: "Gerrit Holl" wrote in message news:mailman.803.1069091744.702.python-list at python.org... > Hi, > > PEP 321 reads: > > Python 2.3 added a number of simple date and time types in the > > ``datetime`` module. There's no support for parsing strings in various > > formats and returning a corresponding instance of one of the types. > > This PEP proposes adding a family of predefined parsing function for > > several commonly used date and time formats, and a facility for generic > > parsing. > > I was recently surprised by this fact. I don't know why there isn't > such a function/method. In my opinion, it isn't a question of whether > to add them or not, but how. > > > Input Formats > > ======================= > > > > Useful formats to support include: > > > > * `ISO8601`_ > > * ARPA/`RFC2822`_ > > * `ctime`_ > > * Formats commonly written by humans such as the American > > "MM/DD/YYYY", the European "YYYY/MM/DD", and variants such as > > "DD-Month-YYYY". I didn't notice this going past the first time: YYYY/MM/DD is the ISO standard format, DD/MM/YYYY is the European variant to the American MM/DD/YYYY. > > * CVS-style or tar-style dates ("tomorrow", "12 hours ago", etc.) The question here is class responsibilities. The datetime module is at a lower conceptual layer than the tarfile module. If the format is specific to the tarfile module, then it should be that module's responsibility to do the conversion. If it is a generally useful capability, then it should be the datetime module's responsibility. I'd like to see that discussed. > I think there should be a 'strptime' equivalent, on which the former > three input formats are build. I think the latter should be a class > method of Timedelta. Then, those examples would be used as such: > > >>> datetime.datetime.iso8601("1985-08-13 15:03") > datetime(1985, 8, 13, 13, 5) > >>> datetime.datetime.rfc2822("Tue, 13 Aug 1985, 15:03:00 +0100") > datetime(1985, 8, 13, 13, 5) > >>> datetime.date.strptime("13/08/1985", "%d/%m/%Y") > date(1985, 8, 13) > >>> datetime.timedelta.fromstring("tomorrow") > timedelta(1) As long as it's kept simple. I have a real problem with the second example; there are simply too many variations out there of the alphabetic month and day of the week to cover them all. > A rising question, especially in the latter case, is how to deal with > locale's. In the context of an strptime implemetation, there are really two issues: numeric date format and alphabetic date format. As far as numeric date format is concerned, a locale dependent "mm" and "dd" that would switch around depending on whether the locale used mm/dd/yyyy or dd/mm/yyyy dates would be adequate. yyyy/mm/dd can always be disambiguated for dates later than 1300 CE. (the 5th and 6th characters distinguish them adequately.) In terms of character months and days of the week, you need a facility to supply a function. This is getting too complex for my tastes. > > 1) Add functions to the ``datetime`` module:: > > > 2) Add class methods to the various types. There are already various > > class methods such as ``.now()``, so this would be pretty natural.:: > > > > import datetime > > d = datetime.date.parse_iso8601("2003-09-15T10:34:54") > > > > 3) Add a separate module (possible names: date, date_parse, parse_date) > > or subpackage (possible names: datetime.parser) containing parsing > > functions:: > > I prefer solution 2. I think it is the most object-oriented way. I agree. Class methods allow the system to be extended, module funtions don't. > And we > already have several date/time modules: datetime, time, calendar. I think > we should have only one, and have calendar integrated into time. I try > to avoid using the time module whenever I can. I don't like it. It doesn't > nicely fit into my brain, it isn't object-oriented, I think it is to much > low-level. I would *not* go for changing the existing calendar module. Probably too much of an impact to existing code, and datetime is supposed to be a replacement for time. > > > * Naming convention to use. > > * What exception to raise on errors? ValueError, or a specialized exception? > > * Should you know what type you're expecting, or should the parsing figure > > it out? (e.g. ``parse_iso8601("yyyy-mm-dd")`` returns a ``date`` instance, > > but parsing "yyyy-mm-ddThh:mm:ss" returns a ``datetime``.) Should > > there be an option to signal an error if a time is provided where > > none is expected, or if no time is provided? Explicit is better than implicit. I'd prefer a class method on the proper class. > > * Anything special required for I18N? For time zones? > > Using relative dates as input uses English input, so this one is suitable > for I18N. I'm not sure about .strptime() though... I don't think it should, > since 05/04/03 may yield entirely different results in different locale's, > which is not true for 'tomorrow'. Locale dependent format parsing is relatively easy: all it requires is a generic parse code that maps to two or three output variables. In other words, one parse code takes care of "mm/dd/yyyy", "dd/mm/yyyy" and "yyyy/mm/dd". The locale disambiguates which of the first two is required, with the ISO format (yyyy/mm/dd) being chosen based on positions 5 and 6). Notice that there is never an ambiguity if you have an alpha month and a 4 digit year. > > > Generic Input Parsing > > ======================= > > > > Is a strptime() implementation that returns ``datetime`` types sufficient? Should be a class method on all four classes, and return that class. > It would at least need to be in the datetime module. > > > Not all input formats need to be supported as output formats, because it's > > pretty trivial to get the ``strftime()`` argument right for simple things > > such as YYYY/MM/DD. Only complicated formats need to be supported; RFC2822 > > is currently the only one I can think of. If it's going to support I18N, then it should support the more common formats directly, or strftime() should support "macro" codes that generate a complete date with separators as one code. > > > > Options: > > > > 1) Provide predefined format strings, so you could write this:: > > > 2) Provide new methods on all the objects:: > > > > d = datetime.datetime(...) > > print d.rfc822_time() > > I prefer implementation #2. I'm never very happy with using constants > defined inside modules. I have to type 'module.CONSTANT' all the time... > I think a method is a very suitable way to do this. I'd like to reiterate my comment from earlier: Internet data handling modules are at a higher logical level than datetime. If the formats are not generally useful, it should be the using module that is responsible for them: that is, the email and news modules for RFC822. If they are, then it should be datetime. John Roth > > yours, > Gerrit. > From aleax at aleax.it Fri Nov 7 05:08:24 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 07 Nov 2003 10:08:24 GMT Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> Message-ID: Bob Gailer wrote: ... > One's prior programming experience can affect one's view of reduce. My > favorite language, prior to Python, was APL. APL's native data container > is the array, and reduce is a native operator in APL. So we used reduce a I've done a _lot_ of APL and APL2 (albeit well before I met Python -- basically in the 1978-1988 time frame) and I don't think that "affects my view of reduce" _in Python_ -- any more than (e.g.) having done a lot of Scheme would affect my view of lambda and tail recursion _in Python_, a lot of Icon that of generators, a lot of Perl that of RE's, ... Basically, the old quip about "coding Fortran in any language" does not apply to Fortran _only_: you can, up to a point, code (APL, Icon, Scheme, Perl, ...) in any language... but it's _still_ basically a bad idea. Mastering a language means (in part) mastering the idioms thereof -- what works well/smoothly/elegantly in that language, what most of that language's best practitioners _do_. Knowledge of other languages -- the more the merrier -- can help, giving you perspective, but in the end it shouldn't really affect your view of the target language. The reduce method of Numeric's ufuncs _is_ a good, close analogy for APL's reduce (more generally, APL concepts -- though not syntax -- do help a lot with Numeric, far more than they do with base Python). Numeric.add.reduce(xs) IS a perfect equivalent to APL's +/xs -- if xs is a Numeric.array (else the conversion overhead's gonna kill you:-): $ timeit.py -c -s'import Numeric' -s'import operator' -s'xs=range(9999)' 'reduce(operator.add, xs)' 100 loops, best of 3: 2.9e+03 usec per loop $ timeit.py -c -s'import Numeric' -s'import operator' -s'xs=range(9999)' 'Numeric.add.reduce(xs)' 10 loops, best of 3: 2.2e+04 usec per loop $ timeit.py -c -s'import Numeric' -s'import operator' -s'xs=range(9999)' 'sum(xs)' 1000 loops, best of 3: 1.15e+03 usec per loop $ timeit.py -c -s'import Numeric' -s'import operator' -s'xs=range(9999)' -s'xa=Numeric.array(xs)' 'Numeric.add.reduce(xa)' 10000 loops, best of 3: 54 usec per loop Yeah, I know, speed isn't everything. But when the speed of a perfectly analogous operation drops by two times (from reduce to sum) or even more when it drops by 50 times (from reduce on a list to Numeric.add. reduce on a Numeric.array) one _does_ get a sense of when one's using a language "reasonably idiomatically" -- within the design space of that language, within the pathways most often taken by the language's best practitioners and therefore most likely to be solid and optimized. > companion of reduce in APL is scan, which did reduce but preserved all the > intermediate values (cumulative sum for example). Yep, that's e.g. Numeric.add.accumulate in Numeric + Python. > To expand your reduce horizons in Python, consider reduce as a way to > examine the relationship between successive pairs of a sequence. For > example one might wants the difference between successive elements: given > seq = [1,3,4,7] we'd like a differences == [2,1,3]. > > differences = [] > def neighborDifference(left, right): > differences.append(right - left) > return right > reduce(neighborDifference, seq) def difs_reduce(seq): differences = [] def neighborDifference(left, right): differences.append(right - left) return right reduce(neighborDifference, seq) return differences def difs_zip(seq): return [ b-a for a, b in zip(seq,seq[1:]) ] import itertools def difs_izip(seq): return [ b-a for a, b in itertools.izip(seq,seq[1:]) ] def difs_loop(seq): differences = [] it = iter(seq) a = it.next() for b in it: differences.append(b-a) a = b return differences $ timeit.py -c -s'import a' -s'x=range(9999)' 'a.difs_reduce(x)' 100 loops, best of 3: 1.8e+04 usec per loop $ timeit.py -c -s'import a' -s'x=range(9999)' 'a.difs_zip(x)' 100 loops, best of 3: 1.8e+04 usec per loop so, the list comprehension with zip has just the same performance as the clever use of reduce -- and is far more concise. But if you're looking for speed, then the humble loop...: timeit.py -c -s'import a' -s'x=range(9999)' 'a.difs_loop(x)' 100 loops, best of 3: 9e+03 usec per loop ...is twice as fast! Simplicity isn't to be sneered at. And if you're keep for higher-level reasoning and expression, itertools is quite good for that: timeit.py -c -s'import a' -s'x=range(9999)' 'a.difs_izip(x)' 100 loops, best of 3: 7.6e+03 usec per loop a one-liner, and another 15% speed boost wrt the humble loop. [I can shave another 10% performance improvement with an experimental 'w2' type I've coded to do specifically the window-by-two job, but that small level of acceleration is probably not enough to justify an extra type...;-)] Yeah, I know, sigh, I come across as a micro-optimization freak, which most definitely _ISN'T_ the point. I'm using speed and concision as proxies for *idiomatic use* -- simplicity and elegance and maintainability... "elegance" &c we could argue about forever, so I go for numbers that aren't quite as arguable:-). I think reduce (like apply, filter, and probably map too) has had its day but really doesn't have enough good use cases any more, in this day and age of list comprehensions and iterator-tools, to justify its existence as a Python built-in except for legacy reasons. Alex From pythonguy at Hotpop.com Thu Nov 20 04:58:15 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 20 Nov 2003 01:58:15 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> <84fc4588.0311140319.3778de15@posting.google.com> <9eabe547.0311191757.2cc51af3@posting.google.com> Message-ID: <84fc4588.0311200158.765826ed@posting.google.com> Exactly my feelings on this topic :-) -Anand python473 at yahoo.com (John Howard) wrote in message news:<9eabe547.0311191757.2cc51af3 at posting.google.com>... > Let's say some one walked into a book store and glanced at the books > in computers. He might think, "gee look at all the books on java and > perl and hardly any books on python. What is python? And it's not even > in the languages section. No sense in looking at that!" It's a matter > of perception. "Lots of perl and java - that's the way to go." I also > agree that maybe a lot of books on python are not necessary to learn > the langage. Heck, I learned almost all I know (which I admit is not > much) from web tutorials and samples. But I do have questions I cannot > find the answers to when I browse the book store. Eg, how do I do > admin stuff with python? How do I do cgi stuff with python? There are > books on how to do these in perl. Dozens. > > pythonguy at Hotpop.com (Anand Pillai) wrote in message news:<84fc4588.0311140319.3778de15 at posting.google.com>... > > In the ideal "techie makes decisions" world this would have > > been a good thing. But not in the real world where the Suits > > make decisions in corporates. > > > > There might have been thousands of books published in C/C++ > > language and they have all helped to popularize it in one > > or the other way. Contrast, in the python world we have one > > Ale x Martelli, one Wesley Chun, one David Mertz, really > > countable by hand. > > > > There is a limit to how much a single person can evangelize > > a language. Questions similar to what the O.P posted arise > > from the listeners. > > > > I would prefer to see more books on Python though they all might > > be useless from a pure techie point of view. Let us have > > a book on Software Projects in python for example. It might not > > have the technical superiority of a Martelli book, but more > > attempts like that will save the language and help the > > eyeball factor, which is so important in practical marketing. > > > > -Anand > > > > afriere at yahoo.co.uk (Asun Friere) wrote in message news:<38ec68a6.0311132310.630e10e2 at posting.google.com>... > > > python473 at yahoo.com (John Howard) wrote in message news:<9eabe547.0311131610.4dd7819c at posting.google.com>... > > > > I've sent several messages over the last year asking about python - > > > > Who teaches python? Is python losing steam? etc. I have noticed, eg, > > > > the declinng number of books at my local borders. The last time I > > > > visited a borders (last week), there was 1 (sic) book about python on > > > > the shelve compared to dozens on perl & java! > > > > > > > > > If you were developing in Java or Perl maybe you would need dozens of > > > books. But Python is so elegant and intuitive a single one will do. > > > ;) From chenyu468 at hotmail.com Wed Nov 5 21:14:55 2003 From: chenyu468 at hotmail.com (chenyu) Date: 5 Nov 2003 18:14:55 -0800 Subject: newbie: question about "__repr__" Message-ID: <6143ac23.0311051814.4d9908f@posting.google.com> Hi, I have read others' code for study, and found one built-in function "__repr__". Could anyone give me an simple example for explaining "when and how" to use it. Thank you for your attention. kind regards/chenyu From alessandro at sephiroth.it Tue Nov 25 16:17:58 2003 From: alessandro at sephiroth.it (Alessandro Crugnola *sephiroth*) Date: Tue, 25 Nov 2003 21:17:58 GMT Subject: avoid multiple instance of the same application Message-ID: Hi, i've created a wxpython app, a text editor, and then I've created the .exe file and make in myOS the file associtation to this application. The problem is that when an instance of the application is already opened and i double click on a file, my system open another instance of the same file. So, the question.. how to avoid this and open the clicked file in the previos opened application? I've founded this piece of code on the net, this just to prevent multiple instance to be opened, but now the problem is how to tell to the first app "open" that file.. if wxPlatform == '__WXMSW__': # [ 838561 ] open file opens a new SEPY instance import win32event, win32api, win32gui, win32con myMutex = win32event.CreateMutex(None,-1,'sepy_mutex') if win32event.WaitForSingleObject(myMutex, 0) == 0: app = App(0) app.MainLoop() else: exeName = win32api.GetModuleFileName(0) sepyWindow = win32gui.FindWindow(0,exeName) if not(win32gui.IsWindowVisible(sepyWindow)): win32gui.PostMessage(sepyWindow, win32con.WM_USER, 0, 0) win32gui.SetForegroundWindow(sepyWindow) if len(sys.argv) > 1: # here call opennewfile... ?? sys.exit() else: app = App(0) app.MainLoop() -- Alessandro Crugnola [sephiroth] Flash | PHP Developer http://www.sephiroth.it Team Macromedia Volunteer for Flash http://www.macromedia.com/go/team Flash-php mailing list http://www.flash-php.it/index.php?ml=fpcoders&action=subscribe From robin at jessikat.fsnet.co.uk Wed Nov 5 13:16:36 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 5 Nov 2003 18:16:36 +0000 Subject: BUG? PyMem_Free vs strdup References: Message-ID: In article , Skip Montanaro writes ...... >Memory allocated by strdup() should almost certainly be freed with free(), >not PyMem_Free(). Yes you're right. > > Robin> Is there an easy way to get a grasp on the various memory > Robin> allocation functions? > >Sure. Keep your allocations and deallocations within the same family of >functions. ;-) > >Skip > in the beginning there was only the primordial heap and now I have PyMem_Free, art_free, free and probably gt1_free grrhhhh! They all used to commingle quite happily and seem to do so under the non-debug case, but now I suppose we're being stricter and stricter. I suppose M$ spends all its money on marketing and fails to get the best possible allocator. -- Robin Becker From zunbeltz at wm.lc.ehu.es.XXX Fri Nov 21 04:51:24 2003 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 21 Nov 2003 10:51:24 +0100 Subject: plataform dependent code Message-ID: Hi I am using wxPython and i want to have some code plataform dependent. Is it possible? I can't find any information about this in the net. TIA Zunbeltz -- Remove XXX from email: zunbeltz at wm.lc.ehu.esXXX From edreamleo at charter.net Sun Nov 9 09:24:02 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Sun, 9 Nov 2003 08:24:02 -0600 Subject: ANN: Leo 4.1 beta 1 An outlining editor References: Message-ID: > > A small request: please don't use spaces in directory or files names in > > your Leo distribution - use dashes or underscores if you need a > > separator. Spaces annoy the hell out of anyone using a command line > > interface. Yes, I do see spaces in the top-level directory of the zip files. I'm not sure where that name gets generated in the install script: I'll see if I can eliminate the spaces in future releases. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From martin at v.loewis.de Sun Nov 23 05:03:59 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 23 Nov 2003 11:03:59 +0100 Subject: Problems sending list/tuple to a C extension. References: Message-ID: seberino at spawar.navy.mil (Christian Seberino) writes: > I hope the mistake in this simple code is obvious to you: There are two errors in your code: > PyArg_ParseTuple(args, "(i)", &a); You MUST check the return value of PyArg_ParseTuple. Otherwise, if it gives an exception, you just continue with incorrect data, which is what happened here. > >>> test.test( (3) ) This does NOT pass a tuple, but an integer only. Use (3,) to display a tuple. Regards, Martin From tim.ronning at start.no Mon Nov 3 18:26:45 2003 From: tim.ronning at start.no (Tim Ronning) Date: Tue, 04 Nov 2003 00:26:45 +0100 Subject: TypeError: can't multiply sequence to non-int In-Reply-To: <20031103133306.BC11.PYTHON@essene.com> References: <20031103133306.BC11.PYTHON@essene.com> Message-ID: P? Mon, 03 Nov 2003 13:33:15 -0700, skrev Python : > Hello, > > I am just learning Python and am going through some examples. I found > one very simple example I can't figure out. Here is the script: > > # Enter a number to be squared > x = raw_input("Enter a number: ") > int(x) > sq = x*x > print sq > > I am getting the following error: > > Enter a number: 5 > Traceback (most recent call last): > File "db.py", line 6, in ? > sq = x*x > TypeError: can't multiply sequence to non-int > > Why is the function "int(x)" not changing the input to an integer? > > Thanks for the help, Jim > Try x = int(raw_input("Enter a number: ")) Regards Tim R -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From usenet_spam at janc.invalid Wed Nov 19 22:38:15 2003 From: usenet_spam at janc.invalid (JanC) Date: Thu, 20 Nov 2003 03:38:15 GMT Subject: PyQt, Qt, Windows and Linux References: Message-ID: Alex Martelli schreef: > Somebody's trying to develop a GPL version of Qt that runs under Windows > (with cygwin, specifically for the purpose of using KDE on cygwin) They are working on a non-Cygwin port too (should compile on VC++ & MinGW), but that might take longer to complete... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From ramen at lackingtalent.com Wed Nov 12 21:45:12 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Thu, 13 Nov 2003 02:45:12 -0000 Subject: Python array syntax in PHP Message-ID: There was a recent proposal on the PHP-DEV list to add a syntax similar to Python's for arrays (in PHP, arrays serve as both lists and dictionaries, though usually not at the same time. ;) Though several of the language developers were marginally positive about the idea, I found it interesting how much of a controversy ensued. http://groups.google.com/groups?dq=&hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=bo9cvn%242cut%241%40FreeBSD.csie.NCTU.edu.tw&rnum=1&prev=/groups%3Fdq%3D%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26selm%3Dbo9cvn%25242cut%25241%2540FreeBSD.csie.NCTU.edu.tw%26prev%3D/groups%253Fq%253Dg:thl151192782d%2526dq%253D%2526hl%253Den%2526lr%253D%2526ie%253DUTF-8%2526oe%253DUTF-8%2526selm%253Dbo9cvn%2525242cut%2525241%252540FreeBSD.csie.NCTU.edu.tw I'm really starting to think that much of a given language's style is arbitrary; the rationalizations come later, once the fear of change sets in. -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From dietrich at zdome.net Fri Nov 21 06:24:19 2003 From: dietrich at zdome.net (Dietrich Epp) Date: Fri, 21 Nov 2003 03:24:19 -0800 Subject: extract the strings in an exe In-Reply-To: <1jrrrv4g350e4oft2hq7p8ukvrahj45jcf@4ax.com> References: <1jrrrv4g350e4oft2hq7p8ukvrahj45jcf@4ax.com> Message-ID: <3F8AF0C6-1C15-11D8-B1A6-0003934ACDEC@zdome.net> On Nov 21, 2003, at 2:52 AM, Fernando Rodriguez wrote: > How can I extract all the strings in an exe with python? O:-) >>> CTRL-D $ strings foo.exe --- OR --- import os os.exec1p('strings', 'foo.exe') --- OR --- import re fooExe = file('foo.exe', 'r').read() strings = re.findall("[\x1f-\x7e]{4,}", fooExe) --- If you're looking for something a little more discriminating, you'll need to ask someone who cares about executable formats. This will probably print out the function names as well. Basically, the code finds strings of printing characters at least four characters long. If you're looking for the definitive list of strings, you're going to hit your head against the cold, hard reality of executable formats not usually storying that information. It just isn't there. From mwilson at the-wire.com Sat Nov 8 10:49:10 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Sat, 08 Nov 2003 10:49:10 -0500 Subject: prePEP: Decimal data type References: Message-ID: <2BRr/ks/KrJE089yn@the-wire.com> In article , "Tim Peters" wrote: > The conversion of prices into euros will require the use of a six- > significant-digit conversion rate (six digits disregarding initial >zeros) > which should not be rounded or truncated. This rate will be irrevocably > fixed on 1 January 1999 and defined in the form of one euro expressed in > national currencies. > >So that part mandates a *floating* point input (not meaning binary floating >point, but "6 digits disregarding initial zeros" is the essence of floating >point -- the total number of digits isn't fixed, nor is the # of digits >after the decimal point fixed, just the # of *significant* digits). > > To convert from national currencies to the euro, one has to divide by > the conversion rate. To convert from the euro to the national currency, > one has to multiply by the conversion rate. The use of inverse rates is > forbidden. > >Neutral. > > To convert from one national currency to another, amounts must be first > converted into euros and then into the second national currency. The > euro amount must be rounded to three decimal places. The national > currency should then be rounded to two decimals. > >So no single fixed-point discipline can suffice: in one direction they want >rounding to 3 digits after the decimal point, in the other to 2 digits, and >one of the inputs is a floating-point value with no fixed number of digits >after the decimal point. The toy Decimal I'm playing with has a class variable specifying number of digits to the right of the decimal point, and this gets used on calls to rounding method(s). By deriving Euros and Dollars from the Decimal class with the right digit specifications and calling for rounding at the right time I might be able to do that. Regards. Mel. From tjreedy at udel.edu Thu Nov 13 08:46:28 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Nov 2003 08:46:28 -0500 Subject: Am I the only one who would love these extentions? - Python3.0proposals (long) References: <04e601c3a943$ac9dc6b0$891e140a@YODA> Message-ID: <-cmdnSKo7eOhFi6iRVn-gQ@comcast.com> "Tim Jarman" wrote in message news:mailman.682.1068673868.702.python-list at python.org... > Enum("RED", "GREEN", "BLUE") creates constants RED=1, GREEN=2, BLUE=3. > Enum(RED=1, GREEN=2, BLUE=4) creates constants RED=1, GREEN=2, BLUE=4. > Enum("RED", "GREEN", "BLUE", BLACK=0) creates BLACK=0, RED=1, GREEN=2, > BLUE=3. ... > I don't claim that this is the One True Answer but it works for me. The apparent lack of there being One True Answer or even a close approximation seems to be one of the barriers to a standard lib module. Other people would rather that Enum("RED", "GREEN", "BLUE") create constants RED='RED', GREEN='GREEN', BLUE='BLUE'. There have been serious proposals on Python-Dev that the standard lib use self-identifying constants that would at least print something more meaningful than a number. On the other hand, some constants (weekdays, months) do need to be ordered other than alphabetically. Terry J. Reedy From aahz at pythoncraft.com Wed Nov 19 19:45:59 2003 From: aahz at pythoncraft.com (Aahz) Date: 19 Nov 2003 19:45:59 -0500 Subject: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com> Message-ID: In article , Andrew Dalke wrote: >Paul Rubin: >> >> Uniq should only have to work on sorted lists. > >*shrug* Okay, that's different than the unix 'uniq' command. I've >needed the unix one more than I've needed yours. Huh?!?! uniq has always to my knowledge only worked on sorted input. Reading the man page on two different systems confirms my knowledge. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From radam2 at tampabay.rr.com Tue Nov 18 12:58:27 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Tue, 18 Nov 2003 17:58:27 GMT Subject: new guy References: Message-ID: <6vmkrvourcsfuc3jjaij4rfkc4m9i2lpr3@4ax.com> On Tue, 18 Nov 2003 12:03:50 -0000, "nards_collective" wrote: >I'm new to Python, in fact I'm new to programming. I'm trying to write >a simulation program, for a biology class I'm teaching next year. the >following code is giving me trouble and i can't work out why. > > if e>= 1 : > a=e > else : > a=0 > > >I keep getting a syntax error. >This piece of code is meant to keep the value of a equal to or grater >than 0. Any odeas would be appreciated. > >THAnkS >NArDS > > 1. Check that you didn't type "If" instead of 'if', or "Else" instead of "else". 2. Look at the line above the if statement, it may be the actual line with the error in it. Tt may be missing a ending quote, bracket, or parentheses, or be incomplete in some other way. _Ronald Adam From __peter__ at web.de Sat Nov 1 04:03:18 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 01 Nov 2003 10:03:18 +0100 Subject: HTMLParser problems. References: <87y8v1krwl.fsf@pobox.com> Message-ID: Peter Otten wrote: > Actually, I'm not, any non-empty string would have done as well, given the > original poster's parser implementation. Nitpicking myself: any string containing at least one non-white character. Peter From kirk at daycos.com Tue Nov 4 14:15:05 2003 From: kirk at daycos.com (Kirk Strauser) Date: Tue, 04 Nov 2003 19:15:05 GMT Subject: nearest neighbor in 2D References: Message-ID: <87ism0ymii.fsf@internal.daycos.com> At 2003-11-03T04:12:47Z, John Hunter writes: > One solution that comes to mind is to partition to space into quadrants > and store the elements by quadrant. When a new element comes in, identify > it's quadrant and only search the appropriate quadrant for nearest > neighbor. Erm, no. Imagine that your new point is in one corner of a quadrant. The other point in the quadrant is in the opposite corner. There is a point in the adjacent quadrant that is infinitessimaly close to your new point. That's where your algorithm breaks down. -- Kirk Strauser The Day Companies From alberto.mantovaniNOSPAM at bologna.marelli.it Wed Nov 5 06:46:08 2003 From: alberto.mantovaniNOSPAM at bologna.marelli.it (Alberto Mantovani) Date: Wed, 05 Nov 2003 11:46:08 GMT Subject: from python1.5.2 to pytghon2.2.2 Message-ID: <3ef16536.3234041@news.marelli.it> Hi, I have a lot of scripts written in python1.5.2 that I have to bring in python2.2.2 , someone could give me some informations about the sintax differences between the two versions?. Are there some tools that can do this automatically? thanks Alberto From dave at pythonapocrypha.com Tue Nov 18 10:26:54 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 18 Nov 2003 08:26:54 -0700 Subject: Looking for an http proxy server written in Python References: Message-ID: <021b01c3ade8$747d1c00$6400000a@YODA> Chris wrote: > Is there such a beast? In particular, I'm looking for a > production-quality proxy server fully compliant with HTTP/1.1 written in > Python. Forward or reverse proxy? > If there isn't, is there anything that comes close? Alan Kennedy has this page: http://xhaus.com/alan/python/proxies.html See also: http://groups.google.com/groups?th=9171610619278850 Which one to use really depends on what you need it for. HTH, Dave From ahatzis at ithcorp.com Thu Nov 13 18:24:55 2003 From: ahatzis at ithcorp.com (Anastasios Hatzis) Date: Fri, 14 Nov 2003 00:24:55 +0100 Subject: Check of a Page About Python In-Reply-To: References: <3FAE6776.4040609@ithcorp.com> Message-ID: <3FB412C7.4080904@ithcorp.com> Eric, Gary many thanks for your proof read and comments. You helped very much! I converged the description stronger to the official version ('interpreted, OO programming language ...'), using 'scripting' in the menue bar because of too little space there. Anastasios From no at no.no.net.org.tv.com.edu.welf Fri Nov 14 23:33:15 2003 From: no at no.no.net.org.tv.com.edu.welf (RaYzor) Date: Sat, 15 Nov 2003 04:33:15 GMT Subject: OT Re: Matrix - Metaphors, Analogies and the REAL References: <9447377298731260.NC-1.60.joobs@news.free-online.net> <944913851691266.NC-1.61.joobs@news.free-online.net> <1Ihtb.1378$Wy4.787@newsread2.news.atl.earthlink.net> Message-ID: "3seas" <3seasA at Tthreeseas.DOT.not> wrote in message news:1Ihtb.1378$Wy4.787 at newsread2.news.atl.earthlink.net... > John Burns wrote: > > > On Thu, 13 Nov 2003 12:09:28 +0000, Gon?alo Rodrigues wrote: > > > [snip] > > >> And I'm out of this thread. > > > > Bye > > I'll feed you pet troll John, I got plenty more where this came from: > >>> -- snip illogical crapfest of complete lunacy ---<<< You're fn crazy sir. Matrix films suck. Its not real. Get a life. RaYzor From claird at lairds.com Wed Nov 12 15:07:46 2003 From: claird at lairds.com (Cameron Laird) Date: Wed, 12 Nov 2003 20:07:46 -0000 Subject: a python book hint References: Message-ID: In article , Nick Vargish wrote: >Alex Martelli is too modest about his own book, so let me tout it >here... > >Python in a Nutshell is an excellent reference, with quite a bit of >expository material. It has examples, and details of how much of the . . . Nick's not the only one to say so: . -- Cameron Laird Business: http://www.Phaseit.net From oom at xxnospamxx.ps.gen.nz Wed Nov 5 23:22:14 2003 From: oom at xxnospamxx.ps.gen.nz (oom) Date: Thu, 06 Nov 2003 17:22:14 +1300 Subject: Why does changing 1 list affect the other? References: <8ufjqvc24b7o1v0c32p2cpv7us32gtsdic@4ax.com> Message-ID: <6rijqvsh2pktnl6l4gfg1vk8gcg74tdicb@4ax.com> On Wed, 05 Nov 2003 23:05:30 -0500, Roy Smith wrote: > oom wrote: > >> I am a bit of a newbie when it comes to python, when working with >> lists today I noticed some very odd behaviour, any suggestions >> welcome: >> >> Python 2.2.3 (#1, Nov 6 2003, 14:12:38) >> [GCC 3.3.2 20031022 (Gentoo Linux 3.3.2-r2, propolice)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> firstlist=['item1','item2','item2'] >> >>> secondlist=firstlist >> >>> print (firstlist,secondlist) >> (['item1', 'item2', 'item2'], ['item1', 'item2', 'item2']) >> >>> firstlist[0]='strangeness' >> >>> print (firstlist,secondlist) >> (['strangeness', 'item2', 'item2'], ['strangeness', 'item2', 'item2']) >> >>> >> >> why does altering one list affect the other list ? it is driving me >> insane! >> > >Because when you say secondlist = firstlist, you're not making a copy of >the list, you're just making another reference to the existing list >object. If you're used to C/C++, think of it as passing a pointer >around. > >If you really wanted to make a new list, you should look at the copy >module (specifically copy.deepcopy). Or, somewhat simplier, you could >have just said secondlist = list (firstlist), which creates a new one >(kind of like a copy constructor might do in C++). Well thanks to both Ben and Roy!! I suspected something like this was going on, but what a head scratching session I had! This is a very active NG ;-) problem solved From __peter__ at web.de Wed Nov 12 19:38:43 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Nov 2003 01:38:43 +0100 Subject: trouble understanding None References: Message-ID: Terry Reedy wrote: > Unless the OP actually needs a list of lines, I think I would make the > value corresponding to each letter one string with embedded newlines: [...] > This is very easy to edit (with a fixed pitch editor), aud to use. Yes, this would be a cleaner approach. > The only real problem is (maybe) the extra newline at the beginning of > the file, which makes the first line line-up with the rest. The raw > mode input makes it impossible (as far as I know) to escape it (with > the usual '\', which gets printed instead). So one could either > postprocess the dict to slice all values or delete the initial newline > in the source code after getting the letter right. I mixed normal and raw strings because I recalled a problem with backslashes at the end of a raw string. I've since found out that this applies only to a single last backslash at the end of the string: >>> r"\\" '\\\\' >>> r"\" File "", line 1 r"\" ^ SyntaxError: EOL while scanning single-quoted string >>> For my Big writer class , that somewhat extends the original task, postprocessing would be the way to go, because of other problems: - every line of a character must be of the same length - every character must have the same height - if character definitions with different heights are allowed, additional information about the baseline is required for the program to decide where to fill in the blank lines Peter From francisgavila at yahoo.com Sat Nov 8 18:11:33 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sat, 8 Nov 2003 18:11:33 -0500 Subject: displaying properly formatted output of ipconfig.exe References: <601be7f8.0311081449.24b3f7e2@posting.google.com> Message-ID: "Joe Flynt" wrote in message news:601be7f8.0311081449.24b3f7e2 at posting.google.com... > but when I view http://server/cgi-bin/test.py i get the following > format of output: > ['\r\n', 'Windows IP Configuration\r\n', '\r\n', > etc. > #!C:\Python23\python.exe > import os > print "Content-type: text/html\r\n\r\n" > cmdpipe = os.popen("ipconfig","r") > lines = cmdpipe.readlines() > print lines You don't want to print a list of strings, you want to print each string in a list.... lines = cmdpipe.readlines() - print lines + for line in lines: + print line -- Francis Avila From h.b.furuseth at usit.uio.no Wed Nov 12 10:44:45 2003 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 12 Nov 2003 16:44:45 +0100 Subject: Am I the only one who would love these extentions? - Python 3.0 proposals (long) References: <99dce321.0311101552.5888daa6@posting.google.com> Message-ID: David M. Wilson wrote: >> -- No '\' for continuation lines -- you can always use parenthesis; > > When reading complex expressions at speed, I have found that bumping > into a '\' in the absence of another continuation indicator (eg. > indentation) improves my ability to comprehend what I am reading. So use indentation. > Once again, this is one of those "4am'ers": > > a = x/y+(1^2+(3+u(b(4**5)))//3 + 4) -- Hallvard From aahz at pythoncraft.com Sun Nov 2 09:56:11 2003 From: aahz at pythoncraft.com (Aahz) Date: 2 Nov 2003 09:56:11 -0500 Subject: Food at Pycon References: <5b4785ee.0311020559.2f84c43b@posting.google.com> Message-ID: In article <5b4785ee.0311020559.2f84c43b at posting.google.com>, Wade Leftwich wrote: > >Salon.com has recently noted a trend of alpha geeks going on the >Atkins diet, so maybe next year we will need fewer chocolate chip >cookies and more pork chops. ...or at least veggies with blue cheese dressing. While the sentiment is appreciated, one problem with protein is that it's *more* expensive. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From janeaustine50 at hotmail.com Fri Nov 28 09:11:10 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 28 Nov 2003 06:11:10 -0800 Subject: python's threading has no "interrupt"? Message-ID: As far as I know python's threading module models after Java's. However, I can't find something equivalent to Java's interrupt and isInterrupted methods, along with InterruptedException. "somethread.interrupt()" will wake somethread up when it's in sleeping/waiting state. Is there any way of doing this with python's thread? I suppose thread interrupt is a very primitive functionality for stopping a blocked thread. Jane From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Nov 1 12:06:03 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 01 Nov 2003 18:06:03 +0100 Subject: prePEP: Decimal data type In-Reply-To: References: <3cd884n4.fsf@yahoo.co.uk> Message-ID: <3fa3e7fb$0$58697$e4fe514c@news.xs4all.nl> John Roth wrote: > In the spirit of explicit is better than implicit, I'd rather have > the control inherent in a div() operator. +1 (without having read all of the thread, but John's statement sounds very reasonable to me) > I think someone earlier suggested (in the context of the Money type) > having the number of digits be an optional arguement to the constructor. > That is: decimal(1.1, 1) showing one place after the decimal point. > > However, I prefer having the compiler take care of it. I think I don't. Consider: d=decimal(1.1) versus: f = 1.1 d = decimal(f) this would yield different results then. And I think that's confusing. Although decimal(1.1,1) -with the extra argument "1 decimal place"- isn't really pretty either, IMHO: you have to actually count the number of decimal digits yourself! --Irmen de Jong From richie at entrian.com Thu Nov 6 11:03:14 2003 From: richie at entrian.com (Richie Hindle) Date: Thu, 06 Nov 2003 16:03:14 +0000 Subject: Pure Aspect-Oriented Program: an example In-Reply-To: <8ef9bea6.0311052119.4f5ab5d6@posting.google.com> References: <8ef9bea6.0311052119.4f5ab5d6@posting.google.com> Message-ID: [Hung Jung] > I have never seen an example of purely > aspect-based program. So, I thought I'd write up one. > Here it is, and let's get some feedback. Fantastic! That's the best introduction to the concepts of AOP I've seen. Many thanks for a very clear and thought-provoking article. Now please implement it for Python, including your proposed IDE. 8-) -- Richie Hindle richie at entrian.com From mwh at python.net Thu Nov 6 08:39:25 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 6 Nov 2003 13:39:25 GMT Subject: Strange problems with encoding References: Message-ID: <7h31xslhb6e.fsf@pc150.maths.bris.ac.uk> "Sebastian Meyer" writes: > Hi newsgroup, > > i am trying to replace german special characters in strings like > str = re.sub('?', 'oe', str) 1) str is the name of a builtin -- often a bad idea to use that as a variable name. 2) I presume `str' is a unicode string? Try writing the literal as u'?' instead (and adding the appropriate coding cookie to your source file if using Python 2.3). Or I guess you could write it u'\N{LATIN SMALL LETTER O WITH DIAERESIS}' Cheers, mwh -- Usenet is like a herd of performing elephants with diarrhea -- massive, difficult to redirect, awe-inspiring, entertaining, and a source of mind-boggling amounts of excrement when you least expect it. -- spaf (1992) From hungjunglu at yahoo.com Sun Nov 23 12:43:31 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 23 Nov 2003 09:43:31 -0800 Subject: code blocks in Python References: <8ef9bea6.0311221215.804bdb3@posting.google.com> <8ef9bea6.0311221913.427cb53e@posting.google.com> Message-ID: <8ef9bea6.0311230943.4a1de6cb@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message news:... > > >>> compile('a=123','','single') > > >>> import dis > >>> dis.dis(compile('a=123','','single')) > 1 0 LOAD_CONST 0 (123) > 3 STORE_NAME 0 (a) > 6 LOAD_CONST 1 (None) > 9 RETURN_VALUE > >>> def foo(): a=123 > ... > >>> dis.dis(foo) > 1 0 LOAD_CONST 1 (123) > 3 STORE_FAST 0 (a) > 6 LOAD_CONST 0 (None) > 9 RETURN_VALUE > > So which code will you want when the compiler compiles an in-context block? > Will you want it to be a first-class object? Yes, absolutely. > with compile's output? Are you willing to forego the optimized local access? I know there is a performance issue, since in normal, local, non-named codeblocks, local variables are retrieved by indices instead of names. There is a question as how to hook up named codeblocks efficiently in the scope of the non-named codeblocks. But one is gotta start somewhere. Optimization comes later. > You could call for magic creation of special > closures so that an exported code block would still refer back to the local name space > (which BTW could be interesting for generators to yield, to give external access to their > internal state). Again, something simple to start with. Closures comes later, if at all necessary. I am not sure whether closure-like codeblocks are fundamental enough, since they could be emulated by other means. E.g. class generic: pass codeblock A: print c.x c.x = 3 c1 = generic() c2 = generic() c1.x = 4 c1.code = A c2.x = 5 c2.code = A c = c1 exec c.code c = c2 exec c.code > And what should assigning a function local codeblock to a global mean? > Maybe creating a one-shot generator where the codeblock could be used to preset state for > a single ordinary function call that re-uses previous state. Or should it just die like a > weak reference? I don't know exactly what you mean by "function local codeblock". If you refer to the function's code, currently accessible as f.func_code, I've tried that, but it seems to bind things to the locals dictionary of the function itself. Which is no good. E.g.: def f(): x = 1 def g(x): exec f.func_code print x g(2) x = 3 exec f.func_code in globals() print x will print 2 and 3. I tried using exec...in... with various namespaces, but the same thing. That is, the func_code remembers its own local scope and refuses access/modify other local scopes. This is very different from: code = compile('x=1\n', '', 'exec') def g(x): exec code print x g(2) x = 3 exec code print x which will print 1 and 1. That is, smart enough to take x from the respective local and global dictionaries. ---------- If by "function local codeblock" you mean codeblocks define inside the scope of a function, I really don't think they should receive any special treatment for optimization, since a codeblock should be an object that can be passed around, and should be independent of where they are defined. It's like if you have the number 3, which is an object, you can pass it around to anywhere, regardless where it was first defined. No complications from nested-scopes, closures, etc. Functions get complicated exactly because they carry all these extra baggages. ---------- Well, all these are the kinds of things to think about. But named codeblocks have well-defined meaning on their own right, independent of implementation details. Theoretically, codeblocks don't know whether the names inside them are local or global. It's a late-binding object. > but I wonder how common/important they are. I can't say in the case you have described. However, in general codeblocks are extremely useful, right now they are not used as widely, I think simply because the codestrings are not compiled and checked at compile time: you need one extra step invoking the compile() function. Named codeblocks will solve a barrage of nuisances in today's programming world. They helps in (a) code re-use, (b) code modularization. By (a) I mean that the same codeblock could be used in a lot of places. By (b) I mean that you can isolate the effects of codeblocks, and do code replacements a la AOP (Aspect-Oriented Programming.) It's just weird that Python has the compile() function, but has no named codeblocks. I really can't understand why. regards, Hung Jung From guettli at thomas-guettler.de Thu Nov 20 05:19:43 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 20 Nov 2003 11:19:43 +0100 Subject: Building RPM Message-ID: Hi! I need to build a Python2.3.2 RPM for Suse7.3. I looked at http://www.python.org/2.3.2/rpms.html and downloaded python2.3-2.3.2-1pydotorg.src.rpm. I unpacked to src.rpm like this: rpm2cpio ../python2.3-2.3.2-1pydotorg.src.rpm | cpio -id Changed the spec file (removed dependencies on expat, gdbm .. since I don't need them) and tried to build the rpms: rpm -ba python-2.3.spec | tee rpm-ba.out All seems to run well, but I can't find any rpms. The tail of rpm-ba.out: Processing files: python2.3-tkinter-2.3.2-1pydotorg PreReq: rpmlib(VersionedDependencies) <= 3.0.3-1 python2.3 = 2.3.2-1pydotorg Processing files: python2.3-tools-2.3.2-1pydotorg Finding Provides: (using /usr/lib/rpm/find-provides)... Finding Requires: (using /usr/lib/rpm/find-requires)... PreReq: rpmlib(VersionedDependencies) <= 3.0.3-1 python2.3 = 2.3.2-1pydotorg Requires: /bin/bash /bin/sh /usr/bin/env /usr/bin/python /usr/bin/python2.3 Processing files: python2.3-docs-2.3.2-1pydotorg Finding Provides: (using /usr/lib/rpm/find-provides)... Finding Requires: (using /usr/lib/rpm/find-requires)... Any hints why there are no rpms? thomas From thomas at esands.com Tue Nov 18 21:23:00 2003 From: thomas at esands.com (Thomas Schulz) Date: Wed, 19 Nov 2003 02:23:00 +0000 Subject: logging: repeated messages Message-ID: Hello, I'm using the logging package from python 2.3 on RH linux. Everything in the test program below works fine if we just use the log configuration with 'logging.basicConfig'. For the example below we get the expected output: ERROR:loggerName:error1 msg ERROR:loggerName:error2 msg If we add a StreamHandler (uncomment the lines with 'hdlr'), things get strange: The messages are repeated as many times as there were messages before that call that qualified for output by their loglevel. Output with enabled StreamHandler: error1 msg error1 msg ERROR:loggerName:error1 msg error2 msg error2 msg error2 msg ERROR:loggerName:error2 msg The problem in the sample program might be the creation of the logger object in each 'log' call. One of the constraints for the use of the loggger in that way is because I have to provide a simple procedure 'log' to handle everything. Sure, if I would create the logger only once it would be fine. But why does the configuration created with basicConfig work fine? Any sugestions to resolve the problem? --Thomas #!/usr/bin/env python import logging, logging.handlers def log(level, message): logging.basicConfig() logger = logging.getLogger('loggerName') # Streamhandler, uncomment the following 3 lines hdlr = logging.StreamHandler() hdlr.setLevel(logging.WARN) logger.addHandler(hdlr) if level == 'DEBUG': logger.debug(message) elif level == 'INFO': logger.info(message) elif level in ['WARN', 'WARNING']: logger.warn(message) elif level == 'ERROR': logger.error(message) elif level == 'CRITICAL': logger.critical(message) log('INFO', 'info message') log('ERROR', 'error1 msg') log('ERROR', 'error2 msg') From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Tue Nov 25 07:28:29 2003 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau) Date: Tue, 25 Nov 2003 13:28:29 +0100 Subject: win32com (VBScript to Python) problem References: Message-ID: Hi ! This code "reboot" the computer 'CPU01' (if rights are OK) : import win32com.client WMIService = win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate,(Shutdo wn)}!\\CPU01\root\cimv2") objs = WMIService.ExecQuery(r"Select * from Win32_OperatingSystem") for obj in objs: obj.Reboot() Perhaps this sample can help you ? @-salutations -- Michel Claveau site : http://mclaveau.com From stephan.diehl at gmx.net Mon Nov 24 04:24:08 2003 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Mon, 24 Nov 2003 10:24:08 +0100 Subject: Bug or Feature? Message-ID: I was playing around with defining new types and have seen the following behaviour: Python 2.3.1 ============ >>> class Int(int):pass ... >>> a = Int(7) >>> b = Int(8) >>> c = a + b >>> type(c) Basicly: Int is not closed under it's defined operations. :-( by contrast: >>> class myset(Set):pass ... >>> a = myset([1,2]) >>> b = myset([2,3]) >>> c = a & b >>> type(c) subclasses of Set are closed under the set operations. :-) Should I consider this as a bug or something I have to live with? Example, why this can be problematic: Consider, I want to define an integer subtype that holds integers modulo N. The straight forward way would be: class mod7(int): def __new__(cls,value): return int.__new__(cls,value%7) Since addition, substraction, etc. doesn't work as expected, one must redefine all relevant operators. This is not what I'd consider object oriented behaviour. Stephan P.S.: for the mind police out there: Other than that, Python is great. From reply.in.the.newsgroup at my.address.is.invalid Wed Nov 19 16:54:03 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 19 Nov 2003 22:54:03 +0100 Subject: Parsing HTTP messages References: Message-ID: <2fpnrvoi0nc08oqkho1uqs1radf9v0976b@4ax.com> Chris Gray: >what Python library do I use to parse HTTP messages? http://www.python.org/doc/2.2.3/lib/module-httplib.html Or a library depending on the format of the payload, if that's what you mean. For example, if the message contains HTML: http://www.python.org/doc/2.2.3/lib/module-HTMLParser.html >When I parse an HTTP request using the email module Que? -- Ren? Pijlman From aleax at aleax.it Fri Nov 14 12:06:12 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Nov 2003 17:06:12 GMT Subject: Python's simplicity philosophy References: <2259b0e2.0311112248.3be2d304@posting.google.com><17lsb.109042$fl1.4548960@twister.southeast.rr.com> <20031112170100.GA32388@godzilla.fibrespeed.net> Message-ID: <8Y7tb.21901$9_.802189@news1.tin.it> Dave Brueck wrote: ... >> Why, pray-tell, would you want an OO program to do: >> >> results = [ func(x) for x in sequence ] >> >> ... instead of ... >> >> results = sequence.map(func) ?? > > Because I find the first much more readable (and IMO the "an OO program to > do" bit is irrelevent from a practical point of view). I entirely agree with both points. They're even clearer when the contrast is between, e.g.: results = [ x+23 for x in sequence ] and: results = sequence.map(lambda x: x+23) where using the HOF approach forces you to understand (and read) lambda too. Alex From theller at python.net Wed Nov 19 16:09:59 2003 From: theller at python.net (Thomas Heller) Date: Wed, 19 Nov 2003 22:09:59 +0100 Subject: "python exe" and "py plugins" References: Message-ID: Ahmad Baitalmal writes: > marco wrote: >> great ! it works with dynamic import ( __import__() )! >> it's a lot better than an execfile ... >> "Marc Boeren" a ?crit dans le message de news: >> mailman.826.1069158322.702.python-list at python.org... > > I'm a bit lost, I'm trying to do the same thing withe BitLeaf > (www.bitbuilder.com/bitleaf). > I put all my pulgins in a folder named "services", then when the > application loads it looks in that folder for any subfolders that have > __init__.py in them (packages, that's how I plan to distribute the > plugins). > > That works fine in linux or uncompiled on windows, but with py2exe, it > can't find the "services" folder. You should be a bit more specific here - what do you mean by "it can't find the services folder" ? I can only think of two problems - first you should locate the folder in the file system (probably relative to the exe-file, which is sys.executable), and then you should add it to sys.path. Second, you must make sure that py2exe doesn't include this folder. Thomas From exarkun at intarweb.us Sat Nov 22 16:22:53 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sat, 22 Nov 2003 16:22:53 -0500 Subject: Class not loading properly in CGI In-Reply-To: References: Message-ID: <20031122212253.GA760@intarweb.us> On Sat, Nov 22, 2003 at 06:24:50PM +0000, Tom Chance wrote: > Hullo, > > I've got a very, very odd problem here which I can't seem to solve. I'm > creating a class instance in a CGI script, but that instance isn't > inheriting all of the methods associated with that file. Confused? Here's > what I mean: > > the commands to check: > import db > mydb = db.mySQL() > print str(dir(mydb)) > > done in a python shell on my machine: > "['__doc__', '__init__', '__module__', 'connectTime', 'cursor', 'delete', > 'fetchRow', 'fetchRows', 'info', 'insert', 'mysql', 'update']" > > in the cgi script online: > ['connectTime', 'cursor', 'mysql'] > > What on earth is going on? Try printing db.__file__ Jp From tuanglen at hotmail.com Mon Nov 17 16:29:16 2003 From: tuanglen at hotmail.com (Tuang) Date: 17 Nov 2003 13:29:16 -0800 Subject: syntax philosophy Message-ID: I'm checking out Python as a candidate for replacing Perl as my "Swiss Army knife" tool. The longer I can remember the syntax for performing a task, the more likely I am to use it on the spot if the need arises. If I have to go off and look it up, as I increasingly have to do with Perl's ever hairier syntax, I'm more likely to just skip it, making me even less likely to remember the syntax the next time. So I hear that Python is easier to remember between uses than Perl. So far, I like what I see. Iterators and generators, for example, are great. Basic loops and other things are very convenient in Python. But I'm surprised at what you apparently have to go through to do something as common as counting the frequency of elements in a collection. For example, counting word frequency in a file in Perl means looping over all the words with the following line: $histogram{$word}++; The creation of the dictionary, the creation of new elements, the initialization to zero, are all taken care of automatically. You just tell it to start counting and the rest is taken care of for you. And the incrementing is just a simple "++". In Python, apparently you have to first remember to declare your dictionary outside the loop: histogram {} Then within the loop you use the following construct: histogram[word] = histogram.get(word, 0) + 1 That's quite a bit hairier and it requires remembering to use braces {}, then square brackets [], then parentheses (), and accessing the dictionary via two different techniques in the same line. This seems sort of unPythonesque to me, given the relative cleanliness and obviousness (after seeing it once) of other common Python constructs. But I guess I'm making assumptions about what Python's philosophy really is. I would expect that a language with something as nice as [x**3 for x in my_list] would want to use something like: histogram[word]++ or even combine them into something like: {histogram[word]++ for word in my_list} Is this just something that hasn't been done yet but is on the way, or is it a violation of Python's philosphy in some way? Since I'm trying to choose a good Swiss-Army-knife programming language, I'm wondering if this Python histogram technique is the sort of thing that bothers Pythonistas and gets cleaned up in subsequent versions because it violates Python's "philosophy" or whether, on the contrary, it's just the way Pythonistas like to do things and is a fair representation of what the community (or Guido) wants the language to be. Thanks. From SEE_AT_THE_END at hotmail.com Mon Nov 10 05:21:29 2003 From: SEE_AT_THE_END at hotmail.com (Georgy Pruss) Date: Mon, 10 Nov 2003 10:21:29 GMT Subject: Am I the only one who would love these extentions? - Python 3.0 proposals (long) Message-ID: Hi all, I would like to propose some extentions to the language, probably for the version 3.0. They are mainly lexical or syntactical and the language will stay compatible with 2.X (even although it was declared somewhere that it's not the main concern in the Python community) but some of them are a bit more "radical." Yes, I know that some of the proposals were discussed here before, but I don't think it means that the language is frozen in its development forever and that everybody's absolutely happy with what it is today. Anyway, this is my wish list :) The features I'd like to see in Python are: underscores in numbers, binary integers, hex strings, true boolean and none constants, enum type, optional colon, built-in regex and RE match, slices, for-as loop, until loop, unconditional loop, one line if-else, etc. 1) Underscores in numbers. It will help to read long numbers. E.g. 12_345_678 3.14159_26535_89793_23846 2) Binary constants. Not in great demand, just nice to have, half an hour to implement. E.g. 0b01110011 0b1110_0101_1100_0111 3) Hex strings. Very useful when you want to initialize long binary data, like inline pictures. E.g. x'48656C6C6F 21 0D0A' ux'0021 000D 000A' They can be combined with other strings: 'Hello!' x'0d0a' Now you can use hexadecimal values, but with two times longer sequences like '\x..\x..\x..\x..', or do the translation during run-time using '....'.decode('hex'). 4) Keywords 'none', 'false', 'true'. They should be keywords, and they should be lowercase, like all the rest keywords. True, False and None can stay for some time as predefined identifiers, exactly like they are now. 5) Enum type. Introduces global (module-level) constants of number or string values. The numeric values can be assigned automatically like in the C language. If the enum declaration has a name, this name defines "a namespace" and it must be specified for referring to the values. # defines constants AXIS.X=0, AXIS.Y=1, AXIS.Z=2 enum AXIS: X, Y, Z # defines color.red, color.green, color.blue enum color red = '#FF0000', green = '#00FF00', blue = '#0000FF' # defines consts A=0, B=1, C=2, D=10, E=11, F=12 enum A, B, C D = 10, E F # the same as above enum: A; B, C, D=10; E, F # ';' and ',' are the same here. 6) The colon is optional after for,if,try,enum etc. if it is followed by a new line. Although it's mandatory if there are statements on the same line. So it's like ';' -- you MUST use it when it's needed. You CAN still use it if you like it, like now you can put a semicolon after each statement as well. def abs(x) if x < 0 return -x else return x 7) Built-in regex'es. It would be nice to have built-in regular expressions. Probably, some RE functionality can be shared with the built-in string class, like presently we can write 'x'.encode('y'). For example $str can produce a regex object and then s==re can return true if s matches re. This would be very good for the switch construction (see below). E.g. id = $ "[A-Za-z_][A-Za-z0-9_]*" if token == id: return token 8) Slices. They can have two external forms and they are used in three contexts: a) in [index], b) in the 'case' clause, c) in the 'for-as' statement. The have these forms: a:b means a <= x < b (a:b:c -- with step c) a..b means a <= x <= b (a..b:c -- with step c) E.g. 1:100 == 1,2,3,...,99 1..100 == 1,2,3,...,100 9) For-as loop. Actually, 'as' is chosen because it is already used as a keyword, and it fits here quite well. Another possible spelling can be 'from' (as somebody proposed in 1999). for as : The sequence (it also occurs in the case clause, see below) is composed of one or more expressions or slices. This form is very short and visual. It will permit a better optimization comparing to the old "in range(x,y)" form. E.g. for n as 1:10,10:50:2,50:100:5 for item as 1..100, 201..300 The ambiguity of constructions like "for v as a():b():c()" can be solved with additional parenthesis: for v as a():b():c() # from a() till b() with step c(); stmts start stmts() # on the next line for v as (a():b()): c() # from a() till b() with step 1; do c() for v as [a():b()]: c() # maybe this form looks better 10) Until loop -- repeat the loop body at least one time until the condition is true. until It's the same as: while not 11) Unconditional loop. Yes, I'm from the camp that finds 'while 1' ugly. Besides, sometimes we don't need a loop variable, just a repetition. loop [] E.g. loop 10 print_the_form() loop line = file.readline() if not line break process_line( line ) 12) Selection statement. The sequence (it can also occur in the for-as statement, see above) is composed of one or more expressions or slices. switch case case else The sequence can contain RE-patterns. case $pattern,$pattern2 # if expr matches patterns ... 13) One line if-else. if : ; else: 14) Conditional expression. Yes, I'd love it. cond ? yes : no 15) Better formatting for repr() repr(1.1) == '1.1' If the parser recognizes 1.1 as a certain number, I can't see any reason why it should print it as 1.1000000000000001 for the next parser run. 16) Depreciated/obsolete items: -- No `...` as short form of repr(); -- No '\' for continuation lines -- you can always use parenthesis; -- No else for while,for,try etc -- they sound very unnatural; -- Ellipsis -- it looks like an alien in the language. I do believe that these changes follow the spirit of the language and help Python to become an even better language. And I'm ready to implement them, if they pass the PEP vote :) If not... I love Python anyway! -- Georgy Pruss E^mail: 'ZDAwMTEyMHQwMzMwQGhvdG1haWwuY29t\n'.decode('base64') From brett at python.org Fri Nov 28 15:54:23 2003 From: brett at python.org (Brett C.) Date: 28 Nov 2003 12:54:23 -0800 Subject: python-dev Summary for 2003-10-16 through 2003-11-15 References: Message-ID: <8ab0589d.0311281254.32862a4c@posting.google.com> > > This is the twenty-eighth and twenty-ninth summaries written by Brett > > Cannon (does anyone even read this?). > > This is a long-overdue note of tremendous thanks to you (and any others > who went before you) for keeping this summary going. First off, thanks to not only you, Tim, but to everyone else who posted a supportive message to me. It means so much to me when people send me an email saying that they read the Summaries and find them helpful. Since I have no legitimate way of tracking readership I have to just assume people read the darn things and find them informative. > I'm a long-standing > Python user and, while I'm not likely to get directly involved in its > development, it's of both technical and general interest to see what's > going on and what's being said on the development lists. I have to admit one of the reasons I keep writing the Summaries is in hopes of getting more people involved in Python development. The longer I stay on python-dev the more I learn and thus marginalize somewhat my personal gain from writing the Summaries in terms of technical learning. But I get a personal gain in terms of knowing I am helping out Python by helping the community and the ultimate gain would not only be to get someone to start using Python, but to cause someone to help improve the language in some way. > The level is > just right for me: informative without too much detail. > Thanks for saying that. I often struggle with how much technical detail I should stick in there and how much I should assume. Usually if I don't explain something well enough someone on python-dev catches it through my drafts that I post to the list (and a personal thanks from me to Raymond Hettinger for proof-reading practically every summary I write from top to bottom very thoroughly). > Please keep it up! > I plan to. =) -Brett From ivoras at fer.hr Mon Nov 17 12:20:46 2003 From: ivoras at fer.hr (Ivan Voras) Date: Mon, 17 Nov 2003 18:20:46 +0100 Subject: Tkinter uses a lot of memory?! References: Message-ID: ServantOfTheSecretFire wrote: > wrong when I saw the memory consumption, so I wrote the simplest Tk > program I could, and yep, it takes about 40MB of memory! I'm using Red > Hat Linux 9.0 and recent versions of the software. Please look at the > output below, and tell me if I am confused... > sjm 25633 4.8 7.2 41576 37352 pts/0 S 22:35 0:00 python Can't say about linux, but on windows your program takes about 5.5MB. -- -- Every sufficiently advanced magic is indistinguishable from technology - Arthur C Anticlarke From phil at riverbankcomputing.co.uk Wed Nov 19 13:08:36 2003 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 19 Nov 2003 18:08:36 +0000 Subject: PyQt, Qt, Windows and Linux In-Reply-To: References: Message-ID: <200311191808.36101.phil@riverbankcomputing.co.uk> On Wednesday 19 November 2003 10:28 am, Richie Hindle wrote: > [Rob] > > > The "official" Qt3 book is due in February of 2004, and the > > included CD will include a non-commerical version of Qt 3.2.1 > > for Windows [...] it appears that you will be able to distribute > > the Qt runtime DLLs with your non commerical application [...] > > This is great news for people who want to develop free Windows software > with Qt. Phil, do you yet know whether PyQt Non-Commercial will support > this version of Qt? I usually follow what Trolltech do, which means that I'll probably look at selling a CD with a compatible version of PyQt on it. Phil From tuanglen at hotmail.com Tue Nov 18 18:56:50 2003 From: tuanglen at hotmail.com (Tuang) Date: 18 Nov 2003 15:56:50 -0800 Subject: syntax philosophy References: Message-ID: "Andrew Dalke" wrote in message news:... > Tuang: > > But I'm surprised at what you apparently have to go through to do > > something as common as counting the frequency of elements in a > > collection. For example, counting word frequency in a file in Perl > > means looping over all the words with the following line: > ... > > This seems sort of unPythonesque to me, given the relative cleanliness > > and obviousness (after seeing it once) of other common Python > > constructs. > > > > But I guess I'm making assumptions about what Python's philosophy > > really is. > > I see several replies already, but they don't seem to address your > question about the philosophical reasons for this choice. Thanks for a spot-on answer to my exact question. ;-) > > A Python philosophy is that "Errors should never pass silently." > (To see some of the other points, 'import this' from the Python > prompt.) > > When you reference '$histogram{$word}++' in Perl it automatically > creates the hash 'histogram' and creates an entry for $word with > the value of 0 (I think; it may set it to undef or ""). This is great, > as long as you don't make mistakes. > > But people do make mistakes and misspell variables. Had you > written '$histrogram{$word}' then Perl would have simply > created a new hash for you with that name. This is enough of > a problem in Perl that it's recommended you 'use strict' > and declare the hash beforehand, as 'my %histogram'. Very true. Other respondants made this point as well, which I think is a good one. It sort of points out that my favorite use of Perl is for quick one-liners that let me do exactly what I want on the spur of the moment, as opposed to writing bigger "programs" for repeated use. I've done both in Perl, but I think it's better suited to the former than the latter. Python appears to scale up much more gracefully. That use of Perl for one-liners, though, is why having them be easy, automatic, and memorable matters. That's why I would prefer the same convenience in anything I use to replace Perl for "Swiss Army knife" use. I would apparently have to give up a bit of the convenience at the one-liner level to buy the superior scaling (and other relative benefits) of Python. > ...Python is strongly > typed, so "2"+1 will raise an exception, unlike Perl where it > yields the number 3. If Python used a 0 for the default then > what if you really wanted to concatenate strings? If it used > "" then what if you wanted to add numbers? Whatever choice > you make, it will be wrong for most cases. I find Perl's defaults to be right almost *all* of the time. Increment a counter? Fine, $counter++ creates the counter if it needs to be created, initializes it if it was just created, and then increments it. On the rare occasions when I want it initialized to something other than 0, I just initialize it myself, but the default initialization of zero is right almost all the time for numbers, so why not take advantage of that fact? And how often would you want to initialize a string to anything other than an empty string? So in Perl, you just start concatenating, and if the string doesn't already exist, it's automatically created for you and your first concatenation concatenates to an empty string. Again, Perl's default is almost always what you want, and in those rare cases where it's not what you want, you're free to do what you have to do in Python every single time. Your point about the typing, though, may be a reason why such a thing couldn't be done in Python, and your point about "use strict" indicates to me that such convenience may have proven to be a liability as soon as your program starts to grow. I do know that there have been a few occasions when I've been stumped by Perl's guessing incorrectly at what data type I meant and my not having any way to explicitly tell it. > Your reply is that you're looking for the philosophy behind > Python, using the histogram as an example. That actually > is part of the philosophy -- in Python it's much easier to > make a class and instantiate an object with the appropriate > behaviours than it is in Perl, what with Perl's "bless" and > shift and @ISA. This is very true. It's starting to appear as though Python's built-ins are often less convenient than Perl's, but in every case that I've seen so far it has been easier to combine those built-ins into higher-level abstractions in Python than in Perl. The above 'Histogram' is simply > > class Histogram: > def __init__(self): > self.histogram = {} > def count(self, word): > self.histogram[word] = self.histogram.get(word, 0) + 1 > > In Perl the equivalent would be something like (and only > roughly like -- I never did fully figure out how do to Perl > OO correctly) LOL! Neither have I. It's not that we're retarded -- well, you be the judge ;-) -- but it's just more trouble than it's worth in Perl. There are so many useful Perl modules that I try to remember just enough to be able to use other peoples', but it's just not worth the bother remembering how to make them myself. After a few hours with Python, I was already better at object-oriented Python than I ever was at object-oriented Perl. > > package Histogram; > sub new { > my ($class, $obj) = @_; > bless $class, $obj; > $obj -> {'histogram'} = {}; > return $obj; > } > sub count { > my ($class, $obj, $word) = @_; > $obj -> {'histogram'}{$word}++; > } > > However, for a one-off histogram this level of abstraction isn't > worthwhile. Amen. But $hist{$word++} works beautifully. > > To summarize, Python's philosophical differences from Perl > for your example are: > - variables must be declared before use (reduces errors) > - dict entries must be declared before use (reduces errors) > - dict entries cannot have a default value (strong typing) > - classes are easy to create (letting you create objects which > better fit your domain) Thanks. That perfectly explained the philosophy behind my example. From __peter__ at web.de Mon Nov 17 04:28:16 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Nov 2003 10:28:16 +0100 Subject: URL listers References: Message-ID: P. Daniell wrote: > I have the following HTML document > > > > I don't give a hoot > > > > I want my HTMLParser subclass (code below) to output > > http://www.yahoo.com I don't give a hoot > > Instead it outputs > > http://www.yahoo.com I don > http://www.yahoo.com ' > http://www.yahoo.com t give a hoot > > > Would anyone care to give me some guidance on how to fix this? handle_data() can be called multiple times inside ..., so you must collect the chunks (see the text attribute below) and only print them in the anchor_end() method: class URLLister(htmllib.HTMLParser): def __init__(self): htmllib.HTMLParser.__init__(self, formatter.NullFormatter()) self.in_a = 0 self.tempurl = '' self.text = [] def anchor_bgn(self, href, name, type): self.in_a = 1 self.tempurl = href def anchor_end(self): print self.tempurl, "".join(self.text) del self.text[:] self.in_a = 0 def handle_data(self, data): if self.in_a: self.text.append(data) By the way, there is another HTMLParser in the HTMLParser module, which I think is superior. Peter From duncan at NOSPAMrcp.co.uk Thu Nov 20 11:53:26 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 20 Nov 2003 16:53:26 +0000 (UTC) Subject: trouble with regex with escaped metachars (URGENT please O:-) References: <3amprvo6n734ovhg5ekatp0539q738809t@4ax.com> Message-ID: Fernando Rodriguez wrote in news:3amprvo6n734ovhg5ekatp0539q738809t at 4ax.com: > Here's the code I'm using: > > def substitute(name, value, cts): > """ > Finds all the occs in cts of $ > and replaces them with value > """ > > pat = re.compile("\$<" + name + ">", re.IGNORECASE) > > return pat.sub(val, cts) # this line causes the error > (see below) > > def escapeMetachars( s ): > """ > All metacharacters in the user provided substitution must > be escaped > """ > meta = r'\.^$+*?{[|()' > esc = '' > > for c in s: > if c in meta: > esc += '\\' + c > else: > esc += c > > return esc > > cts = """Compression=bzip/9 > OutputBaseFilename=$ > OutputDir=$ > LicenseFile=Z:\apps\easyjob\main\I18N\US\res\license.txt""" You forgot to double some backslashes here, not that this is relevant to your problem. > > name = 'OutputDir' > value = "c:\\apps\\whatever\\" # contains the backslash metachar > > print substitute( escapeMetachars(name), value, cts) > > I get this error: > Traceback (most recent call last): > File "", line 1, in -toplevel- > pat.sub(s,cts) Strangely, this line doesn't appear in the code you said you were using. > File "C:\ARCHIV~1\python23\Lib\sre.py", line 257, in _subx > template = _compile_repl(template, pattern) > File "C:\ARCHIV~1\python23\Lib\sre.py", line 244, in _compile_repl > raise error, v # invalid expression > error: bogus escape (end of line) > > What on earth is this? O:-) Whatever it is, its not what I get when I copy and paste your code. I get a "NameError: global name 'val' is not defined" when I use the code you posted. So, I deduce that you modified the code before posting it and all bets are off. However, it would appear that your main problem is that pat.sub will try to unescape any backslashes in the replacement string, so you want to double them all before using. Another minor point is that your escapeMetachars looks to be a poor-man's version of re.escape, so you might prefer to use re.escape instead. Putting that all together gives: >>> cts = """Compression=bzip/9 OutputBaseFilename=$ OutputDir=$ LicenseFile=Z:\\apps\\easyjob\\main\\I18N\\US\\res\\license.txt""" >>> name = 'OutputDir' >>> value = "c:\\apps\\whatever\\" # contains the backslash metachar >>> def substitute(name, value, cts): """ Finds all the occs in cts of $ and replaces them with value """ value = value.replace('\\', '\\\\') name = re.escape(name) pat = re.compile("\$<" + name + ">", re.IGNORECASE) return pat.sub(value, cts) >>> print substitute(name, value, cts) Compression=bzip/9 OutputBaseFilename=$ OutputDir=c:\apps\whatever\ LicenseFile=Z:\apps\easyjob\main\I18N\US\res\license.txt That will work fine so long as (a) you only have a few strings to substitute, and (b) none of the replacements contain sequences looking like substitution strings. If you have more strings to substitute you might try making a dict of replacements and applying them all at the same time: >>> def substitute(mapping, cts): """ Finds all the occs in cts of $ and replaces them with value """ pat = re.compile("\$<([^>]+)>", re.IGNORECASE) def repl(match): key = match.group(1).lower() return mapping[key] return pat.sub(repl, cts) >>> keys = { 'outputfilename': 'C:\\output.txt', 'outputdir': value } >>> print substitute(keys, cts) Compression=bzip/9 OutputBaseFilename=C:\output.txt OutputDir=c:\apps\whatever\ LicenseFile=Z:\apps\easyjob\main\I18N\US\res\license.txt -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From a.schmolck at gmx.net Tue Nov 18 12:37:15 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 18 Nov 2003 17:37:15 +0000 Subject: Can this be written more concisely in a functional style References: <92c59a2c.0311171648.6360213d@posting.google.com> <92c59a2c.0311172340.544faac6@posting.google.com> <698f09f8.0311180259.bdd4359@posting.google.com> <2259b0e2.0311180714.4f605bab@posting.google.com> Message-ID: Dennis Lee Bieber writes: > > def all(p, seq): > > """Returns true if all elements in seq satisfy predicate p.""" > > for elt in itertools.ifilterfalse(p, seq): > > return False > > return True > > > I'd be wasting a local with > > def any(p, seq): > """ibid""" > a = False > for elt in itertools.ifilter(p, seq): > a = True break > return a You're not just wasting a local. 'as From FBatista at uniFON.com.ar Tue Nov 4 12:35:46 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 4 Nov 2003 14:35:46 -0300 Subject: prePEP: Decimal data type Message-ID: Alex Martelli wrote: #- There may be a niche for a Rational data type, but in MHO it #- cannot take the #- place of a limited-precision-decimal (fixed or float). I #- suggest you think #- of a separate PEP to propose Rational (check the existing #- and rejected ones #- first, there may be some that are relevant) rather than #- attacking this one. #- ... #- (Facundo, I think you should include these considerations in #- the PEP to #- explain why you're NOT going for rationals.) OK. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 lance.ellinghaus at eds.com Mon Nov 3 14:40:45 2003 From: lance.ellinghaus at eds.com (Ellinghaus, Lance) Date: Mon, 3 Nov 2003 14:40:45 -0500 Subject: Does python always need to compile ENTIRE program before it c an start to run it??? Message-ID: <1093E8BAEB6AD411997300508BDF0A7C1571EE7B@ushem204.exse01.exch.eds.com> Python always compiles your scripts to bytecode before it can be executed. It cannot and does not do partial compilation and execution. But this is not the whole story. Python does not always have to do the compilation phase. When Python loads a module (.py file) from an 'import' statement, it will see if there is an already compiled version in the same directory and named the same except for the '.pyc' or '.pyo' extension. If it finds this file AND it is newer than the corresponding source code (.py) then it will load the saved compilation and then run it. If the file is not found or it is older than the source, then Python will compile the source, attempt to save the compiled version, and then it will execute it. I hope this helps answer your question. Lance Ellinghaus EDS - TWAI Operations Phone: 214-922-5454 Cell: 940-597-4755 -----Original Message----- From: seberino at spawar.navy.mil [mailto:seberino at spawar.navy.mil] Sent: Monday, November 03, 2003 1:45 PM To: python-list at python.org Subject: Does python always need to compile ENTIRE program before it can start to run it??? I can achieve something similar to Python's automatic compilation in C/C++ by making a script that compiles and runs my program like this: make ; myprogram I am trying to think of an advantage Python has over this hack.... Is it true that unlike C/C++ that Python programs can start executing before compilation is COMPLETELY done??? I think so but I'm not sure. Chris -- http://mail.python.org/mailman/listinfo/python-list From scrutinizer at gmx.at Tue Nov 18 13:16:02 2003 From: scrutinizer at gmx.at (Francesco) Date: Tue, 18 Nov 2003 19:16:02 +0100 Subject: simple program to prevent from exceptions Message-ID: Hello, I know pychecker, but is there a simpler program, which checks my source, in such a way, that it makes me attentive, if possible exception can occur. I think for example of using a varible, without setted before. thank you, -- Francesco From __peter__ at web.de Thu Nov 6 19:29:57 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Nov 2003 01:29:57 +0100 Subject: problem with Tk References: Message-ID: Lucas Raab wrote: > In browsing through the Python module index, I noticed the rotor > encryption module. It piqued my interest and I made a Tk app out of it. > The only problem is whenever I input a string to be encrypted I get the > error message: > > Exception in Tkinter callback > Traceback (most recent call last): > File: "C:\PYTHON23\lib\lib-tk\Tkinter.py", line 1345 in __call__ > return self.funcs(*args) > TypeError: encrypt() takes exactly 1 argument (0 given) > > Now is this bad programming on my part or something else? I'm running > Python 2.3.2 on a Win98 machine if that is of any relevance. > > See the attachment for the code. Please don't put your code into an attachment next time and try to provide the exact script you actually ran. I've made as few changes as possible: import Tkinter import rotor class Tkencryptor: def encrypt(self): # with your current design, there is no need for self self.rt = rotor.newrotor('key', 12) self.e=entry.get() print self.rt.encrypt(self.e) def decrypt(self): pass encryptor = Tkencryptor() win=Tkinter.Tk() frame = Tkinter.Frame() #quit button quit_button = Tkinter.Button(frame, text='Quit', command=frame.quit) quit_button.grid(row=1, column=0) #encrypt button encrypt = Tkinter.Button(frame, text='Encrypt', command=encryptor.encrypt) encrypt.grid(row=1, column=2) #decrypt button decrypt_button = Tkinter.Button(frame, text='Decrypt') decrypt_button.grid(row=1, column=3, sticky=Tkinter.S) #entry box entry = Tkinter.Entry() entry.pack() #pack frame frame.pack() win.mainloop() The significant change is the command parameter of the encrypt button. There are two ways of calling a method with only a self parameter: instance.method() # corresponds to command=instance.method or Class.method(instance) # command=Class.method As the command is called from inside Tkinter, which has no way of knowing the Tkencryptor instance, only the first form works. Peter PS: Did you notice the deprecation warning? From jjl at pobox.com Thu Nov 27 18:16:28 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Nov 2003 23:16:28 +0000 Subject: if - else References: <871xrtr8yb.fsf@pobox.com> <5ctxb.120283$Ec1.5141313@bgtnsc05-news.ops.worldnet.att.net> Message-ID: <87smk9mmgj.fsf@pobox.com> Jeff Wagner writes: > On Thu, 27 Nov 2003 22:28:29 GMT, Christopher Koppler wrotf: [...] > >It does assignment (=) instead of comparison (==) in the condition, > >which is illegal in Python. > > Yikes, I didn't even notice the = instead of the == ... thanks. That's why it's illegal :-) In C, this has caused endless bugs. It's the reason experienced C coders write stuff like: if (10 == sum) {...} rather than if (sum == 10) {...} -- the first won't compile if you accidentally write if (10 = sum) {...} Unfortunately, that doesn't get you out of all the trouble this causes. What would be nice in Python, I think, is an assignment operator for assignment expressions that can't be mistaken or mistyped for equality comparison. One trivial but annoyingly real problem is, ASCII has no decent arrow symbol -- and unicode saturation is a long way off. Guido seems to have no interest in the idea, anyway. John From saoirse_79 at yahoo.com Wed Nov 19 07:02:07 2003 From: saoirse_79 at yahoo.com (saoirse_79) Date: Wed, 19 Nov 2003 12:02:07 -0000 Subject: List of lists Message-ID: I was wondering if anyone knows a short way to do the following.. I have 2 lists of list..eg [('a','b','c'),('k','-','l'),('1','2','3')] [('a','b','c'),('k','-','x'),('1','4','3')] I want to comapre the two lists of lists and count the number of times the sublists match. In the above example its 1 From pmaupin at speakeasy.net Thu Nov 13 01:39:41 2003 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 12 Nov 2003 22:39:41 -0800 Subject: Conversion of 24bit binary to int References: <653b7547.0311111826.608ae618@posting.google.com> Message-ID: <653b7547.0311122239.79a91c52@posting.google.com> I just realized that, according to your spec, it ought to be possible to do the rgb -> bgr0 conversion on the entire file all at one go (no nasty headers or block headers to get in the way:) So I wrote a somewhat more comprehensible (for one thing, it gets rid of that nasty sum() everybody's been complaining about :), somewhat more memory-intensive version of the program. On my machine it executes at approximately the same speed as the original one I wrote (10 source megabytes/second), but this one might be more amenable to profiling and further point optimizations if necessary. The barebones (no comments or error-checking) functions are below. Pat import array def RgbToBgr0(srcstring): srcarray = array.array('B',srcstring) dstarray = array.array('B',len(srcstring) * 4 // 3 * chr(0)) for i in range(3): dstarray[2-i::4] = srcarray[i::3] return dstarray.tostring() def deinterleave(srcstring,numchannels=6,pixelsperblock=512): bytesperblock = pixelsperblock*4 totalblocks = len(srcstring) // bytesperblock blocknums = [] for i in range(numchannels): blocknums.extend(range(i,totalblocks,numchannels)) return ''.join([srcstring[i*bytesperblock:(i+1)*bytesperblock] for i in blocknums]) def mungefile(srcname,dstname): srcfile = open(srcname,'rb') dstfile = open(dstname,'wb') dstfile.write(deinterleave(RgbToBgr0(srcfile.read()))) srcfile.close() dstfile.close() From nav+posts at bandersnatch.org Wed Nov 12 10:06:51 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 12 Nov 2003 10:06:51 -0500 Subject: Get more from Google (was: programming languages (etc) "web popularity" fun) References: <9Vvob.74272$e5.2721707@news1.tin.it> Message-ID: "Cousin Stanley" writes: > Nick .... > I could probably translate .... > Declined the bid .... > As .... > Add another X% and a Partridge in a Pear Tree > and we MIGHT reconsider .... Except that Google declined forcefully enough that MSFT is apparently shopping elsewhere for their search engine. That could be a bargaining tactic, but it really doesn't look like it. To drag this thread kicking and screaming back onto topic, does anyone know what Google uses Python for, and to what extent? 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 buzzard at urubu.freeserve.co.uk Wed Nov 26 16:19:13 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Wed, 26 Nov 2003 21:19:13 -0000 Subject: Pychecker under Windows References: <153fa67.0311252016.2e02b575@posting.google.com> <153fa67.0311261206.648e73c6@posting.google.com> Message-ID: "Kylotan" wrote in message news:153fa67.0311261206.648e73c6 at posting.google.com... > "Duncan Smith" wrote in message news:... > > > > It seems to work for me in IDLE (well enough for my purposes, anyway). > > Yeah. I see what the issue is now - after Pychecker.checker is > imported, import statements work fine, but nothing else does at all. > So I just have to make sure that I set up the sys.path before I import > Pychecker, so that I am able to import my files. (Is there another > way?) > > -- > Ben Sizer I don't know. I don't use it very frequently. Is there any reason you can't fire up a couple of instances of IDLE and use one for 'pychecking' and do the rest of your stuff in another? Duncan From luis_ at iname.com Thu Nov 6 15:52:01 2003 From: luis_ at iname.com (Lupe) Date: Thu, 06 Nov 2003 20:52:01 +0000 Subject: thank you References: <3faab07b$0$58705$e4fe514c@news.xs4all.nl> Message-ID: I'm starting with Python and I find it really great! It's... natural! Lupe From alanmk at hotmail.com Tue Nov 11 12:08:48 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 11 Nov 2003 17:08:48 +0000 Subject: threads References: Message-ID: <3FB117A0.B828C0F9@hotmail.com> [Zunbeltz Izaola] > I want to know if it is posible to do this CHANGE of threads. It is not possible to "switch" execution between threads like this: the whole point of threads is that there multiple execution contexts operating in parallel. Once a thread has been started, it must run all the way through until it's execution terminates naturally. You cannot even raise exceptions in one thread from another thread. What you *can* do is communicate information between threads. This is most often done by using a Queue object, which you can read about here http://www.python.org/doc/current/lib/module-Queue.html So a good design pattern for what (I think) you're trying to do is to devise a class/object which represents the work to be done, and send that "work object" back and forth on the Queue between the threads. This way, it "appears" that the work is actually moving between threads. When there is no work for a thread to do, it is blocked in a Queue.get call, waiting for something to do. But it does not "go away". Of course, this is just one way to do it: another poster suggested another excellent approach: co-routines. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From ville.spammehardvainio at spamtut.fi Thu Nov 20 09:57:09 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 20 Nov 2003 16:57:09 +0200 Subject: New Guy References: <3l3nrv8p6a2jjv3erq9j4pc75tn9p6b5os@4ax.com> <3fbbf0b9$0$58703$e4fe514c@news.xs4all.nl> Message-ID: Ben Finney writes: > Vim does this (:set softtabstop=4 expandtab); I believe Emacs can also > do it. Yes, it's the default behaviour for python-mode.el. It's still funny to observe how some people are so fanatical about using tabs. Even talking about this issue is a good way to get flamed. Python is also very PC, and tries to indulge all the tabnicks to the greatest extent possible. Even if tabs are, objectively speaking, an inferior and less reliable system, and people probably use them because they must insist on using their inferior text editors (notepad?) for coding until the end of time... Python should interpret tabs so that tab stops would be 153 spaces apart, that way mixing tabs and spaces would never accidentally work. -- Ville Vainio http://www.students.tut.fi/~vainio24 From ray at rays-web.com Sat Nov 15 07:08:32 2003 From: ray at rays-web.com (Ray Smith) Date: Sat, 15 Nov 2003 12:08:32 GMT Subject: RuntimeError 'maximum recursion depth exceeded' In-Reply-To: <30ntb.5073$C14.183051@twister.southeast.rr.com> References: <30ntb.5073$C14.183051@twister.southeast.rr.com> Message-ID: <3fb616f5$1@news.syd.ip.net.au> Georgy Pruss wrote: > Sometimes I get this error. > E.g. > > >>>>sum = lambda n: n<=1 or n+sum(n-1) # just to illustrate the error >>>>sum(999) > > 499500 > >>>>sum(1000) > > ........... > RuntimeError: maximum recursion depth exceeded > > Is there any way to set a bigger stack in Python? > > G-: See sys.getrecursionlimit(), and sys.setrecursionlimit(limit) doco at: http://python.org/doc/current/lib/module-sys.html a quick search of the doco or the newsgroup archive at: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&group=comp.lang.python would have found the answer. Regards, Ray Smith From hwlgw at hotmail.com Tue Nov 18 16:42:40 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 18 Nov 2003 13:42:40 -0800 Subject: rotor alternative? References: Message-ID: > [Robin Becker] > It seems that the rotor module is being deprecated in 2.3, but there > doesn't seem to be an obvious alternative. I'm using it just for > obfuscation... Deprecation is a very serious matter. I love the Python language but I have questions about the deprecation decisions. The two deprecations I hate most are rotor and xmllib. I write software that sometimes has to run on Python 1.5.2 too, because of lazy web hostings, and I really hate to see the deprecation warnings now when I run it with Python 2.3 on my laptop. Doing try: import newstuff except ImportError: import oldstuff and then all the tweaking makes me feel like deinstalling 2.3. and installing 1.5.2 on the laptop too. Especially when there are no real good alternatives for the deprecated modules! Use xml.sax instead of xmllib you say? NO! The effbot said it well on c.l.p.: avoid SAX and DOM like the plague. -- rotor lives! From tzot at sil-tec.gr Wed Nov 5 13:47:34 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 05 Nov 2003 20:47:34 +0200 Subject: BUG? PyMem_Free vs strdup References: Message-ID: <18hiqv0qps5hk5fcng4brajsl4gcmjqmsj@4ax.com> On Wed, 5 Nov 2003 18:16:36 +0000, rumours say that Robin Becker might have written: >They all used to commingle quite happily and seem to do so under the >non-debug case, but now I suppose we're being stricter and stricter. I >suppose M$ spends all its money on marketing and fails to get the best >possible allocator. Have you seen the small video files with Steve Ballmer dancing around a podium as a monkey, then saying 'I love this company', then rhythmically calling out (possibly begging :-) for 'Developpers, developpers, developpers!' ? A sight to be seen. If you haven't and are interested, let me know by email and I'll make them available to you. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From adalke at mindspring.com Wed Nov 12 15:28:49 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 12 Nov 2003 20:28:49 GMT Subject: trouble understanding None References: Message-ID: <5Kwsb.8574$nz.317@newsread2.news.pas.earthlink.net> Jakle: > I'm trying to write a program (with my very limited knowledge of python) > that will convert text I type into those letters drawn with ascii symbols. BTW, if you get really into this you might want to take a look at figlet (http://www.figlet.org/ ) which both does this and provides fonts for you to do your own ASCII graphics. Andrew dalke at dalkescientific.com From aleax at aleax.it Fri Nov 14 13:03:39 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Nov 2003 18:03:39 GMT Subject: Python's simplicity philosophy References: <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: <%N8tb.28277$hV.1041253@news2.tin.it> Douglas Alan wrote: ... > Well, that's the argument you seem to be making -- that reduce() is > superfluous because a sum() and max() that work on sequences were > added to the language. "added"? 'max' worked that way since well before I met Python. But to be consistent with your other arguments, no doubt you'd argue for a .sort() followed by [-1] as "more general" than max... >>> I can already see what's going to happen with sum(): Ultimately, >>> people will realize that they may want to perform more general types >>> of sums, using alternate addition operations. > >> Not gonna happen - this _might_ happen if Python was a >> design-by-committee language, but it's not. > > According to Alex Martelli, max() and min() are likely to be extended > in this fashion. Why not sum() next? I was just presenting my personal opinion regarding the fact that the max and min functions should have an optional key= argument, simply because the .sort method now (2.4) has one too. If I implied that anything I feel should be done is automatically "likely" to be accepted by Guido, I apologize for mis-communicating; he throws stones at far more of my ideas than he embraces. >> To you, perhaps. Not me, and not a lot of other people. > > Well, perhaps you can explain your confusion to me? What could > possibly be unintuitive about a function that is just like sum(), yet > it allows you to specify the addition operation that you want to use? Addition, as you have remarked elsewhere, is intrinsically suitable for being applied to multiple operands; one is therefore naturally disposed to think in terms of "add them all up", "sum them all", and the like, NOT in terms of "iteratively perform total = operator.add(total, item) for all items in the sequence of numbers". But, reduce as it exists in Python today cannot be clearly defined EXCEPT by such an iteration with some generic "callable which accepts two arguments" specified in lieu of the operator.add. Given this total generality, even though hardly ever does it make sense to USE it, reduce becomes quite complex. You've even argued in this thread, incorrectly, that reduce could be eliminated if only all binary operators were able to accept arbitrary numbers of arguments. This, plus your insistence that 'reduce' is "just like" APL's / (which does NOT accept arbitrary functions on its left -- just specific operators such as +), indicate a _misconception_ of reduce on your part. I'm sure you don't hold it consciously, but these miscommunications indicate that even you, reduce's paladin, do NOT properly grasp reduce "intuitively". Having (e.g.) add accept a sequence argument (like max does), or, for explicitness and potentially performance, grow an add.reduce attribute just like in Numeric, would give no particular problems. I'd still want (just like Numeric does) to have sum as a name for add.reduce, because it's by far the most common case and avoids getting into the issue of what the (expletive delete) does "reducing" have to do with anything that "add.reduce" does (it's really a curve ball compared with the many meanings of "reduce" in English, after all). But, most importantly, such a design would avoid the veritable traps to which the current, too-general 'reduce' subjects the poor learner who's quite reasonably going to believe that all that generality MUST be good for something if it's been designed into a built-in. We've seen quite a few such inappropriate uses on this thread, after all. As I said, I'm not particularly good at guessing what Guido will or won't bless, but I suspect that a patch to the operator module to grow appropriate attributes on its functions, or even just make them accept multiple arguments, might be well-received (to avoid wasting work one might want a PEP or prePEP about that first, of course). > Of course, you can get the same effect by defining a class with your > own special __add__ operator, and then encapsulating all the objects > you want to add in this new class, and then using sum(), but that's a > rather high overhead way to accomplish the same thing that reduce() > lets you do very easily. In practice, I judge it quite unlikely that people will go out of their way to abuse sum as I've seen them abuse reduce -- reduce lets you abuse it very easily, as you mention, while sum needs you to really jump through hoops to do so. Alex From rainerd at eldwood.com Sat Nov 29 12:30:45 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Sat, 29 Nov 2003 17:30:45 GMT Subject: Printing dots in single-line References: <3fb39e32$1_1@nova.entelchile.net> Message-ID: <8J4yb.249740$mZ5.1858603@attbi_s54> Alok Singhal wrote: > Incidentally, I saw other responses, and most of them suggest > sys.stdout.write(). Is there a reason that is preferable over the > solution above? Yes: the print statement is an abomination. It is a special-case syntax for a task that requires no special syntax, and will hopefully be deprecated in the future, the sooner the better. It is also not as general as sys.stdout.write. It may be important that the dots are printed in separate statements. For example, the dots could be used as a progress indicator. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From usenet at icarus.freeuk.com Fri Nov 7 01:47:20 2003 From: usenet at icarus.freeuk.com (Icarus Sparry) Date: Fri, 07 Nov 2003 06:47:20 GMT Subject: Need help with OOP References: Message-ID: sinisam wrote: > Object oriented programming is not a new term to me, but when I tried > to do some of it... uhh... it sure looked (and felt) like Hell :) I > won't bother about things like "help me learn it" (but wouldn't mind > if someone recommends a good fresh-start tutorial), instead I'll ask > for help... > I did my share of programming several years ago... 6 or 7 to be more > specific, and as I'm pretty proud of my achievements ;) > I continued on the same path. Several weeks ago, Python showed up. > I got the 'assignment' to start learning it... almost professionally :) > > OK, I did my part, but now the tests are becoming more than fair :( > > Next part (even though I said I know *nothing* about OOP) is: > > "Make class for the IP address. It should be initialized from the > string. Later on, we can add functions to it." > > [1] What in the world I have to do here? > [1a] How to make class for the IP address? What does it mean? > [2] "Initialization from the string" means something like passing > arguments from the command line...? Warning - oversimplification ahead! With OOP, the idea is to make "Objects". In this case you want to make an object which represents an IP address. You will want (eventually) to have a list of things that you want to do to an IP address object, like create one, convert one to a name via the DNS, destroy one, pretend that CIDR doesn't exist and get the netmask for one and so on. In order to do these things you will need to have some data associated with the object. So all we need to do is package these things together (the functions you want to use with the object and the persistant data you need). This packaged "thing" is called a "class". In python, you define a function called __init__ which makes the objects, this is the initialization. So you fire up a copy of python. and get a prompt. You then type class ipaddress: def __init__(self,str): self.string_rep=str and press return some more times until you get the >>>> prompt back. This has defined a class called 'ipaddress', and made an initialization routine for it. This routine takes 2 parameters, the first is traditionally called 'self' and refers to the object itself. The second, named 'str', represents the string parameter. The action of the initialization routine is to store this string into an internal variable (called string_rep). You can now create an ipaddress object by typeing an_ip=ipaddress("192.168.1.1") and you can do things like print an_ip.string_rep Later on you will want to define other functions, and maybe add some more data. For instance you may want to define __str__(self) so you can just print out an object. It is worth working through the python tutorial if you have not already done so. To make life more interesting, OOP uses different words, like "method" to refer to one of the functions defined in the class. Above we created a variable called 'an_ip' which is an "instance" of the ipaddress class, we could make a second instance another_ip=ipaddress("192.168.1.2") Normally the __init__ method would do rather better error checking, so it made sure that it was being given a sensible string value, When you have more methods defined, you can use tham as an_ip.netmask() which would be written as netmask(an_ip) in most languages which are not OOP languages. Hope this very brief and superficial introduction helps. From bac at OCF.Berkeley.EDU Thu Nov 27 14:33:39 2003 From: bac at OCF.Berkeley.EDU (Brett C.) Date: Thu, 27 Nov 2003 11:33:39 -0800 Subject: python-dev Summary for 2003-10-16 through 2003-11-15 Message-ID: <3FC65193.7000300@ocf.berkeley.edu> python-dev Summary for 2003-10-16 through 2003-11-15 ++++++++++++++++++++++++++++++++++++++++++++++++++++ This is a summary of traffic on the `python-dev mailing list`_ from October 16, 2003 through November 15, 2003. 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 twenty-eighth and twenty-ninth summaries written by Brett Cannon (does anyone even read this?). 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 something mentioned here. 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. .. _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 .. contents:: .. _last summary: http://www.python.org/dev/summary/2003-09-01_2003-09-15.html ===================== Summary Announcements ===================== Thanks to midterms and projects my time got eaten up by school. That postponed when I could work on the twenty-eighth summary so much that the twenty-ninth was need of being written. So they are combined in into one to just get the stuff out the door. The second half of October had some major discussions happen. Guido and Alex Martelli talking equals pain for me. =) There was a large discussion on scoping and accessing specific namespaces. Jeremy Hylton is working on a PEP on the subject so I am not going to stress myself over summarizing the topic. A big discussion on the first half of November was about weakrefs and shutdown. Tim Peters figured out the problem (had to do with weakrefs referencing things already gc'ed and thus throwing a fit when trying to gc them later or keeping an object alive because of the weakref). It was long and complicated, but the problem was solved. If you have ever wanted to see linked lists used in Python in a rather elegant way, take a look at Guido's implementation of itertools.tee at http://mail.python.org/pipermail/python-dev/2003-October/039593.html . Europython is going to be held from June 7-9, 2004 in Sweden. See http://mail.python.org/pipermail/europython/2003-November/003634.html for more details. PyCon is slowly moving along. The registration site is being put through QA and the paper submission system is being worked on. The Call for Proposals (CFP) is still on-going; details at http://www.python.org/pycon/dc2004/cfp.html . Keep an eye out for when we announce when the registration and paper submission systems go live. ========= Summaries ========= ------------------------------------------ How to help with the development of Python ------------------------------------------ In an attempt to make it easy as possible for people to find out how they can help contribute to Python's development, I wrote an essay on the topic (mentioned last month, but some revisions have been done). It covers how Python is developed and how **anyone** can contribute to the development process. The latest version can be found at http://mail.python.org/pipermail/python-dev/2003-October/039473.html . Any comments on the essay are appreciated. Contributing threads: - `Draft of an essay on Python development `__ - `2nd draft of "How Py is Developed" essay `__ ------------------------------------------------ Generator Expressions: list comp's older brother ------------------------------------------------ If you ever wanted to have the power of list comprehensions but without the overhead of generating the entire list you have Peter Norvig to thank initially, and then what seems like the rest of the world, for generator expressions. `PEP 289`_ covers all the details, but here is a quick intro. You can think of generator expressions as list comprehensions that return an iterator for each item instead a list items. The syntax is practically the same as list comprehensions as well; just substitute parentheses for square brackets (most of the time; generator expressions just need parentheses around them, so being the only argument to a method takes care of the parentheses requirement). A quick example is:: (x for x in range(10) if x%2) returns an iterator that returns the odd numbers from 0 to 10. This make list comprehensions just syntactic sugar for passing a generator expression to list() (note how extra parentheses are not needed):: list(x for x in range(10) is x%2) Having list comprehensions defined this way also takes away the dangling item variable for the 'for' loop. Using that dangling variable is now discouraged and will be made illegal at some point. For complete details, read the PEP. .. _PEP 289: http://www.python.org/peps/pep-0289.html Contributing threads: - `decorate-sort-undecorate `__ - `accumulator display syntax `__ - `listcomps vs. for loops `__ - `PEP 289: Generator Expressions (second draft) `__ --------------------- list.sorted() is born --------------------- After the addition of the 'key' argument to list.sort(), people began to clamor for list.sort() to return self. Guido refused to do give in, so a compromise was reached. 'list' now has a class method named 'sorted'; pass it an iterable and it will return a sorted list. Contributing threads: - `decorate-sort-undecorate `__ - `inline sort option `__ - `sort() return value `__ - `copysort patch `__ ------------------------------------ Recursion limit in re is now history ------------------------------------ Thanks to Gustavo Niemeyer the recursion limit in the re module has now be removed! Contributing threads: - `SRE recursion `__ - `SRE recursion removed `__ ----------------------------------- Copying iterators one day at a time ----------------------------------- Reiteration for iterators came up as part of the immense discussion on generator expressions. The difficulty of doing it generally came up. This lead to Alex Martelli proposing magic method support for __copy__ in iterators that have want to allow making a copy of itself. This was written down as `PEP 323`_. As an interim solution, itertools grew a new function: tee. It takes in an iterable and returns two or more iterators which independently iterate over the iterable. .. _PEP 323: http://www.python.org/peps/pep-0323.html Contributing threads: - `Reiterability `__ - `cloning iterators again `__ - `... python/nondist/peps pep-0323.txt, NONE ... `__ - `Guido's Magic Code `__ ------------------------------------------------------ Returning Py_(None, True, False) now easier than ever! ------------------------------------------------------ Py_RETURN_NONE, Py_RETURN_TRUE, and Py_RETURN_FALSE have been added to Python 2.4. They are macros for returning the singleton mentioned in the name. Documentation has yet to be written (my fault). Contributing threads: - `How to spell Py_return_None and friends `__ - `python/dist/src/Include object.h, 2.121, ... `__ ------------------------------------------------------------------------- 'String substitutions'/'dict interpolation'/'replace %(blah)s with $blah' ------------------------------------------------------------------------- The idea of introducing string substitutions using '$' came up. Guido said that if this was made a built-in feature it would have to wait until Python 3. He was receptive to moving the functionality to a module, though. Barry Warsaw pasted code into http://mail.python.org/pipermail/python-dev/2003-October/039369.html that handles string substitutions. Contributing threads: - `Can we please have a better dict interpolation syntax? `__ ------------------------------------------ "reduce() just doesn't get enough mileage" ------------------------------------------ That quote comes from Guido during the discussion over whether 'product' should be added as an accumulator function built-in like 'sum'. The idea was shot down and conversation quickly turned to whether 'reduce' should stay in the language (the consensus was "no" since the function does not read well and its functionality can easily be done with a 'for' loop). A larger discussion on what built-ins should eventually disappear will be covered in the next Summary. Contributing threads: - `product() `__ ----------- PyPy update ----------- The PyPy_ development group sent an update on their happenings to the list. Turns out they are trying to get funding from the European Union. They are also fairly close to getting a working version (albeit with some bootstrapping from CPython, but it will still be damn cool what they have pulled off even with this caveat). They also announced a sprint they are holding in Amsterdam from Dec. 14-21. More info can be found at http://codespeak.net/moin/pypy/moin.cgi/AmsterdamSprint . .. _PyPy: http://codespeak.net/pypy/ Contributing threads: - `PyPy: sprint and news `__ ---------------------------- Never say Python is finished ---------------------------- I asked python-dev for masters thesis ideas. I great number of possibilities were put out. If anyone out there is curious to see what some people would like to see done for Python in terms of a large project check the thread out. Contributing threads: - `Looking for master thesis ideas involving Python `__ --------------------------------- Rough draft of Decimal object PEP --------------------------------- Facundo Batista has posted a rough draft of a PEP for a decimal object that is being worked on in the sandbox. Comment on it on `comp.lang.python`_ if this interests you. Contributing threads: - `prePEP: Decimal data type `__ ---------------------------------------------------------- Relations of basestring and bye-bye operator.isMappingType ---------------------------------------------------------- The idea of introducing relatives of basestring for numbers came from Alex Martelli. That idea was shot down for not being needed once the merger of int and long occurs. The point that operator.isMappingType is kind of broken came up. Both Alex and Raymond Hettinger would not mind seeing it disappear. No one objected. It is still in CVS at the moment, but I would not count on it necessarily sticking around (although there are rumblings that there might be a way to fix it so it is partially useful). Contributed threads: - `reflections on basestring -- and other abstract basetypes `__ - `operator.isMappingType `__ --------------------------------------------------------- Why one checks into the trunk before a maintenance branch --------------------------------------------------------- The question of whether checking a change into a maintenance branch before applying it to the main trunk was acceptable came up. The short answer is "no". Basically the trunk gets more testing than the maintenance branches and thus the patch should have to prove its stability first. Only then should it go into a maintenance branch. The same goes for changes to code that will eventually disappear in the trunk. Someone might be planning on removing some code, but if that person falls off the face of the earth the code will still be there. That means applying the patch to the code that is scheduled to disappear is still a good idea. Contributing threads: - `check-in policy, trunk vs maintenance branch `__ ----------------------- New reversed() built-in ----------------------- There was a new built-in named reversed(), and all rejoiced after giving the creator a thorough beating. Straight from the function's doc string: "reverse iterator over values of the sequence". `PEP 322`_ has the relevant details on this new built-in. .. _PEP 322: http://www.python.org/peps/pep-0322.html Contributing threads: - `PEP 322: Reverse Iteration `__ --------------------------- Cleaning the built-in house --------------------------- Guido asked what built-ins should be considered for deprecation. Instantly intern, coerce, and apply came up. apply already had a PendingDeprecationWarning and that will stay for the next release or two. intern and coerce, though, did not have any major champions (intern had some fans, but just for the functionality). Guido did state that none of these built-in will be removed any time soon. If they do get deprecated it does not lead to immediate removal. Python 3, though, takes the gloves off and that can see them just completely disappear. Contributing threads: - `Deprecating obsolete builtins `__ ---------------------------------------- Passing arguments to str.(encode|decode) ---------------------------------------- The idea of allowing keyword arguments be passed to any specified encoder/decoder was brought up by Raymond Hettinger. It seemed like an idea that was supported. The idea of specifying the encoder or decoder based on the actual object instead of the current way of specifying a string that is passed to the registered codec search functions was suggested. Nothing has been finalized on this idea as of now. Contributing threads: - `Optional arguments for str.encode /.decode `__ ------------------------------------------------------ Where, oh where, to move the good stuff out of string? ------------------------------------------------------ It looks like ascii_* and possibly maketrans from the string module will be tacked on to the str type so that the string module can finally be removed from the language. It has not been pronounced upon, but it looks like that is what the BDFL is leaning towards. Issues of using the methods of str as unbound methods did come up. As it stands you cannot pass a unicode object to str.upper and thus there is no one uppercasing function as there is in the string module. This issue brought up the problem of Unicode and locale ties and collation (how to sort things). Contributing threads: - `other "magic strings" issues `__ ----------------------------------------- Supported versions of Sleepycat for bsddb ----------------------------------------- The basic answer is 3.2 - 4.2 should work when you compile from source. Contributing threads: - `which sleepycat versions do we support in 2.3.* ? `__ ----------------------------- Sets now at blazing C speeds! ----------------------------- Raymond Hettinger implemented the sets API in C! The new built-ins are set (which replaces sets.Set) and frozenset (which replaces sets.ImmutableSet). The APIs are the same as the sets module sans the name change from ImmutableSet to frozenset. Contributing threads: - `set() and frozenset() `__ From __peter__ at web.de Fri Nov 21 12:56:18 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Nov 2003 18:56:18 +0100 Subject: Empty list as default parameter References: Message-ID: Fredrik Lundh wrote: > or perhaps: > > def __init__( self, myList=None): > self.myList = myList or [] This treats empty and non-empty myList args differently: >>> mylist = [] >>> (mylist or []) is mylist False >>> mylist = [1] >>> (mylist or []) is mylist True To be consistent you could do self.myList = myList[:] or [] >>> mylist = [] >>> (mylist[:] or []) is mylist False >>> mylist = [1] >>> (mylist[:] or []) is mylist False or avoid the above pattern altogether. Peter From mis6 at pitt.edu Tue Nov 25 01:08:36 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 24 Nov 2003 22:08:36 -0800 Subject: another candidate for deprecation (was: Why should input(prompt="hello:") fail?) References: <37ba82ff.0311240831.6e0dfba7@posting.google.com> <3FC23B46.8E2BF00B@engcorp.com> Message-ID: <2259b0e2.0311242208.6f74e99e@posting.google.com> Peter Hansen wrote in message news:<3FC23B46.8E2BF00B at engcorp.com>... > Note however that input() is a poor choice for serious work: you > should quickly get past the point of wanting to use it and learn > why raw_input() is a better choice. > > -Peter Very true. Is "input" a candidate for deprecation in 3.0? If not, here I give my vote to put "input" in the black list ;) Michele From __peter__ at web.de Thu Nov 6 03:09:56 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Nov 2003 09:09:56 +0100 Subject: Metaclass and __slots__ References: Message-ID: anabell at sh163.net wrote: > Do I need to define my own metaclass in order to use __slots__? Some things ar better tried than asked :-) >>> class S(object): ... __slots__ = "slots are bad".split() ... >>> s = S() >>> s.bad = "as you can get" >>> s.good = "to know" Traceback (most recent call last): File "", line 1, in ? AttributeError: 'S' object has no attribute 'good' >>> Peter From juntu at operamail.com Thu Nov 27 03:45:18 2003 From: juntu at operamail.com (Juntu) Date: 27 Nov 2003 00:45:18 -0800 Subject: pymat and Matlab6.5 References: Message-ID: John Hunter wrote in message news:... > >>>>> "Juntu" == Juntu writes: > > Juntu> To who read this message: I am trying to use pymat with > Juntu> python2.3 and matlab6.5 but unfortunatlly it does not work > Juntu> because it is intended for python2.2. I tried to recompile > Juntu> the source code to make it work with matlab6.5 and > Juntu> python2.3 platform but it does not work for my at all. Is > Juntu> there any one in this plant who have already the compiled > Juntu> library and sned it to me by email or post it in the > Juntu> internet in the Python web site. > > Not an answer to your question but, what are you trying to do? > > Numeric and scipy provide a lot of matlab functionality -- the MLab > module of Numeric provides many functions with matlab compatible > arguments and return values. There are python modules for loading > *.mat files into python dictionaries in the matfile library > ftp://ion.le.ac.uk/matfile/matfile.tar.gz. The matplotlib.mlab > library complements MLab by adding more matlab compatible functions to > python, and matplotlib.matlab library provides matlab compatible > plotting in python > > http://matplotlib.sourceforge.net > > If using python instead of matlab is an option for you, let us know > what you are trying to do and in most cases my guess is there is a > python solution. > > Former pymat user now almost completely weaned from matlab, > John Hunter >----------- From Juntu, The same prolem again. I found no binaries of Scipy for Python2.3 under Windows Xp. To compile the source code you need many package which really I do not want to install them in my computer, and also I do not have enough experience to do complilation process. Is there someone who already compiled Scipy to work for Pyhton2.3 for Win32 patform???. Thanks From sunking77 at hotmail.com Sat Nov 1 18:32:10 2003 From: sunking77 at hotmail.com (Ray) Date: Sat, 1 Nov 2003 15:32:10 -0800 Subject: Py2exe error messages Message-ID: <000001c3a0d0$5f43dab0$041ad20c@computer> Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Python22>python setup.py py2exe --icon EXE icon Traceback (most recent call last): File "setup.py", line 7, in ? scripts = ["wxApp1.py"], File "C:\Python22\distutils\core.py", line 101, in setup _setup_distribution = dist = klass(attrs) File "C:\Python22\distutils\dist.py", line 130, in __init__ setattr(self, method_name, getattr(self.metadata, method_name)) AttributeError: DistributionMetadata instance has no attribute 'get___doc__' This is the error message I'm getting when I try to run This is my setup script: from distutils.core import setup import py2exe setup(name = 'Notebook', version = '0.1', description = 'Simple Text Editor', author = 'Ray Sleeper', author_email = 'sunking77 at hotmail.com', url = ' ', scripts = ["wxApp1.py"], I'm using Python2.2 and Boa0.2.3 if that helps Why am I getting this error message? From skemplay at dingley.net Fri Nov 7 07:48:17 2003 From: skemplay at dingley.net (S Kemplay) Date: Fri, 7 Nov 2003 23:48:17 +1100 Subject: Why does this choke? In-Reply-To: <87wuac1huw.fsf@pobox.com> References: <87wuac1huw.fsf@pobox.com> Message-ID: <200311072348.17568.skemplay@dingley.net> Thanks John, that explains it :) Sean Kemplay On Friday 07 November 2003 23:30, John J. Lee wrote: > S Kemplay writes: > > I wrote a script to choose random dates for a statistics assignment. > > I only need to choose 30 dates from one year with no leap years and it > > works fine. However I tested with different numbers of dates. It hangs > > from 450 up. I only need 30 dates but it would be good to know why it > > hangs. (My coding probably has something to do with it :)) > > [...] > > > if (day, month) in dates: > > continue > > [...] > > This looks like the culprit. I bet it really hangs from 366 up . > > > John From asdf at asdf.com Sun Nov 30 03:39:33 2003 From: asdf at asdf.com (John Smith) Date: Sun, 30 Nov 2003 03:39:33 -0500 Subject: pil bug? Message-ID: Hello, I don't know if this is a bug or not, but when you convert an image from one mode to another, the object's filename gets lost in the conversion process. for example: >>import Image >>im = Image.open('someRGB.bmp') >>im.filename 'someRGB.bmp' >>im = im.convert('L') >>im.filename error: no attribute called filename is this a bug? The simple solution is to assign a new attribute called filename to the newly converted object, but it seems like filenames should probably be kept?? opinions? suggestions? thanks in advance From mwh at python.net Thu Nov 20 11:30:00 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 20 Nov 2003 16:30:00 GMT Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <3FBB805D.40A8DA75@engcorp.com> Message-ID: "Dave Brueck" writes: > Hmmm... the more I think about it I guess the root cause of the > problem is the archaic, goofy encryption export laws of the U.S.. Unfortunately the US is far from having a monopoly on silly export laws about crypto. Given the -- highly international -- way the last year or so of Python development have gone and e.g. where www.python.org is located it's unclear what *any* countries *export* laws have to do with it, but unfortunately many countries have *import* laws too. The world is a sorry place. Cheers, mwh -- ARTHUR: Ford, you're turning into a penguin, stop it. -- The Hitch-Hikers Guide to the Galaxy, Episode 2 From n.vanweersch at hccnet.nl Tue Nov 4 15:00:32 2003 From: n.vanweersch at hccnet.nl (W. Vanweersch) Date: Tue, 4 Nov 2003 21:00:32 +0100 Subject: round off Message-ID: <001401c3a30e$4e070b60$9600000a@vanq3f9r2bpz4o> Hello, The following looks strange to me in Python: 7/-3 gives -3 It looks like Python rounds off -2.33333 to -3! is this correct?? Isn't it -2? Greets, Wim. -------------- next part -------------- An HTML attachment was scrubbed... URL: From maximo at meteorstudios.com Mon Nov 17 16:12:43 2003 From: maximo at meteorstudios.com (Maxim Olivier-Adlhoch) Date: Mon, 17 Nov 2003 16:12:43 -0500 Subject: socket object, connection refused ... Message-ID: that's it !!! The docs really are misleading, especially if you've done this sort of thing in other languages and localhost is used as a reference to 'self'... without reference to any NIC. thanks soooo much! -MAx --- "You can either be part of the problem or part of the solution, but in the end, being part of the problem is much more fun." > -----Original Message----- > From: Diez B. Roggisch [mailto:deets_noospaam at web.de] > Sent: Monday, November 17, 2003 3:52 PM > To: python-list at python.org > Subject: Re: socket object, connection refused ... > > > Hi, > > > using 'localhost' or '127.0.0.1' always works, using my > actual machine's > > ip or its hostname does not!! > > I had the exact problem last week - I think there should be > an update to the > docs, as these say: > > > # Echo server program > import socket > > HOST = '' # Symbolic name meaning the local host > > > > Unfortunately, this is not right - what happens wheny you > bind localhost or > 127.0.0.1, the socket _only_ listens on your local loop back > device. When > binging to '', this means "bind to all IPs of this machine" - > and thats > exactly what you are looking for. > > So try to either explictely bind to your IP, or '' - that will help. > > Regards, > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From nessus at mit.edu Tue Nov 11 12:21:24 2003 From: nessus at mit.edu (Douglas Alan) Date: Tue, 11 Nov 2003 12:21:24 -0500 Subject: Python's simplicity philosophy References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: "Dave Brueck" writes: > Part of the problem here is that just saying "only one way to do it" is a > horrible misquote, and one that unfortunately misses IMO some of the most > important parts of that "mantra": Well, perhaps anything like "only one way to do it" should be removed from the mantra altogether, since people keep misquoting it in order to support their position of removing beautiful features like reduce() from the language. |>oug From a.schmolck at gmx.net Tue Nov 18 12:39:22 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 18 Nov 2003 17:39:22 +0000 Subject: Can this be written more concisely in a functional style References: <92c59a2c.0311171648.6360213d@posting.google.com> <92c59a2c.0311172340.544faac6@posting.google.com> <698f09f8.0311180259.bdd4359@posting.google.com> <2259b0e2.0311180714.4f605bab@posting.google.com> Message-ID: mis6 at pitt.edu (Michele Simionato) writes: > Am I the only one? ;) I think such code is likely to fool people into thinking that the else part of loops is only executed if no single iteration takes place. 'as From cpgray at library.uwaterloo.ca Tue Nov 18 11:16:51 2003 From: cpgray at library.uwaterloo.ca (Chris Gray) Date: Tue, 18 Nov 2003 11:16:51 -0500 Subject: Looking for an http proxy server written in Python In-Reply-To: <3FBA38B9.42F93370@hotmail.com> References: <3FBA38B9.42F93370@hotmail.com> Message-ID: Thanks, Alan, Your resource page is very helpful and your "Why" section explains exactly why I'm interested in this. At first blush it looks like httpMonitor is most in line with what I'm planning, namely, the ability to do arbitrary processing on requests and responses. The problem I've run across so far is transparency and performance. I've written my own proxy server and experimented with WebDebug and found that some things slow down considerably and other things don't seem to pass through at all. I want, as much as possible, for the proxy to pass requests and responses through in a way that makes no difference to the client, but gives me a hook to hang selective logging, storage, and other processing on. That's why I specified production-quality and HTTP/1.1 compliance. If I could just find a proxy server that forwarded requests and responses seamlessly, I'd be happy. Thanks again, Chris "Okey dokey.. free my mind. Right, no problem, free my mind, free my mind, no problem, right... " -The Matrix On Tue, 18 Nov 2003, Alan Kennedy wrote: > [Chris Gray] > > I'm looking for a > > production-quality proxy server fully compliant with HTTP/1.1 written in > > Python. > > > > If there isn't, is there anything that comes close? > > That depends on what you want the proxy to do. > > Check the following page for a list of python http proxies. > > http://xhaus.com/alan/python/proxies.html > > If there's nothing there that catches your eye, then give a clearer > indication of what you need the proxy to do. > > regards, > > -- > alan kennedy > ----------------------------------------------------- > check http headers here: http://xhaus.com/headers > email alan: http://xhaus.com/mailto/alan > From my-first-name at hazen.net Wed Nov 19 05:54:59 2003 From: my-first-name at hazen.net (my-first-name at hazen.net) Date: Wed, 19 Nov 2003 02:54:59 -0800 Subject: New Guy In-Reply-To: References: Message-ID: <20031119105459.GA13594@gate2.hazen.net> [NArDS] > while gen <=40 : > > gen=gen+1 > e= (b+d)/2+ (b-c) > f= (a+c)/2+(b-d) > g=(b+d)/2+(c-a) > h=(a+c)/2+(d-b) > > print gen,a,b,c,d > print gen,e,f,g,h > > if e >= 1: > a=e > else : > a=0 [Duncan] > The problem is that you have indented the 'if' statements. You aren't > allowed to indent code arbitrarily in Python. Indent inside blocks, but the > first if statement doesn't start a new block, so it MUST be at exactly the > same indentation level as the preceding print statement. While this is correct, looking at the code makes me think that everything is intended to be in the while loop (otherwise it doesn't do anything). So try indenting the print statements to the same level as everything else in the loop. Hopefully, the results will be closer to what you expected. -John (john at my-domain -- see from address) From aleax at aleax.it Tue Nov 11 12:09:01 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 11 Nov 2003 17:09:01 GMT Subject: Python's simplicity philosophy (was Re: reduce()--what is it good for?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> <847upWAopMs$EwBp@jessikat.fsnet.co.uk> Message-ID: Robin Becker wrote: ... >>Python's essence is simplicity and uniformity. Having extra features >>in the language and built-ins runs directly counter to that. > > no disagreement, reduce is in line with that philosophy sum is a > shortcut and as others have said is less general. 'sum' is _way simpler_: _everybody_ understands what it means to sum a bunch of numbers, _without_ necessarily having studied computer science. The claim, made by somebody else, that _every_ CS 101 course teaches the functionality of 'reduce' is not just false, but utterly absurd: 'reduce', 'foldl', and similar higher-order functions, were not taught to me back when _I_ took my first university exam in CS [it used Fortran as te main language], they were not taught to my son in _his_ equivalent course [it used Pascal], and are not going to be taught to my daughter in _her_ equivalent course [it uses C]. Google for "CS 101" and convince yourself of how utterly absurd that claim is, if needed -- how small is the proportion of "CS 101" courses that teach these subjects. Python's purpose is not, and has never been, to maximize the generality of the constructs it offers. For example, Ruby's hashes (and, I believe, Perl's) are more general than Python's dicts, because in those hashes you can use arbitrary mutable keys -- e.g., arrays (Ruby's equivalent of Python's lists), strings (which in Ruby are mutable -- more general than Python's strings, innit?), etc. Python carefully balances generality, simplicity, and performance considerations. Every design is a series of compromise decisions, and Python's design is, in my opinion, the best one around (for my purposes) because those compromises are struck with an _excellent_ batting average (not perfectly, but better than any other language I've ever studied, or designed myself). The underlying idea that there should preferably be ONE obvious way to express a solution is part of what has kept Python so great as it evolved during the years. >>> The whole 'only one way to do it' concept is almost certainly wrong. >> >>Bingo! You disagree with the keystone of Python's philosophy. Every >>other disagreement, quite consequently, follows from this one. > > not so, I agree that there ought to be at least one way to do it. But not with the parts that I quoted from the "spirit of C", and I repeat them because they were SO crucial in the success of C as a lower-level language AND are similarly crucial in the excellence of Python as a higher-level one -- design principles that are *VERY* rare among computer languages and systems, by the way: Keep the language small and simple. Provide only one way to do an operation. "Only one way" is of course an _ideal_ goal (so I believe the way it's phrased in Python, "preferably only one obvious way") -- but it's a guiding light in the fog of languages constructed instead according to YOUR completely oppposite goal, and I quote you: There should be maximal freedom to express algorithms. Choose just about every OTHER language on Earth, and you'll find it TRIES (with better or worse results depending on how well or badly it was designed, of course) to meet your expressed goal. But NOT Python: you're using one of the _extremely few_ languages that expressly do NOT try to provide such "maximal freedom", that try instead to stay small and simple and provide (preferably) only one (obvious) way to do an operation. Your choice of language is extremely peculiar in that it _contradicts_ your stated goal! >>Want "maximal freedom to express algorithms"? You can choose among > > ... you may be right, but I object to attempts to restrict my existing > freedoms at the expense of stability of Python as a whole. Nobody restricts your existing freedom of using Python 2.3.2 (or whatever other release you prefer) and all of its constructs and built-ins; nobody ever proposed retroactively changing the license to do that (and I doubt it could be done even if anyone wished!). But we're talking about Python 3.0, "the point at which backwards compatibility will be broken" -- the next _major_ release. To quote Guido, in 3.0 "We're throwing away a lot of the cruft that Python has accumulated." After a dozen years of backwards compatible growth, Python has a surprisingly small amount of such cruft, but it definitely does have some. Exactly _what_ qualifies as 'cruft' is not yet decided, and it won't be for quite a while (Guido thinks he won't do 3.0 until he can take PSF-financed time off to make sure he does it right). But there is no doubt that "reduce feature duplication" and "change rules every so slightly to benefit optimization" _are_ going to be the themes of 3.0. Python can't keep growing with great new ideas, _AND_ still be a small and simple language, without shedding old ideas that do not pull their weight any more, if they ever did. Check out, e.g., the "python regrets" talk of well over a year ago, http://www.python.org/doc/essays/ppt/regrets/PythonRegrets.ppt to see that lambda, map, filter, and reduce are all among those regrets -- things that Guido believe he never should have allowed in the language in the first place. E.g., and I quote from him: """ reduce() nobody uses it, few understand it a for loop is clearer & (usually) faster """ and that was way BEFORE sum took away the vast majority of reduce's use cases -- so, guess how he may feel about it now...? One of Python's realities is that _Guido decides_. Not without lots of pressure being put on him each and every time he does decide, of course -- that's part of why he doesn't read c.l.py any more, because the pressure from this venue had gotten way excessive. Of course, he's going to be pressured on each and every one of the items he mentions in detail in the "regrets" talk and more summarily in the Python 3.0 "State of the Python Union" talk. But I'm surely not the only one convinced that here, like in (by far) most difficult design decisions in Python's past, he's on the right track. Python does need to keep growing (languages that stop growing die), but it must not become big, so it must at long last lose SOME of the accumulated cruft, the "feature duplication". I'll deeply regret, come Python 3.0, not being able to code "if blah(): fleep()" on one single like any more, personally. And I may try to put on pressure for a last-minute reprieve for my own pet "duplicated feature", of course. But in the end, if I use Python it's because I believe Guido is a better language designer than I am (and that most other language designers are), so I will accept and respect his decisions (and maybe keep whining about it forevermore, as I do for the "print>>bah,gorp" one:-). >>But can't you let us have *ONE* language that's designed according > > I am not attempting to restrict anyone or change anyone's programming > style. I just prefer to have a stable language. I think Python's stability is superb, but stability cannot mean that there will never be a 3.0 release, or that the language will have to carry around forever any mistaken decision that was once taken. I'm not advocating a "high level of churn" or anything like that: we have extremely "sedate" and stable processes to gradually deprecate old features. But such deprecation _will_ happen -- of that, there is most definitely no doubt. Alex From peter at engcorp.com Tue Nov 4 08:25:48 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 04 Nov 2003 08:25:48 -0500 Subject: New to Python - Compiled Language? References: Message-ID: <3FA7A8DC.23981AA5@engcorp.com> Relee Squirrel wrote: > > I just found out about Python today and it sounds very interesting, > but I'm having trouble finding solid information about my main > question. Is Python a compiled language, or merely a sequence of > commands fed into a seperate program? Why is that your main question? If it's not just curiosity, can you explain why this issue concerns you? If you think the world is divided into "compiled" and "not compiled" languages, you are missing some useful and interesting experience. You might also be missing some great opportunities if you let that impact your decision-making in a big way. > The impression I get from www.python.org is that it is a compiled > very high level language, which is extendable via C++. I'm a C++ > programmer and the tools and utilities referred to existing in Python > would increase the development time of my projects. However, what I'm > creating are programs, not just scripts. My company (Kaval Wireless) uses Python to create "programs" which would have been created in C (if, say, we were insane) but which we chose to create in Python. We did this because it is a very high-level language which allows us to get more work done in less time, with higher quality results. It's also easier to do with Python, and much more fun! The products range from embedded industrial controllers through automated testing systems right up to Intranet servers. Oh yeah, we also write "scripts" using Python, when necessary (to use the meaning I suspect you assign to that term). > Is Python a language which can be compiled into an executable program? Definitely. We do it frequently. The fact that it is not done in the traditional (and rapidly becoming obsolete) way that, say, C++ is handled is not important to us. As a C++ programmer, I suspect you consider Java a "real" language, and not a scripting language. You've surely seen the market for programmers using Java grow and in some cases impact on the market for C++ programmers. Just so you know, Python is a compiled language in much the way Java is -- specifically the code compiles to byte code (like "machine code") for a "virtual machine". Other than the fact that CPUs that natively execute Python byte code don't actually exist (though they now do for Java, of course), there's not much difference in that respect. In the end, it's easiest to download it (since it's free after all) and whip through the tutorial, which you can probably manage in an hour or so. Afterwards, if you aren't inspired to try more, at least you gave it a shot. On the other hand, you might start to see some potential, and if you do I predict you'll rapidly find fewer and fewer places where using C++ seems reasonable. -Peter From for_usenet2000 at yahoo.de Mon Nov 3 12:03:48 2003 From: for_usenet2000 at yahoo.de (Daniel Schüle) Date: Mon, 3 Nov 2003 18:03:48 +0100 Subject: static? + some stuff Message-ID: Hi all I have 2 questions 1) is there a way do declare static variables in a class? I coded this logic in global variable foo_cnt 2) is there a way to see the types of all data/function members of a class? dir(cls) returns a list of strings (of members) so it's logical that type(tmp.i) fails ... is it possible at all? thanks for your time -- Daniel foo_cnt = 0 #<<<< Message-ID: <3FAF5AF6.B97DA23E@alcyone.com> Parzival wrote: > It further tuns out that I have no control over the placement of > entries > in PATH, so that my .bash_profile login script which adds > /usr/local/bin to > the PATH, wherein are "python", "python2.3" and "idle", does not have > precedence over the Mandrake installed /usr/bin, wherein are "python" > and > "idle". The result is that I must type "python2.3 myscript.py" or > "/usr/local/bin/idle myscript.py", and the just explained > "#!/usr/bin/env > python" at the start of scripts always resolves in favour of the > Mandrake > installed Python, not my own current version. Yes, unfortunately this is the fault of the #!/usr/bin/env solution (neglecting that in very rare cases env may not be located in /usr/bin). If multiple Python interpreters are installed, or the same script are run with rather different environments, then it's hard to say which interpreter will get caught. For instance, cron jobs often run with PATH=/bin:/usr/bin only, in which case they wouldn't ever find a python in /usr/local/bin, unless you told it to do so. > I would like my personal installation of Python to be the default and > convenient version, i.e. "./Myscript.py" "python MyScript.py" and > "idle" > should resolve that instead of the system version. Is there a good way > to > accomplish this? The best way to do it for your use is to put the place where you want it found first in your PATH, or invoke the specific interpreter you want directly. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Human love is often but the encounter of two weaknesses. \__/ Francois Mauriac From dyoo at hkn.eecs.berkeley.edu Sat Nov 1 21:11:29 2003 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sun, 2 Nov 2003 02:11:29 +0000 (UTC) Subject: ANN: BayPIGgies meeting for Thursday, November 13, 2003 Message-ID: When: Thursday, November 13, 2003 Where: Carnegie Institute of Washington at Stanford University; Palo Alto Agenda: What's new in Python? Not your usual list of new features Speaker: Guido van Rossum Python is an OO programming language that is usable for pedestrian tasks typically called "scripting", as well as for the construction of highly advanced class libraries. The latest versions, Python 2.2 and 2.3, have added significant power to Python's competence in the latter area, primarily through the introduction of two new concepts: iterators (a generalization of for loops) and descriptors (a generalization of customizable attributes). In this talk I will present the principles and some examples of these additions, and show how they are useful for lowly scripting tasks as well as for advanced class library authors. I encourage audience participation and will be available for questions afterwards. For driving directions to Carnegie, as well as information about BayPIGgies, please visit: http://www.baypiggies.net From newsgroups at jhrothjr.com Sat Nov 1 20:48:29 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 1 Nov 2003 20:48:29 -0500 Subject: operator.isMappingType References: Message-ID: "Raymond Hettinger" wrote in message news:vgYob.46447$4O1.17443 at nwrdny01.gnilink.net... > Since the advent of extended slicing, operator.isMappingType() returns a > misleading result. > > >>> map(operator.isMappingType, ([], (), {}, '', u'')) > [True, True, True, True, True] > > > I recommend removing it from the operator module. I get the following on 2.2.3: >>> map (operator.isMappingType,([], {}, (), ", u")) [0, 1, 0, 0] Where did the fifth True come from? That's really odd! How much code would removing it break, versus changing the test so it looked for one or more of the methods that's unique to maps, and not to other kinds of sequences? Granted, testing for something other than a magic method would slow it down, but that should be better than either leaving it broken, or breaking otherwise innocent code. John Roth > > > Raymond Hettinger > > From gerrit at nl.linux.org Thu Nov 13 15:09:44 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 13 Nov 2003 21:09:44 +0100 Subject: [OT] Re: guten tag In-Reply-To: <3FB23136.1010702@ghaering.de> References: <3FB23136.1010702@ghaering.de> Message-ID: <20031113200944.GD5646@nl.linux.org> Gerhard H?ring wrote: > Necati Agirbas wrote: > >Betreff: SCHULBESCHEINGUNG F?r Frau DERYA AGIRBAS, [...] > > Sie haben das wohl an die falsche Adresse geschickt > (python-list at python.org), anstatt an die Adresse der Schule. Und Sie haben diese bericht auch an die falsche Adresse geschickt, anstatt and ie Adresse der Necati Agirbas. And you have also send the message to the wrong address, instead of the address of Necatie Agirbas. En u heeft het bericht ook aan het verkeerde adres gestuurd, in plaats van het adres van Necati Agirbas. Et la destination de votre curriel etait mauvais aussi, la destination correcte etwait Necati Agirbas. Av dig har... Let's stick to English ;) Gerrit. -- 103. If, while on the journey, an enemy take away from him anything that he had, the broker shall swear by God and be free of obligation. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From see_signature__ at hotmail.com Sun Nov 30 03:59:55 2003 From: see_signature__ at hotmail.com (Georgy Pruss) Date: Sun, 30 Nov 2003 08:59:55 GMT Subject: Bug in glob.glob for files w/o extentions in Windows References: <0Zfyb.48050$dl.2119318@twister.southeast.rr.com> Message-ID: "Jules Dubois" wrote in message news:b6xinmmkc0wp.16hmc77xoj9t2$.dlg at 40tude.net... | | We agree, then, that every operating system has its good points and its bad | points. (I guess we don't agree on whether "*." should or shouldn't match | files without periods in their name.) Anyway, "*." is not a bad DOS convention to select files w/o extention, although it comes from the old 8.3 name scheme. BTW, how can you select files w/o extention in Unix's shells? G-: From max at alcyone.com Fri Nov 21 02:09:50 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 20 Nov 2003 23:09:50 -0800 Subject: Exceptions, assigning a tuple References: <3fbdb857$0$1727$5a62ac22@freenews.iinet.net.au> Message-ID: <3FBDBA3E.23D54A7C@alcyone.com> Derek Fountain wrote: > What I don't understand is the assignment of a tuple in the except > clause. > The O'Reilly Nutshell book says "The optional target is an identifier > that > names a variable that Python binds to the exception object just before > the > exception handler executes". This doesn't make sense in this case: > > except IOError, (errno, strerror): > > The target is a tuple of 2 variable names so how can it bind "the > exception > object" to them? The documentation for try/except says that "the > exception's parameter is assigned to the target". So what, exactly, is > an > "exception's parameter"? This is just using tuple unpacking in assignment: >>> tup = 1, 2, 3 >>> x, y, z = tup >>> x 1 >>> y 2 >>> z 3 This syntax can be used anywhere an lvalue is allowed, which might include the "variable" of a for statement: >>> for x, y in [(1, 2), (3, 4), (5, 6)]: ... print x, y ... 1 2 3 4 5 6 and the "variable" in a try/except clause is just another example of this. The "exception's parameter" is a 2-tuple, consisting of the errno and the strerror. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ Yes I'm / Learning from falling down / Heavily -- Lamya From tzot at sil-tec.gr Thu Nov 6 11:28:28 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 06 Nov 2003 18:28:28 +0200 Subject: Please explain the meaning of 'stealing' a ref References: <7h3wuagiagy.fsf@pc150.maths.bris.ac.uk> <56gkqvcjhgvb6gn31v6458ghk95u6bn1er@4ax.com> Message-ID: My last post in this thread, since it --like Alex noticed too-- tends to move into 'off-topic' territory. On Thu, 06 Nov 2003 14:30:30 GMT, rumours say that Alex Martelli might have written: [snip: Alex ponders on whether the thread remains on topic (it merely does), then states that, as an author himself, has strong opinions on style, nuances, fine point of connotation etc] Point taken, and be sure that all my respect goes to acknowledged authors like yourself; after all, we don't discuss one of your books or your style here, but rather the python documentation and how it could be improved for newcomers --not that *I* *know* how to improve it. I only pointed parts that might be as unclear to others as to me. [snip: I suggesting a defining "owning a reference", Alex counter-proposing a variation to the current doc sentence about what a function that owns a reference has to do, I accidentally ignoring the counter proposal, summarising instead where in the docs the answers to my questions can be collected from] >So what about my proposed transliteration of "when X, Y" into "X >means Y"? This is similar to (e.g.) changing "when somebody owns >a property outright, they can sell it" to "owning a property >outright means you can sell it" -- essentially equivalent in normal >English usage, but perhaps more specific or clear to non-natives? I really have no preference between the two. I believe they carry the same amount of information. Sorry for not commenting upon your proposal. >>>> This text is obviously clear [snip: I acknowledge a fault on my part in keeping in mind the difference between owning an object and owning a reference, Alex re-states the fact that the documentation is clearest on this, I mistake at a point Alex's use of second person in his sentence as referring to me, and Alex explains that he used 'you' as a generic person (my comment: ? la 'on' in French) instead of me specifically.] Explanation and not justification: In English I have met more often the idiom 'one can only hope' than 'you can only hope' when speaking in general, so I perceived you meant me. After your clarification, I understand it's a null issue. [snip: discussion about the phrase 'Few functions steal references; the two notable exceptions are...'] Sorry for snipping all of your reply, but this should be kept short. Do you believe that the following: 'Few functions steal references; of these exceptions, the two notable are...' is more to the point of passing the message that the word 'exceptions' after the semicolon means a subset of the exceptions referenced before the semicolon? If you really believe this is a moot point, please, let's drop the subject without further discussion on this. I insist on my point for clarity, but I am not an expert, cause I am a self-taught English speaker (by listening to songs, watching cinema and TV, and practicing whenever I could with native speakers (mostly British, apart from two trips to the States)). I say to drop the subject if you disagree because, pragmatically speaking, your opinion counts more than mine, so let's keep our energies for more grave matters. [snip some more discussion about the 'exceptions' subject] >> If the python documentation had a terminology dictionary, how would >> 'stealing', 'borrowing' and 'owning' a reference be defined in a concise >> and absolutely clear way? I seem to not be able to write these >> definitions, although I would like to. > >The concept of "owning a reference" is the crucial one. "Stealing" >is just one way to permanently transfer ownership, "borrowing" means >no transfer of ownership takes place, and these meanings are so close >to those in everyday language that the "terminology dictionary" would >have few problems, I believe. > >So, focusing on ownership, and foregoing the concision that would >probably be required in a dictionary, we might say: > >""" >Ownership pertains to references, never to objects (objects are not >owned: they are always shared). "Owning a reference" means being >responsible for calling Py_DECREF on it when the reference is no >longer needed. Ownership can also be transferred, meaning that the >code that receives ownership of the reference then becomes >responsible for eventually decref'ing it when it's no longer needed. >""" > >plus, perhaps, pointers to the various appropriate sections in >the "extending and embedding" tutorial and API reference that deal >with this concept. Really, the true meaning of "reference >ownership" is _operational_ -- the "responsibility of eventually >decref'ing (unless the ownership is transferred)" _together_ with >the rules for how and when ownership (i.e. responsibility to >eventually decref) is transferred. There you go, back to your excellent ability to reply to answers in a way that seems definite. That's the Alex before the tiresome python-syntax-in-lisp thread :) The above text in triple-quotes, believe me, is what I sought since the start. Our discussion really helped me answer my questions before I read it clearly in your post; and I firmly believe that your triple-quoted text should be added to the documentation. I just submitted patch 837322 merging your words above into the documentation text --please revise. Thanks for your time. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From miika.keskinen at utu.fi Wed Nov 5 03:33:46 2003 From: miika.keskinen at utu.fi (Miika Keskinen) Date: Wed, 05 Nov 2003 10:33:46 +0200 Subject: XORing long strings opimization? References: Message-ID: On Tue, 04 Nov 2003 22:33:52 +0000, Noen wrote: >> alist = [chr(x ^ y) for x in ord1 for y in ord2] >> >> This creates a way too big list... Im not familiar with two for loops in >> one, so I cant see whats wrong :( >> > Oh, my debugger says that it works like: > for x in range ord1: > for y in range ord2: > chr(x^y) > which does it x*y times... > > wonder how the line really should look like... I've had similar needs and used following code: reduce(lambda x, y: x+y, map(chr, [ord(x)^ord(y) for x, y in zip("string1", "string2")])) dunno if this is optimal but it is anyways simple quick hack. If one is going to handle large amounts of data it should be done in parts to avoid memory issues. for some analysis zip will do O(n) in space and O(n) and O(n) in speed. ord(x) ^ ord(y) for x, y will do O(n) in space and O(n) in speed map chr will do O(n) in space and O(n) in speed lambda x, y: x+y will do O(n) in space and O(n) in speed. So my conclusion (correct me if I'm wrong) this method will run in O(n) space and O(n) time. -- Miika From A.Panayotopoulos at sms.ed.ac.uk Fri Nov 21 07:12:43 2003 From: A.Panayotopoulos at sms.ed.ac.uk (Alex Panayotopoulos) Date: Fri, 21 Nov 2003 12:12:43 +0000 Subject: Empty list as default parameter Message-ID: Hello all, Maybe I'm being foolish, but I just don't understand why the following code behaves as it does: - = - = - = - class listHolder: def __init__( self, myList=[] ): self.myList = myList def __repr__( self ): return str( self.myList ) # debug: 'a' should contain 42, 'b' should be empty. But no. a = listHolder() a.myList.append( 42 ) b = listHolder() print a print b - = - = - = - I was expecting to see [42] then [], but instead I see [42] then [42]. It seems that a and b share a reference to the same list object. Why? -- <<>> Defender of Spudkind From fredrik at pythonware.com Thu Nov 20 10:28:52 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Nov 2003 16:28:52 +0100 Subject: httplib and Proxy References: Message-ID: Rolf Wester wrote: > I want to fetch some web-pages via http. I know how to do this without a > proxy server in between but unfortunately we can only access the > internet via a proxy. I would be very appriciative if anybody could tell > me how to do this. use urllib, not httplib. >>> import os, urllib >>> os.environ["http_proxy"] = "http://proxyserver:3128" >>> data = urllib.urlopen("http://server/page").read() you can of course set the http_proxy environment variable before you start Python. on Windows, you can also use the standard "Internet Options" dialogue to configure the proxy. also see: http://www.python.org/doc/current/lib/module-urllib.html From fjh at cs.mu.oz.au Tue Nov 11 10:12:53 2003 From: fjh at cs.mu.oz.au (Fergus Henderson) Date: Tue, 11 Nov 2003 15:12:53 GMT Subject: Python from Wise Guy's Viewpoint References: <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <3F9D5D21.2060408@ps.uni-sb.de> <3fb097fe$1@news.unimelb.edu.au> <3fb0c2cd$1@news.unimelb.edu.au> Message-ID: <3fb0fc70$1@news.unimelb.edu.au> Pascal Costanza writes: >I am not sure if I understand you correctly, but are you actually >suggesting that it is better to reimplement Common Lisp on your own than >to just use one of the various Common Lisp implementations? No. I'm just pointing out that these sort of things can be implemented in statically typed languages without much difficulty. Generally I _don't_ want to reimplement Common Lisp. If on occaision I do need some dynamic binding, or dynamic typing, say, then this need is usually localized within a small part of the application, and so I can implement what I need very easily. Your article that I was responding to was suggesting that there might be some things which could not be done in statically typed languages, and in particular that this sort of eval(read()) loop might be one of them. As I hope I've demonstrated, it is not. So in answer to question "d" in that post of yours, "would you still disagree with the assessment there is a class of programs that can be implemented with dynamically typed languages but without statically typed ones?", I would say yes, I still disagree. -- Fergus Henderson | "I have always known that the pursuit The University of Melbourne | of excellence is a lethal habit" WWW: | -- the last words of T. S. Garp. From spam at spam.com Sat Nov 22 00:22:09 2003 From: spam at spam.com (Jim Westwood) Date: Fri, 21 Nov 2003 21:22:09 -0800 Subject: java applets in python Message-ID: Is it possible to write java applets in the python language. is that what jython does? I would realy like to write an applet but i dont know any java. I do have some python experience. Can you write the applets in pure python or do you have to know a little java? ifso is this done much? and is there any good documentation out there on how to do it thanks. From k at k.com Sun Nov 23 06:48:14 2003 From: k at k.com (kk) Date: Sun, 23 Nov 2003 19:48:14 +0800 Subject: Use of GPLed Python extension modules In-Reply-To: References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> Message-ID: kk wrote: > Paul Rubin wrote: > >>Tim Churches writes: >> >> >>>If a compiled Python extension module B includes code from some >>>other software A which is licensed only under the GPL, do other >>>Python programmes, C, which import module B also need to be licensed >>>under a GPL-compatible license (assuming C is/are to be distributed >>>to third parties)? >> >> >>It's not enough for B and C to be under "GPL-compatible licenses". >>They have to be under the actual GPL. >> >>From http://www.gnu.org/licenses/gpl-faq.html#LinkingWithGPL >> >> You have a GPL'ed program that I'd like to link with my code to build >> a proprietary program. Does the fact that I link with your program >> mean I have to GPL my program? >> >> Yes. > > AFAIK, ur python program, which is interpreted, is considered data in > view of the program interpreter. So the GPL license is not needed. > Correct me if I am wrong. > http://www.gnu.org/licenses/gpl-faq.html#IfInterpreterIsGPL If a programming language interpreter is released under the GPL, does that mean programs written to be interpreted by it must be under GPL-compatible licenses? When the interpreter just interprets a language, the answer is no. The interpreted program, to the interpreter, is just data; a free software license like the GPL, based on copyright law, cannot limit what data you use the interpreter on. You can run it on any data (interpreted program), any way you like, and there are no requirements about licensing that data to anyone. However, when the interpreter is extended to provide "bindings" to other facilities (often, but not necessarily, libraries), the interpreted program is effectively linked to the facilities it uses through these bindings. So if these facilities are released under the GPL, the interpreted program that uses them must be released in a GPL-compatible way. The JNI or Java Native Interface is an example of such a facility; libraries that are accessed in this way are linked dynamically with the Java programs that call them. Another similar and very common case is to provide libraries with the interpreter which are themselves interpreted. For instance, Perl comes with many Perl modules, and a Java implementation comes with many Java classes. These libraries and the programs that call them are always dynamically linked together. A consequence is that if you choose to use GPL'd Perl modules or Java classes in your program, you must release the program in a GPL-compatible way, regardless of the license used in the Perl or Java interpreter that the combined Perl or Java program will run on. From newsgroups at jhrothjr.com Sun Nov 2 07:37:33 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 2 Nov 2003 07:37:33 -0500 Subject: None References: Message-ID: "Daniel Sch?le" wrote in message news:bo2t4k$p3f$1 at news.rz.uni-karlsruhe.de... > Hi NG > > > > def executer(func, para): > func(para) > > def foo(): > print "function without parameter" > > def bar(a): > print "function with 1 parameter" > print a > > #executer(foo, None) #error > > executer(bar, 100) > > print type(foo) > print type(bar) > #seem to have the same type, though one takes parameter and the other doesnt > > > does this mean that None *is* a value > some special value to show that variable cant be initialized with more > appreciate value at this stage? None is an object like any other object in Python. It's conventional uses are as a return value from functions that don't return a value, and as an initial value for optional function parameters. These are conventional; they are not mandated by the language (except that the return statement without parameters does return None.) > > is there a way to allow parameterless functions as parameter in executer? I'm not sure what you mean by this question. Functions are first class objects, so you can, of course, pass them to other functions. There are numerous examples in the standard library of methods which take functions as a parameter. Look at, for example, the map(), reduce() and filter() built-in functions, and also at the .sort() method of lists. John Roth > > -- > Daniel > > From max at ucmg.com.ua.remove.it Mon Nov 3 06:16:28 2003 From: max at ucmg.com.ua.remove.it (Max Ischenko) Date: Mon, 03 Nov 2003 13:16:28 +0200 Subject: PYTHONPATH is ignored by win32all? Message-ID: Hi, I'm writing a COM server in python which relies upon another python module whose location is in PYTHONPATH env. variable. The problem is that I got ImportError for that module -- seems like win32all doesn't use PYTHONPATH. I currently added sys.path.append to my COM server module but I don't like this hack. Anyone knows how to solve this properly? From bokr at oz.net Fri Nov 14 14:47:57 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Nov 2003 19:47:57 GMT Subject: Making a maze.... References: <1PSsb.44675$jy.34613@clgrps13> Message-ID: On Thu, 13 Nov 2003 21:35:57 GMT, "Bernard Fields" wrote: >Greets, all. > > >As the title suggests, I'm trying to make a maze. Specifically, it's a >top-down, 2-d maze, preferably randomly generated, though I'm willing to >forego that particular aspect as this point. > I'm not sure what you mean by 'top-down.' Also, do you just want to show (print and/or display) a maze, or do you want a representation that you can "walk" through with a program? >I've done many, many web-searches, but nothing that I've found so far has >provided any clues.... > It should not be that hard, but do you have any constraints on loops, islands, where entry and exit are supposed to be, dimensions, connectivity (e.g. square cells vs rooms and corridors of arbitrary shape, etc.)? Regards, Bengt Richter From giles_brown at hotmail.com Sun Nov 2 06:28:47 2003 From: giles_brown at hotmail.com (Giles Brown) Date: 2 Nov 2003 03:28:47 -0800 Subject: Py2exe error messages References: Message-ID: <57de9986.0311020328.477086b7@posting.google.com> "Ray" wrote in message news:... > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > C:\Python22>python setup.py py2exe --icon EXE icon > Traceback (most recent call last): > File "setup.py", line 7, in ? > scripts = ["wxApp1.py"], > File "C:\Python22\distutils\core.py", line 101, in setup > _setup_distribution = dist = klass(attrs) > File "C:\Python22\distutils\dist.py", line 130, in __init__ > setattr(self, method_name, getattr(self.metadata, method_name)) > AttributeError: DistributionMetadata instance has no attribute > 'get___doc__' > > This is the error message I'm getting when I try to run Hmmm. Have you taken a good look at the distutils/dist.py code? On my 2.2.2 installation the nearest match (which strangely isn't line exactly on line 130) is this chunk of code: """ # Store the distribution meta-data (name, version, author, and so # forth) in a separate object -- we're getting to have enough # information here (and enough command-line options) that it's # worth it. Also delegate 'get_XXX()' methods to the 'metadata' # object in a sneaky and underhanded (but efficient!) way. self.metadata = DistributionMetadata() for basename in self.metadata._METHOD_BASENAMES: method_name = "get_" + basename setattr(self, method_name, getattr(self.metadata, method_name)) """ Don't know if I'm teach grandma to suck eggs here, but this code it constructing a metadata sub-object and "stealing" certain "get" functions from it to pass off as its own. The list of attributes that it is prepared to get is taken from Distribution._METHOD_BASENAMES (in the same file). Looking at the version of this from my installation I see: ''' class DistributionMetadata: """Dummy class to hold the distribution meta-data: name, version, author, and so forth. """ _METHOD_BASENAMES = ("name", "version", "author", "author_email", "maintainer", "maintainer_email", "url", "license", "description", "long_description", "keywords", "platforms", "fullname", "contact", "contact_email", "licence") ''' This leads to the question where is the loop in the extract above getting the "__doc__" from that is using to build the method name? You may want to inspect your the distutils code in your python installation (and maybe put a few print statements into it) to investigate. Hope this helps. Regards, Giles From ulysses_dm at yahoo.com.cn Thu Nov 20 22:35:21 2003 From: ulysses_dm at yahoo.com.cn (ulysses) Date: 20 Nov 2003 19:35:21 -0800 Subject: gettext crazy question Message-ID: <43e3984e.0311201935.64aac584@posting.google.com> hi, I want to translate my app to Chinese use gettext module in python22,wxpython. I have get pot file, use msgfmt convert to mo file. But if I type some line character , app can't load MO file. trans = gettext.GNUTranslations(open('en.mo')) raise a error , error message is "unpack str size does not match format" exp: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ "Project-Id-Version: PACKAGE VERSION\n" "POT-Creation-Date: Mon Aug 25 16:40:30 2003\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=iso-8859-1\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: pygettext.py 1.5\n" #: AboutForm.py:56 msgid "Author" msgstr "chinese character" #: AboutForm.py:62 msgid "Donate To" msgstr "" #: AboutForm.py:70 msgid "Close" msgstr "chinese character" If i don't fill 62 , app is ok. So I debug gettext module. I find following interest question. -=gettext line 154=- buf = fp.read() I sure fp(file object) has open. It can't read all binary code. buf 's lengh smaller than real file. exp ,whole file 1000 byte. gettext only read 187 . So raise unpack error at gettext line 167 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ tlen, toff = unpack(ii, buf[transidx:transidx+8]) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Because request transidx doesn't exit. then I remove 62 line ,left empty. App can work. I open the mo file by ultraedit and compare the different . I notice the read function broken position bytecode is 0x1A but good mo same position is 0x0A. so I change the bad mo to 0A. It's work. It's really crazy .I don't know where and why I get failure. If you help us explain the puzzle I very appreciate. Ulysses From Ian.Sparks at etrials.com Fri Nov 21 09:06:18 2003 From: Ian.Sparks at etrials.com (Ian Sparks) Date: Fri, 21 Nov 2003 09:06:18 -0500 Subject: Passing source code to __init__ to override method dynamically(Table driven subclassing) Message-ID: <41A1CBC76FDECC42B67946519C6677A9A20CE6@pippin.int.etrials.com> >>From: Pettersen, Bjorn S [mailto:BjornPettersen at fairisaac.com]> >>At this point stop and ask yourself why: >> >> - being table driven is a good thing? >> - having a common base class is useful? Thanks Bjorn, The rational is that the application I have in mind allows (experienced, trusted) end-users to store "decision making" code in a database table. This can be as simple as "if self.somevalue < self.someothervalue then PASS else FAIL." There really is no need for those end-users to have to add all the template code to make a valid subclass. I want to override a method in order to get access to the "self" namespace which provides access to everything in the environment needed to make these "decisions" and to process a PASS or FAIL. Perhaps my efforts *are* misguided in which case I'd appreciate any advice you can give. Finally, thanks for the tip but I'm having trouble taking a function created : import new code = """ ... """ x = new.function(compile(code,"",'exec'), globals()) and adding it as a method to my existing class as a replacement to my existing function. I'll keep experimenting. - Ian -----Original Message----- From: Pettersen, Bjorn S [mailto:BjornPettersen at fairisaac.com] Sent: Thursday, November 20, 2003 8:10 PM To: Ian Sparks; python-list at python.org Subject: RE: Passing source code to __init__ to override method dynamically(Table driven subclassing) > From: Ian Sparks [mailto:Ian.Sparks at etrials.com] > > I want to create specialized instances of a base class > without declaring descendant classes. > > Instead, I want to do the specialization by passing > source-code to the constructor of the base-class. This way I > can make my program table-driven. At this point stop and ask yourself why: - being table driven is a good thing? - having a common base class is useful? > Here's my working (but sucky) code : [..] # I belive this is equivalent (untested). import new code = """ ... """ x = new.function(compile(code,"",'exec'), globals()) > Any advice? You're being too clever... or not clever enough . I have a feeling you might be looking for the new import machinery... -- bjorn Designing your classes AS CLASSES rather than as bunches of vaguely related snippets of source would undoubtedly be a far better way to proceed. -- Alex Martelli From tzot at sil-tec.gr Thu Nov 6 08:10:49 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 06 Nov 2003 15:10:49 +0200 Subject: Please explain the meaning of 'stealing' a ref References: <7h3wuagiagy.fsf@pc150.maths.bris.ac.uk> Message-ID: <56gkqvcjhgvb6gn31v6458ghk95u6bn1er@4ax.com> On Wed, 05 Nov 2003 20:24:39 GMT, rumours say that Alex Martelli might have written: >> The missing part IMO is what "owning a reference" means. I understand > >Hmmm... what if the text was transliterated into "Owning a reference >means you have to dispose of it properly" from the current "When a >function owns a reference, it has to dispose of it properly"? The current >expression and my suggested rewording are meant to convey just the >same meaning, but perhaps the rewording is more immediately obvious >to some non-native speakers of English (I'm a non-native speaker myself, >but sometimes I have trouble gauging what problems others may have). For other people (if any) that have similar to my questions, all the information about 'owning', 'borrowing' and 'stealing' references is in the sections 1.2.1-1.2.2 of the "Python/C API reference", but first have a good grasp of the tutorial "Extending and Embedding the Python interpreter", subsections 1.10.1-1.10.4 . >> This text is obviously clear, and the misconception was my fault: since >> references are just pointer variables at the C level, and I never had a >> concept of a function (or a program) 'owning' its variables, >> automatically my brain converted the word 'reference' to 'reference to >> python object' to 'python object'. That's it. > >Ah. So there may be no fix for this -- we can't get any more explicit, >but if your brain converts this to "we talk of owning python objects, >never of owning objects" there's really nothing we can do:-(. You use present tense for 'converts' above, but I assume you meant to use past tense, since this is what I did in the previous paragraph. Unusual of you to miss details. Like I said, the text is clear; it needs no fix in the case of owning references|objects. >> The word "exceptions" implies "exception to the previous statement". > >Yes, to the statement terminated by the semicolon - the one saying that few >functions steal references. > >> IIUC "exceptions" should be changed to "examples". > >Yes, this is surely a reasonable change, if it clarifies the text for some >readers. Since you agree (and make more specific) that 'exceptions' means 'exception to the statement terminated by the semicolon', and since neither PyList_SetItem nor PyTuple_SetItem are exceptions to the few functions that steal references, doesn't that make the choice of the word 'exceptions' unreasonable (as in exactly the opposite of what was meant)? It's not a matter of simple clarification. Either the word 'exceptions' should be changed, or it should be changed to 'notable exceptions to ' The previous two paragraphs were written only because your 'if it clarifies the text for some readers' seems to ignore the fact you yourself stated two paragraphs above in 'Yes, to the statement...' >> Also, it would be helpful if (possibly as footnotes too) there was the >> following definition: >> "stealing a reference": a function that steals a reference takes away >> from the caller the responsibility of calling Py_DECREF on the >> referenced object. >> >> If all of the above seem redundant to you, then perhaps it would make > >Yes, totally -- and incomplete, because it doesn't really capture the >_concept_ of ownership. E.g., if the called didn't own the reference >but borrowed it, then to pass it to a function that steals it, the caller >must Py_INCREF it -- now the "takes away the responsibility" can >be considered a very misleading statement. Yes, your example is a good one -as usual for a bot :)- to make my suggestion lacking. If the python documentation had a terminology dictionary, how would 'stealing', 'borrowing' and 'owning' a reference be defined in a concise and absolutely clear way? I seem to not be able to write these definitions, although I would like to. Anyway, given time and inspiration, sf.net is just a few blocks down the street :) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From golux at comcast.net Wed Nov 5 12:18:26 2003 From: golux at comcast.net (Stephen C. Waterbury) Date: Wed, 05 Nov 2003 12:18:26 -0500 Subject: reduce() anomaly? Message-ID: <3FA930E2.6080203@comcast.net> This seems like it ought to work, according to the description of reduce(), but it doesn't. Is this a bug, or am I missing something? Python 2.3.2 (#1, Oct 20 2003, 01:04:35) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> d1 = {'a':1} >>> d2 = {'b':2} >>> d3 = {'c':3} >>> l = [d1, d2, d3] >>> d4 = reduce(lambda x, y: x.update(y), l) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in AttributeError: 'NoneType' object has no attribute 'update' >>> d4 = reduce(lambda x, y: x.update(y), l, {}) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in AttributeError: 'NoneType' object has no attribute 'update' - Steve. From sandorlevi at yahoo.com Sun Nov 23 20:38:20 2003 From: sandorlevi at yahoo.com (Levente Sandor) Date: 23 Nov 2003 17:38:20 -0800 Subject: minidom nodes without a document? References: Message-ID: <8b5e42a6.0311231738.6376d486@posting.google.com> mlh at furu.idi.ntnu.no (Magnus Lie Hetland) wrote in message news:... > Is it possible to build a minidom tree bottom-up without access to a > document node? It seems that simply instantiating the various node > classes doesn't quite do the trick... I'm not sure what you mean exactly by "without access to...". You need a Document instance to create the elements, but they aren't added automatically to it. >>> import xml.dom.minidom >>> doc = xml.dom.minidom.Document() >>> foo = doc.createElement('foo') >>> for i in range(3): ... foo.appendChild(doc.createElement('bar')) ... >>> doc.toxml() '\n' >>> foo.toxml() '' >>> ---- levi From dave at pythonapocrypha.com Tue Nov 18 12:03:28 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 18 Nov 2003 10:03:28 -0700 Subject: Detecting Browsers in Python References: <77dd287a.0311180813.5405af98@posting.google.com> Message-ID: <02bb01c3adf5$efb0ccc0$6400000a@YODA> > Does anyone know of a simple way to have a Python script find out what > browser is accessing it? After a web search the only thing I found to > do this is Zope, but the system I'm programming doesn't use Zope and > I'm not really interested in installing it just for this minor detail. > Is there another way? (I assume you mean that the script the browser is accessing is a CGI script) Most browsers include a "User-Agent" in the HTTP request they make to a server. Users can override these, but few people do, so you can semi-reliably detect the browser that way. I sometimes need to make sure a browser is running on "new enough" Windows, so I use this: ua = ua.lower() if ua.find('win') != -1 and ua.find('win16') == -1 and \ ua.find('windows nt 4') == -1 and ua.find('winnt4') == -1: # platform is Windows else: # non-Windows or old Windows As for browser vendor, this is the pseudocode I use: if ua.find('opera') != -1: # opera elif ua.find('gecko') != -1: # gecko (moz/ns) elif ua.find('msie') != -1: # Most likely really is IE else: # somebody else This works for what I need because usually I'm just trying to acertain if the browser is IE on a newer Windows box, but you may need additional checks (Google can turn up huge lists of all known default User-Agent strings so it's fairly easy to come up with a good test suite). -Dave From Raaijmakers, Vincent (IndSys, Mon Nov 10 13:56:46 2003 From: Raaijmakers, Vincent (IndSys, (Raaijmakers, Vincent (IndSys,) Date: Mon, 10 Nov 2003 12:56:46 -0600 Subject: web guru advise needed. Message-ID: <971323274247EB44B9A01D0A3B424C850304C77A@FTWMLVEM02.e2k.ad.ge.com> Agreed 100%. Apache shouldn't be in the requirements. Let me rephrase the question a bit. Preparing for an unknown high load in the future, what are the 'don't even think about these options' web solutions. If Apache is one of these, fine, please let me know but give me please the best alternative. Without testing, what are the boundaries of Apache? I don't know. Apache (Tomcat) was chosen because some JSP stuff was already written. Doesn't mean that we can't change that, this is still an early stage of development. Of course, most of the java developers won't be happy hearing this. Vincent -----Original Message----- From: Cameron Laird [mailto:claird at lairds.com] Sent: Monday, November 10, 2003 1:42 PM To: Raaijmakers, Vincent (IndSys, GE Interlogix) Subject: Re: web guru advise needed. In article , Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: . . . >The web server requirements I'm looking at are: > >1) simple presentation layer processing. The HTML pages produced by >server will be more focused on presenting images (dynamic), rather that >fancy tables, frames, buttons. >2) the framework has to be robust and FAST on performance. >3) runs only on Linux, well not really a requirement, more a statement. >4) runs on Apache (and/or Tomcat) > >What technology gives me the best performance? . . . I hope I've misunderstood your intent. When I first read this, the impression it makes is that you have an interest only in the one Apache-based Web server with "the best performance". For practical use, I think a far more satisfying approach is to look for a system which is robust, high in performance, and maintain- able, and *measure* its performance in a test environment to estimate whether it is fast enough. "Fast enough" can be a considerably more useful criterion than "fastest possible". -- Cameron Laird Business: http://www.Phaseit.net From __peter__ at web.de Mon Nov 24 05:48:06 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Nov 2003 11:48:06 +0100 Subject: string similarity in python References: Message-ID: Achim Domma wrote: > I have a list of lets say 100-1000 strings and want to know which one is > most similar to a reference string. Does somebody know such a library for > Python? I don't need complicated scientific stuff, I think the most simple > ones will do it for my data. Remembering an algorithm called Levenshtein, google came up with something that looks promising. http://trific.ath.cx/resources/python/levenshtein/ HTH, Peter From for_usenet2000 at yahoo.de Sat Nov 1 16:00:29 2003 From: for_usenet2000 at yahoo.de (Daniel Schüle) Date: Sat, 1 Nov 2003 22:00:29 +0100 Subject: None Message-ID: Hi NG def executer(func, para): func(para) def foo(): print "function without parameter" def bar(a): print "function with 1 parameter" print a #executer(foo, None) #error executer(bar, 100) print type(foo) print type(bar) #seem to have the same type, though one takes parameter and the other doesnt does this mean that None *is* a value some special value to show that variable cant be initialized with more appreciate value at this stage? is there a way to allow parameterless functions as parameter in executer? -- Daniel From huzzah at tampabay.rr.com Sat Nov 1 20:17:35 2003 From: huzzah at tampabay.rr.com (Todd Stephens) Date: Sun, 02 Nov 2003 01:17:35 GMT Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0310312008.ce341ea@posting.google.com> <87r80sdyb1.fsf@pobox.com> <7xn0bg6njb.fsf@ruckus.brouhaha.com> <7x7k2jpti9.fsf@ruckus.brouhaha.com> <7x7k2jboy9.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 01 Nov 2003 19:21:02 -0500, Paul Rubin wrote: > Why side with the company if it's not paying its programmers? The > business model was charge for the software and use some of the cash to > pay the programmers. If the programmers aren't getting paid, the > correct pro-consumer sentiment is to call for the software to be > released for free. Well, we don't *know* the facts for sure. The OP is obviously a former employee of the company, and his credibility is shadowed -whether justly or not- by being disgruntled. I say he is disgruntled because someone with no bone to pick would not have gone around posting as he did. And his assertion that Rekall is not available from theKompany is incorrect as I went to their site today and it is indeed for sale there. But, I again have to ask how this is related to the Python language? -- Todd Stephens From newsgroups at jhrothjr.com Tue Nov 11 14:03:38 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 11 Nov 2003 14:03:38 -0500 Subject: Python's simplicity philosophy References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: "David Eppstein" wrote in message news:eppstein-1FB54D.10202111112003 at news.service.uci.edu... > In article , > Douglas Alan wrote: > > > "Dave Brueck" writes: > > > > > Part of the problem here is that just saying "only one way to do it" is a > > > horrible misquote, and one that unfortunately misses IMO some of the most > > > important parts of that "mantra": > > > > Well, perhaps anything like "only one way to do it" should be removed > > from the mantra altogether, since people keep misquoting it in order > > to support their position of removing beautiful features like reduce() > > from the language. > > I think the more relevant parts of the zen are: > Readability counts. > Although practicality beats purity. > > The argument is that reduce is usually harder to read than the loops it > replaces, and that practical examples of it other than sum are sparse > enough that it is not worth keeping it just for the sake of > functional-language purity. IMO, this arguement is basically religious, that is, it is not based on common sense. Apply, lambda, map, filter and reduce never constituted a complete set of functional programming constructs, so trying to make them so for the sake of the arguement is, basically, silly. Apply was absorbed into the language core with a small change in function call specifications. Good idea - it gets rid of a built-in function. Map and filter were (almost) obsoleted by list comprehensions and the zip built-in function. Whether or not list comprehensions are clearer than map and filter is debatable, but the only thing we lost in the transition was map's capability of processing lists of different lengths. Sum is not an adequate replacement for reduce, regardless of the performance benefits. Something similar to a list comprehension would be. I don't, at this point, have a good syntax to suggest though. A not so good example would be: numbers = [1, 2, 3, 4] result = [x: x + i for i in numbers] The ":" signals that the result is a single object, not a list of objects. The first list element is bound to that label, and then the expression is evaluated for the rest of the elements of the list(s). The problem with the syntax is the brackets, which suggest that the result should be a list. John Roth > -- > David Eppstein http://www.ics.uci.edu/~eppstein/ > Univ. of California, Irvine, School of Information & Computer Science From peter at engcorp.com Wed Nov 19 11:52:41 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 19 Nov 2003 11:52:41 -0500 Subject: GIL risky for threading and networking? (was Re: good book on multithreaded programming with Python) References: Message-ID: <3FBB9FD9.62D62FD@engcorp.com> Nick Vargish wrote: > > A book that covers all the above options would really help me figure > out the optimal approach to this project. I'm especially concerned > that the GIL will make a pure-Python approach risky, since this > application involves a fair abount of network data and real-time data > processing. What risk concerns you with respect to doing networking and "real-time" processing using Python, given that the GIL exists? Would you have the same concerns if you didn't even know of the existence of the GIL? (I believe you should have those concerns, but just because you're trying to use an unfamiliar environment for something fairly intensive, not because it's Python specifically, or the GIL.) I do lots of "network data and real-time data processing" using Python and have not encountered any particular difficulties, and certainly none that can be attributed to the existence of the GIL. Is this a case of fear arising out of ignorance? If so, why not just write a quick test/experiment that will remove or affirm your concern? It would be trivial to write a program that created a dozen threads, each doing processing that would take five seconds of dedicated CPU time, and a network thread which grabs data from an external source as it becomes available, at whatever rate you need. You'll likely find out that with an adequate CPU, everything will work just as you need it to, and that the only difference between the old program and the new is that the Python-based one consumes a lot more CPU time for the same data... If you have specific reasons for the concern, please provide them so we can address them. The GIL certainly doesn't get in the way of soft real-time work in any way that's significant. -Peter From s-rube at uselessbastard.net Tue Nov 18 11:55:03 2003 From: s-rube at uselessbastard.net (Eric Williams) Date: Tue, 18 Nov 2003 17:55:03 +0100 Subject: Updating PyQt widgets question Message-ID: Hello all, I'm working on a little application using PyQt. The main window is just a dialog with 2 progress bars and a few labels. In its original form, the dialog started, then ran a function which downloaded a directory full of files from an ftp server, using an ftplib.FTP object's retrbinary function. http://xoffender.de/Downloads/screenie4.png Now, inside the callback function of the retrbinary call, I was calling the progress bars' setProgress function, and the labels' setText functions. What happened was, the progress bars got updated, albeit sporadically, but the labels didn't. They only changed once the function was completed. I've changed this now so that the download process runs in a thread, and I use a self.startTimer(50) call with a timerEvent function that updates the progress bars and labels by reading variables out of the thread. This works perfectly, as far as I can tell, but I still have 2 questions: - Is the above result (with the non-updating labels) the expected behavior, or did I do something wrong? - Is the thread/timer combination the 'correct' way to do it? I also tried connecting emit() signals within the thread to updating slot() functions in the dialog, which worked but seemed a little chaotic. Thanks! Eric -- --- s- should be removed to contact me... From jzgoda at gazeta.usun.pl Mon Nov 24 17:51:14 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 24 Nov 2003 22:51:14 +0000 (UTC) Subject: wxPython i18n question References: Message-ID: Logan pisze: > Is it possible to tell the wxPython widgets (e.g. file dialogs) > to use another language (instead of English)? Yes, look at article on i18n at wxPython Wiki. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From pmetzger at bellsouth.net Sat Nov 22 02:26:44 2003 From: pmetzger at bellsouth.net (Paul Metzger) Date: Sat, 22 Nov 2003 01:26:44 -0600 Subject: Frustration with Boa Constructor In-Reply-To: <153fa67.0311212057.108a1119@posting.google.com> Message-ID: <000301c3b0c9$fe7b89d0$6588a8c0@serendipity> > I am attempting to learn how to use wxPython from their mailing list, > from the demos that come with the package, and from the Wiki > (http://wiki.wxpython.org/index.cgi/FrontPage). However, expect to > have to do a lot of cross-referencing, as I couldn't find anything > that could stand alone as a comprehensive guide. > If you ever find a good source for documentation on wxPython, please tell me. The only thing I can find worth anything is the one chapter in Python 2.1 bible. It's a good basic, beginning, but leaves off where I need something to start. So the way I have to attack it is trial and error until I get it figured out... Paul From exarkun at intarweb.us Wed Nov 5 18:25:28 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Wed, 5 Nov 2003 18:25:28 -0500 Subject: prePEP: Decimal data type In-Reply-To: References: Message-ID: <20031105232528.GA22022@intarweb.us> On Wed, Nov 05, 2003 at 01:55:09PM -0500, Aahz wrote: > In article , > Emile van Sebille wrote: > > > >The Context still needs to be defined, but Aahz says: > >> Context applies only to operations, not to Decimal instances; > >> changing the Context does not affect existing instances if > >> there are no operations on them. > > > >...from which I infer that Context exists in part to limit/round > >calculated results. Even if it were possible for me, as a user of > >Decimal, to set Context appropriately to achieve these ends, what > >if I use a library that also changes Context? The integrity of my > >calculations may be impacted. > > That's correct. There needs to be a social convention that libraries > intended for use by other people *CANNOT* muck with Context, and if they > do so for their own internal calculations, they must save and restore > Context. You can probably find additional information about this in > Cowlishaw. Enter the context stack. Jp From huaiyu at gauss.almaden.ibm.com Tue Nov 4 22:01:08 2003 From: huaiyu at gauss.almaden.ibm.com (Huaiyu Zhu) Date: Wed, 5 Nov 2003 03:01:08 +0000 (UTC) Subject: replacement of rexec? References: <8cf2994e.0310231033.6a01871a@posting.google.com> <698f09f8.0310301113.356fd637@posting.google.com> Message-ID: In article <698f09f8.0310301113.356fd637 at posting.google.com>, Jeremy Fincher wrote: > Skip Montanaro wrote in message news:... >> I'm not aware of anything. Assuming your inspection process shows the file >> is okay, why not just call execfile()? > > > Probably because that won't get him a useful value :) He'd have to > use eval (but you probably knew that and just typo'ed execfile; I'm > mostly just saying it to try and prevent confusion on his part). That's the point - the file contains multiple strings to be converted to python objects. I've written the following code over the weekend. It is more complicated than I'd like. Hopefully someone can replace part or all of it by some builtin functionality. #------------------------------------------------------- import compiler def safe_eval(s): """ Evaluate strings that only contains the following structures: const, tuple, list, dict """ stmts = compiler.parse(s).node.nodes #print stmts assert len(stmts) == 1 node = compiler.parse(s).node.nodes[0] assert node.__class__ == compiler.ast.Discard nodes = node.getChildNodes() assert len(nodes) == 1 return safe_assemble(nodes[0]) seq_types = { compiler.ast.Tuple: tuple, compiler.ast.List: list, } map_types = { compiler.ast.Dict: dict, } def safe_assemble(node): """ Recursively assemble parsed ast node """ cls = node.__class__ if cls == compiler.ast.Const: return node.value elif cls in seq_types: nodes = node.nodes args = map(safe_assemble, nodes) return seq_types[cls](args) elif cls in map_types: keys, values = zip(*node.items) keys = map(safe_assemble, keys) values = map(safe_assemble, values) return map_types[cls](zip(keys, values)) else: raise "Type not allowed", cls if __name__ == '__main__': tests = [ "3j", "1, 2.5", "['abc', 0xF7]", "1, ['abc', [2,3]], {(4,5):[6.5, 8]}", ] for s in tests: print safe_eval(s) #------------------------------------------------------- Huaiyu From codeapocalypse at msn.com Mon Nov 3 16:21:56 2003 From: codeapocalypse at msn.com (Brian) Date: 3 Nov 2003 13:21:56 -0800 Subject: PyQt, Qt, Windows and Linux References: Message-ID: Alex Martelli wrote in message news:Vamsi Mudrageda wrote: >> 2) Do I need to buy a license from TrollTech? > > Yes, or from one of Trolltech's licensed resellers of licenses. The > cheapest way you can proceed, I believe, is to buy Blackadder, personal > edition, from theKompany.com: it comes with personal-use licenses of > PyQt and Qt for both Linux and Windows (I _think_ mac, too, but I don't > know about that). I believe it currently costs US $70 . Note that according to the BlackAdder page at thecompany.com, you must purchase the business edition ($400, currently) if you want the right to distribute the run-time elements of it. I'm not sure if the OP only wanted to distribute an app for use on his own windows box, or distribute his application on the net for use by others. Trolltech's pricing strategy, for me, keeps me on wxWindows. Qt does seem like an excellent product, however. From sunking77 at hotmail.com Sat Nov 1 23:26:40 2003 From: sunking77 at hotmail.com (Ray) Date: Sat, 1 Nov 2003 20:26:40 -0800 Subject: Py2exe on windows Message-ID: <000001c3a0f9$83652290$041ad20c@computer> I'm using Win XP with Python2.2 and PY2exe0.4.2 python and py2exe i downloaded from their websites. The following is a copy of my cmd.exe shell showing what i type in and the error messages. C:\Python22>python setup.py py2exe --ico EXE icon Traceback (most recent call last): File "setup.py", line 7, in ? scripts = ["wxApp1.py"], File "C:\Python22\distutils\core.py", line 101, in setup _setup_distribution = dist = klass(attrs) File "C:\Python22\distutils\dist.py", line 130, in __init__ setattr(self, method_name, getattr(self.metadata, method_name)) AttributeError: DistributionMetadata instance has no attribute 'get___doc__' C:\Python22> From nessus at mit.edu Fri Nov 7 15:52:27 2003 From: nessus at mit.edu (Douglas Alan) Date: Fri, 07 Nov 2003 15:52:27 -0500 Subject: Tkinter, resizing, and widget clipping Message-ID: Is there a way to tell Tkinter that I'd like to allow a window to be resizable, but only down to the point where no widget clipping occurs? I know that to get the effect I want, I can always (1) draw the window without any geometry setting, (2) fetch the geometry of the drawn window, (3) set the minimum window size to be this size, and then (4) reset the geometry of the window to be the size that I'd really like the window to start off as. It seem to me, though, that is something of a slow and gross hack. |>oug From http Wed Nov 5 11:59:18 2003 From: http (Paul Rubin) Date: 05 Nov 2003 08:59:18 -0800 Subject: (htmllib) How to capture text that includes tags? References: Message-ID: <7xad7arbtl.fsf@ruckus.brouhaha.com> I've generally found that trying to parse the whole page with regexps isn't appropriate. Here's a class that I use sometimes. Basically you do something like b = buf(urllib.urlopen(url).read()) and then search around for patterns you expect to find in the page: b.search("name of the product") b.rsearch(' References: <3fa3fab9$0$58702$e4fe514c@news.xs4all.nl> <3FA4284A.6010701@zg.htnet.hr> <3fa4395a$0$58698$e4fe514c@news.xs4all.nl> <3FA4CB41.8080306@zg.htnet.hr> <3FA548D2.6080900@zg.htnet.hr> Message-ID: <3fa54ada$0$58712$e4fe514c@news.xs4all.nl> Haris Bogdanovic wrote: > It works for me fine too, when client and server execute on the same > computer (mine) but I get "access denied" error when I put server.py on > my free telnet account ("m-net.arbornet.org"). > Is that the place where I should put server.py if I want to implement > chess server or is there some other common place where servers are put ? It looks to me that you are behind a firewall on your 'telnet account', i.e. you cannot access the necessary socket port(s). Usually only a few sockets are 'open' to the outside world. Try setting up your server to use one of these 'open' sockets or change the firewall configuration. --Irmen From bokr at oz.net Mon Nov 3 22:56:03 2003 From: bokr at oz.net (Bengt Richter) Date: 4 Nov 2003 03:56:03 GMT Subject: Selling Python Software References: <8765i1d2jb.fsf@pobox.com> Message-ID: On Mon, 03 Nov 2003 13:54:52 GMT, Alex Martelli wrote: [...] >It's not about programming languages at all. In the end, "clever" >schemes that are presumed to let people run code on machines under >their control yet never be able to "read" the code must rely on >machinecode tricks of some sort, anyway, since obviously, from a >technical viewpoint, if the code must be executable, it must be >*read* on the way to the execution engine -- if it's encrypted it >must exist in decrypted form at some point (and it can then be >captured and examined at that point), etc. Some of the code that (or maybe it can't, for practical purposes, see below) >I was supposed to "protect" for my previous employer was in C, >Fortran, C++, and other high-level languages; some was in >machine code; other yet was in intermediate-code generated by a >proprietary scripting language; ... in the end it made no real >difference one way or another. OTOH, we are getting to the point where rather big functionality can be put on a chip or tamper-proof-by-anyone-but-a-TLA-group module. I.e., visualize the effect of CPUs' having secret-to-everyone private keys, along with public keys, and built so they can accept your precious program code wrapped in a PGP encrypted message that you have encrypted with its public key. The computer owner can say run it or not, but other than i/o nothing can be observed, because decryption happens in cache memory that you can't reach the address/data busses of, and execution likewise passes no instructions or temporary data through any tappable wire. A separate execution unit commpunicates via a restricted protocol to a normal CPU unit that has normal OS stuff running and can do the rest, but can't reach into that private space. This is not so magic. You could design a PC with a locked enclosure and special BIOS to simulate this, except that that wouldn't be so hard to break into. But the principle is there. Taking the idea to SOC silicon is a matter of engineering, not an idea break-through (though someone will probably try to patent on-chip stuff as if it were essentially different and not obvious ;-/) I think this will come. It can be a good thing _if used right_, but that's a big if. I just hope it won't be used to make artificial obstacles to interoperability of free vs proprietary. And doing it between proprietary stuff just raises the prices for what can't compete on merit. I have a hunch FSF/EFF lawyers should be preparing to lobby against laws that will permit such market manipulations, if they aren't already. Or maybe get law enacted mandating free interoperability. Maybe I'm just a worrywart ;-) Regards, Bengt Richter From peter at engcorp.com Fri Nov 21 12:21:57 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Nov 2003 12:21:57 -0500 Subject: Best method for an NT service and python to interact? References: <9arqrv4umfpe1dhnicfjuod1bv7ihf8pds@4ax.com><3FBD7C3A.AC542F65@engcorp.com> Message-ID: <3FBE49B5.4D1D46D4@engcorp.com> Brad Clements wrote: > > _ > "Charlie Orford" wrote in message > news:qq1rrvkm58mddn4f7ost889dligvlo65c2 at 4ax.com... > > > Thanks Peter. I am so clowded with Win32 programming that all I think > about > > is window messaging. Setting up a simple UDP server is a great idea and I > > think I will go down this route. > > Don't forget to consider the security ramifications of such a simple > approach. I'll put it another way: make sure that your server is bound to ('127.0.0.1', port) instead of ('' , port) and there should be relatively few issues with security. -Peter From cbrown at metservice.com Mon Nov 3 16:09:26 2003 From: cbrown at metservice.com (Colin Brown) Date: Tue, 4 Nov 2003 10:09:26 +1300 Subject: Qn: Nested dictionary cleanup Message-ID: <3fa6c327$1@news.iconz.co.nz> My code fragment below: for key1 in dict1.keys(): for key2 in dict1[key1]: if dict1[key1][key2] == None: del dict1[key1][key2] gives the following error: RuntimeError: dictionary changed size during iteration Any suggestion on how to code this please. Thanks Colin Brown PyNZ From bokr at oz.net Sun Nov 9 11:52:29 2003 From: bokr at oz.net (Bengt Richter) Date: 9 Nov 2003 16:52:29 GMT Subject: prePEP: Decimal data type References: Message-ID: On 9 Nov 2003 03:02:21 -0500, aahz at pythoncraft.com (Aahz) wrote: >In article , >Mel Wilson wrote: >>In article , >>"John Roth" wrote: >>> >>>My personal opinion in the matter is that setting the precision >>>high enough so that you won't get into trouble is a hack, and it's >>>a dangerous hack because the amount of precision needed isn't >>>directly related to the data you're processing; it's something that >>>came out of an analysis, probably by someone else under some other >>>circumstances. Given a software implementation, there's a performance >>>advantage to setting it as low as possible, which immediately puts >>>things at risk if your data changes. >> >> It puzzles me. In the COBOL days, we used to worry over setting the >>sizes of our data fields large enough. We'd set a size we thought was >>ridiculously large and then worry whether today would be the day that >>the company would do the unprecedented amount of business that would >>blow up the night-shift batch runs. We escaped from that with Python's >>long ints and now we're trying to invent it again. > >Division is the fly in the ointment, unfortunately. The other operations >lead to unbounded-but-finite number sets; division leads to infinite size >unless truncated or rounded. But (a/b) / (c/d) == (a/b) * (d/c) == (a*d/b*c) so if you can deal with multiply you can postpone truncation or rounding if you postpone actual division by maintaining the separate rational components. Of course (a/b) + (c/d) => (a*d+b*c / b*d) so you can wind up with a lot of multiplies too, if b!=d. I wondered what was really entailed, so I wrote an experimental module (exactdec.py, see recent post in this thread (it is very unoptimized, but it seems to work for interactive purposes)). At least one can mentally shift to thinking about when and why rounding or truncation is _really_ necessary in real use cases. Maybe eager rounding is premature optimization and/or a no-op in a lot of cases (or worse, hidden value transformations that are not documented as intentional). I wonder what the legislators would mandate if they thought exact arithmetic was as cheap and easy as hardware fixed point. Maybe currency exchange rates would be expressed as e.g. / when they were fixed legally, and there would be no argument about using the inverse ;-) The problem would move elsewhere. But where? Well, I don't know, presumably how to round when doing debit/credit across an exact echange rate to accounts expressed in discrete mimimum quanta. Hm, ... that's actually not uninteresting ;-) What does currency exchange _really_ mean? Any given exchange that is not exact could be said to have an exactly defined error in one or both sides of the transaction. If a price is stated in one currency, that could be presumed exact. If the other side always truncated down to an exact amount, the exact errors could theoretically be accumulated in an error bank, doing exact arithmetic summing fractions all less than 1, determined by the various exchange rates in effect over time. Ignoring the computing problems, what would be the meaning of the total in that national error bank at the end of a year? A tax on inexact arithmetic? What is the meaning of ignoring the amount? A leak in the monetary system? Probably only of theoretical interest compared to other leaks ;-) Regards, Bengt Richter From mcicogni at siosistemi.it Fri Nov 7 13:04:11 2003 From: mcicogni at siosistemi.it (Mauro Cicognini) Date: Fri, 07 Nov 2003 19:04:11 +0100 Subject: try...finally is more powerful than I thought. In-Reply-To: <3FABB15C.6BB2C44A@hotmail.com> References: <3faab4e8$0$559$b45e6eb0@senator-bedfellow.mit.edu> <3FABB15C.6BB2C44A@hotmail.com> Message-ID: Alan Kennedy wrote: > When an exception occurs in the try clause, the exception is > temporarily saved, the finally clause is executed, and then the saved > exception is re-raised. I've always wondered, how does one use this in real life? Since I cannot write try... except... finally..., which would be the most intuitive construct to me, I understand I should write try: try: ... finally: ... except: ... to achieve the same effect. Am I right? I.e. (again) how do you people use try .. finally in real use cases? Does anyone else think Python could have a nicer syntax for this one? Mauro From duncan at NOSPAMrcp.co.uk Fri Nov 28 10:11:45 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 28 Nov 2003 15:11:45 +0000 (UTC) Subject: Unexpected python behaviour References: Message-ID: Richard Philips wrote in news:mailman.1174.1070029879.702.python-list at python.org: > Consider the script: > > def test(drivers={}): > if drivers: > print drivers > else: > drivers["A"] = "B" > > if __name__ == "__main__": > test() > test() > > prints in stdout: > {'A': 'B'} > > I expected that nothing would be displayed. > I do not understand this behaviour (python2.3 on WinXP and Linux). You are not alone, this is one of the commonest questions from beginners. > > If anybody can explain this situation, you are welcome. The best explanation I know is in the FAQ, entry 4.21. See http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects > > Thank you. > You are welcome. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From martin at v.loewis.de Mon Nov 10 16:31:13 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 10 Nov 2003 22:31:13 +0100 Subject: pickle complexity limit? References: <7x4qxckwdu.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > I wonder if it's feasible to write a pickler as a C extension that > works something like a pointer-reversing garbage collector, > eliminating the need for recursion and still not needing any extra > storage in the objects. You definitely will need storage, to remember the objects you have to come back to; you won't necessarily need storage *in the objects*. Regards, Martin From guido.schimmels at freenet.de Thu Nov 20 15:21:49 2003 From: guido.schimmels at freenet.de (Guido Schimmels) Date: Thu, 20 Nov 2003 21:21:49 +0100 Subject: What do you think of this Python logo? References: <3FB00D3B.2BCE081A@engcorp.com> Message-ID: Am Tue, 11 Nov 2003 05:07:22 +0000 schrieb Patrick Ellis: > All the logos seem to be purely snake oriented. There is nothing about the > Monty kind of Python. I don't think a snake with a silly walk would work as > a logo. Maybe a snake with a napkin on its head? Or a dead parrot? Two puns for the price one. Buy Now! From belred1 at yahoo.com Sun Nov 16 19:24:14 2003 From: belred1 at yahoo.com (Bryan) Date: Mon, 17 Nov 2003 00:24:14 GMT Subject: PyQt, Qt, Windows and Linux In-Reply-To: References: Message-ID: <3FB8152D.7080909@yahoo.com> > > Programming is a hobby for me and I want to write Win32 GUI programs using PyQt but don't want to be > the only one who can enjoy my programs. Specifically, I am writing a numberology program in Python > that I wrote many years ago using VB6 and want to use PyQt and Qt for the GUI design. It seems that > Qt is the only platform which uses Tab Widgets. I couldn't find anything like that in wxPython (I > need multiple tabs) and Qt has a QTab Widget that works perfectly. > > Than you for the help. I really want to get BlackAdder but don't want to buy it just to be > disappointed later. jim, i clicked on the screenshots at the wxPython website and just about every screenshot uses a tab widget and they all look really nice: http://www.wxpython.org/screenshots.php wxWindows/wxPython includes a wxNotepad which is belive is what you are calling a tab widget. wxPython has wxNotebook, wxNotebook event and wxNotebook Sizer classes. there's an nice example in the wxPython demo and the source code looks very easy to use. the look and feel is what you would expect on windows. here's a link to an alphabetical listing of the classes. http://www.lpthe.jussieu.fr/~zeitlin/wxWindows/docs/wxwin27.htm#classref bryan From mis6 at pitt.edu Tue Nov 25 01:47:19 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 24 Nov 2003 22:47:19 -0800 Subject: Adding new methods at runtime to a class References: <338366A6D2E2CA4C9DAEAE652E12A1DEEEC2C9@au3010avexu1.global.avaya.com> Message-ID: <2259b0e2.0311242247.140cd06e@posting.google.com> Fran?ois Pinard wrote in message news:... > [Delaney, Timothy C (Timothy)] > > > From: Fernando Rodriguez > > > > How can I add new methods at runtime to a class? > > > Before we send you into what most would consider black magic in > > Python, you should explain why you want to. In most cases, this is > > *not* what you want to do - there are better, more elegant and much > > more Pythonic ways of doing it. > > There is a case which happens sometimes for me, in which I find it > useful assigning methods at runtime. It occurs in stateful objects, > where the actions of conceptual method varies according to the state. > It is clean, clear and fast to merely assign various processors to > methods when the state changes, more than maintaining and testing a > state variable all-around in a never changing set of methods. (What > does not change is the external API.) > > To me at least, it does not look like black magic, I find it Pythonic > enough, and even elegant, to the point I'm doing more and more. Oh, I > do read your assertion about what people do "in most cases", but I'm not > sure how you get such statistics. Please enlighten us! :-) I was thinking about an even more frightening possibility: changing the class of the stateful object! I.e. there would be a different class for each state (hopefully collected in a common hierarchy) and one would change the class of "self" according to some condition. This would automatically accomplish the change of the methods according to the state, and would give the additional benefit of inheritance (i.e. methods could call they supermethods quite easily). I haven't written anything yet, since I am not sure if it would be a good idea in practice, however I wonder if somebody ever tried it. The message is "We got a dynamic language: let use it!" Michele From ktilton at nyc.rr.com Sun Nov 2 11:00:38 2003 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Sun, 02 Nov 2003 16:00:38 GMT Subject: Paging Mr. Rettig [ws Re: Explanation of macros; Haskell macros] In-Reply-To: <87n0bfhszi.fsf@thalassa.informatimago.com> References: <87brs2tjut.fsf@memetrics.com> <87n0bfhszi.fsf@thalassa.informatimago.com> Message-ID: Pascal Bourguignon wrote: > Kenny Tilton writes: > >>Cue Duane of Franz. He mentioned over lunch at ILC2003 where John >>McCarthy used my laptop for ten minutes that their Allegro Common Lisp > > > Just put "John McCarthy used my laptop for ten minutes" in your > signature and forget it! :-) I prefer the subliminal approach, it affects brain Cells more indelibly. How about JMUML? :) kenny -- http://tilton-technology.com Why Lisp? http://alu.cliki.net/RtL%20Highlight%20Film Your Project Here! http://alu.cliki.net/Industry%20Application From aleax at aleax.it Thu Nov 13 13:01:21 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Nov 2003 18:01:21 GMT Subject: access to python function from C code References: <16d19726.0311130836.263e2a74@posting.google.com> Message-ID: Vin wrote: > Is it possible to access a function defined in python shell from c-code? > > For example if I have defined > >>>> def c(x): > ... return x*x > ... > > and defined in some module foo > > static PyObject * > ptk_doit(PyObject *self, PyObject *args) > { > > get reference to a function here from python interpreter and apply the > function to a given value ... Yes, it can be done. Exactly how depends on how you want to call this C-coded function, see below. > > return Py_BuildValue("d",result); > } > > > then I can do ... > >>>> import foo >>>>foo.doit(c,4) > 16 So you want to pass the function object and its single argument? OK, BUT: > function can be supplied to an underlying C code > without compilation. Probably the performance would be affected but that > my not be a problem in some cases. > > Needs like this arise in Optimization for example when > objective function can be arbitrary and optimization is done with general > optimization routines written in C. ...that's very unlikely to be a sensible tack because you'll call that function so MANY times the (big) performance impact will hurt. Still, whatever makes you happy (warning, untested code)...: PyObject *func, *arg, *resultobj, *floatresult; double result; if(!PyArg_ParseTuple(args, "OO", &func, &arg)) return NULL; resultobj = PyObject_CallFunctionObjArgs(func, arg, NULL); if (!resultobj) return NULL; floatresult = PyNumber_Float(resultobj); Py_DECREF(resultobj); if (!floatresult) return NULL; result = PyFloat_AS_DOUBLE(floatresult); Py_DECREF(floatresult); this should be an acceptable body for ptk_doit before its return statement. Alex From JTesser at nbbc.edu Mon Nov 24 08:00:23 2003 From: JTesser at nbbc.edu (Jason Tesser) Date: Mon, 24 Nov 2003 07:00:23 -0600 Subject: Web Authentication to AD Message-ID: <04875CB4331F0240A0AD66F970978651160A24@paul> I would like to write a python web service that would take a username and password entered on a web form and authenticate to Active directory. A few questions about this. 1. How can I do it :-) 2. I would like the script to be in the same server as the websites which is a linux box. So I need it to call active directory on a M$ box. If this is too hard could someone at least explain the process if I make this a service on the M$ box. Which I guess I can do if keeping it on the Linux box is too much. 3. I would like to expand the service so that I could check the computer the user is on and not make them enter a username and password if they are already logged in to the domain. I huess I would have to use Java Script for this. Any ideas here? Thank you in advance. Jason Tesser Web/Multimedia Programmer Northland Ministries Inc. (715)324-6900 x3050 From bkelley at wi.mit.edu Wed Nov 19 15:02:10 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Wed, 19 Nov 2003 15:02:10 -0500 Subject: Misleading Python error message Message-ID: <3fbbcbfc$0$577$b45e6eb0@senator-bedfellow.mit.edu> I accidentally derived a class from a module (types instead of types.Dicttype) >>> import types >>> class f(types): pass ... Traceback (most recent call last): File "", line 1, in ? TypeError: function takes at most 2 arguments (3 given) Shouldn't this report something like (TypeError: can't subclass from a module) It goes to the right line, but I coudn't see where the function was being called :) Brian From duncan at NOSPAMrcp.co.uk Wed Nov 5 04:15:55 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 5 Nov 2003 09:15:55 +0000 (UTC) Subject: Stuck on inheritance References: <2259b0e2.0311042349.63530be8@posting.google.com> Message-ID: mis6 at pitt.edu (Michele Simionato) wrote in news:2259b0e2.0311042349.63530be8 at posting.google.com: > Notice that "function" is a built-in, so I changed it to "funct". Perhaps you are using an unusual variant of Python? The usual variants don't have a built-in called "function". -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Fri Nov 21 07:42:14 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Fri, 21 Nov 2003 15:42:14 +0300 Subject: Empty list as default parameter In-Reply-To: References: Message-ID: Alex Panayotopoulos wrote: > Hello all, > > Maybe I'm being foolish, but I just don't understand why the following > code behaves as it does: > > - = - = - = - > > class listHolder: > def __init__( self, myList=[] ): > self.myList = myList > > def __repr__( self ): return str( self.myList ) > > # debug: 'a' should contain 42, 'b' should be empty. But no. > a = listHolder() > a.myList.append( 42 ) > b = listHolder() > print a > print b > > - = - = - = - > > I was expecting to see [42] then [], but instead I see [42] then [42]. It > seems that a and b share a reference to the same list object. Why? > Really common mistake: lists are _mutable_ objects and self.myList references the same object as the default parameter. Therefore a.myList.append modifies default value as well. Mutable defaults are better avoided (except for some variants of memo pattern). Standard trick is: def __init__(self, myList = None): if myList is None: self.myList = [] else: self.myList = myList regards, anton. From try_vanevery_at_mycompanyname at yahoo.com Fri Nov 14 05:49:23 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Fri, 14 Nov 2003 02:49:23 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <2259b0e2.0311140033.4e3ca8ea@posting.google.com> Message-ID: "Michele Simionato" wrote in message > > It is quite sterile to complain against things we have no real > way to control. True... but in most cases we're making an Existential choice about our willingness to control. We are not in fact helpless. Such is the case with Python. If you want to actually do something about marketing Python "like the big boys do," I encourage you to join the marketing-python forum. http://pythonology.org/mailman/listinfo/marketing-python Fair warning: you are going to hear a lot of people talking in circles. You are only going to get things done if you are the kind of person who will take a bull by the horns and actually get things done, even / especially when others are yapping mindlessly and endlessly. Commercial outfits have significant advantages over volunteer outfits when it comes to marketing: they can order people to march in a particular direction, pay people lotsa money to follow the orders, and fire them if they don't comply. Still... commercial outfits are hardly immune to Dilbertism, but the high tech landscape is dominated by companies like Microsoft who are not prone to Dilbertism in their approaches to marketing. > We can only wait and see (as in that old chinese said ...) Chinese philosophies, at least as received by Westerners looking for alternatives to their high stress culture, often have the flaw of being too Yin. The Tao is balance, not passivity. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA Brandon's Law (after Godwin's Law): "As a Usenet discussion grows longer, the probability of a person being called a troll approaches one RAPIDLY." From aahz at pythoncraft.com Thu Nov 6 16:37:46 2003 From: aahz at pythoncraft.com (Aahz) Date: 6 Nov 2003 16:37:46 -0500 Subject: prePEP: Decimal data type References: Message-ID: In article , John Roth wrote: > >The trouble is that most of the difficulty that's being discussed is >not for casual users. It's for professional users that have to adhere >to legal, regulatory and other requirements that have no inherent >underlying order that makes them amenable to a nice, neat and trivially >understandable solution. > >If coming up with something that is understandable to novices is a rock >bottom requirement, then I most respectfully suggest that the rest of >the discussion is a waste of time. Well, I disagree with that. >The part of my response which you didn't quote said something >about my not being able to find an expression syntax that would >handle these essentially arbitrary and capricious regulations. If >you would suggest one, I'd be delighted. Oh, I don't think there's a purely expression-based syntax that will solve that problem. But because it's easy enough (or should be -- I still haven't looked at the most recent version of the code) to create context objects and then use them to switch the active context between operations, I think that expert programmers will have little difficulty parameterizing their operations. Using named contexts should make things reasonably easy to read. Or, as Tim pointed out, the current code allows one to call operations directly on a context. That's pretty close to what you were asking for earlier. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From skip at pobox.com Mon Nov 24 22:35:48 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 24 Nov 2003 21:35:48 -0600 Subject: String Regex problem In-Reply-To: References: <7b454334.0311241844.210b4846@posting.google.com> Message-ID: <16322.52756.478752.965841@montanaro.dyndns.org> >> Since I am very poor in regex, can someone show me how to do it using >> a few examples? Don> http://www.amk.ca/python/howto/regex/ ... Don> http://kodos.sourceforge.net If you're a Mac Python person there's also Dinu Gherman's excellent RegexPlor: http://starship.python.net/crew/gherman/RegexPlor.html Even if you're not, it's worth popping over there to watch the MPEG clip of RegexPlor in action. Skip From steve at ninereeds.fsnet.co.uk Wed Nov 5 05:10:04 2003 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Wed, 05 Nov 2003 10:10:04 +0000 Subject: AI and cognitive psychology rant References: <8d667de1.0311031311.525ab29c@posting.google.com> Message-ID: <0jihqvg9hor8mjvlui1rosj2aq0iih0kvo@4ax.com> On 3 Nov 2003 13:11:16 -0800, socraticquest at hotmail.com (socraticquest) wrote: >How are adults with Asperger Syndrome in this newsgroup managing >career development agendas? Sorry for not answering yet - I am not sure what to say about my own situation, which is frankly bizarre. I'll have a think, and may reply by e-mail later. I will say that a lot of the people with AS that I've met IRL have never had a job at all. Online you can get the impression that almost everyone with AS is a computer nerd, but there is a lot of sampling bias in that. Also, while many people with AS have strong technical leanings, it doesn't really follow that there will be loads of AS people in a technical group. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From gherron at islandtraining.com Mon Nov 3 17:42:23 2003 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 3 Nov 2003 14:42:23 -0800 Subject: tar interface In-Reply-To: References: Message-ID: <200311031442.24359.gherron@islandtraining.com> On Monday 03 November 2003 02:29 pm, David Bear wrote: > I just googled for a 'python tar interface module' and got over 33000 > hits. ug. > > I'm looking for a python module that either interfaces to gnutar in a > pythonic way or reads/writes tar files directly. I know there's > always os.popoen etc, but was hoping for something a little more .. Python 2.3 has a module named tarfile that provides tar functionality as well as some of the gnu extensions to tar. It does not interface with any external implementation of tar, put provides its own. Here is an excerpt from its documentation: tarfile -- Read and write tar archive files New in version 2.3. The tarfile module makes it possible to read and create tar archives. Some facts and figures: * reads and writes gzip and bzip2 compressed archives. * creates POSIX 1003.1-1990 compliant or GNU tar compatible archives. * reads GNU tar extensions longname, longlink and sparse. * stores pathnames of unlimited length using GNU tar extensions. * handles directories, regular files, hardlinks, symbolic links, fifos, character devices and block devices and is able to acquire and restore file information like timestamp, access permissions and owner. * can handle tape devices. Hope that works for you, Gary Herron From peter at engcorp.com Fri Nov 21 13:56:12 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Nov 2003 13:56:12 -0500 Subject: small, fast and cross-platform flat-file database for python References: <425cc8d1.0311210915.33eb10e0@posting.google.com> <3FBE4940.BD960E76@engcorp.com> <4Ksvb.20$pr5.692@eagle.america.net> Message-ID: <3FBE5FCC.270BD194@engcorp.com> Eric Baker wrote: > > "Peter Hansen" schrieb im Newsbeitrag > news:3FBE4940.BD960E76 at engcorp.com... > > mir nazim wrote: > > > > > > i want to know if there is any flat-file relational database system > > ^^^^^^^^^ ^^^^^^^^^^ > > > > I'm no database expert, but aren't these two terms contradictory in > > some important way? > > > > -Peter > > Depends what your definition if the word "is" is :) > > In my early perl days, i used a simple text file based SQL "database". > http://search.cpan.org/~shgun/Sprite-3.21/Sprite.pm > > Now with Python, i would probably use SQLite, which isnt exactly a "flat > text file", but still a nice lightweight database for *nix and win32 IMHO. > http://www.hwaci.com/sw/sqlite/ I thought it depended more on the definition of "relational", which I understood to refer to operations such as "joins" between different tables. I suppose it could just be operations between different searches of the same table, however, in which case I suppose it's a valid term. -Peter From bokr at oz.net Sun Nov 30 17:49:29 2003 From: bokr at oz.net (Bengt Richter) Date: 30 Nov 2003 22:49:29 GMT Subject: The namespace for builtin functions? References: <3FC926ED.7070906@irl.cri.nz> Message-ID: On Sun, 30 Nov 2003 19:00:16 +0100, "Fredrik Lundh" wrote: >Blair Hall wrote: > >> Can anyone please tell me how to correctly use a built in function >> when there is a function of the same name in local scope? >> >> Here is an example. Suppose the following is in myApply.py: >> >> def apply(func,seq): >> # >> # Code can default to >> # built-in definition in some cases: >> return __builtins__.apply(func,seq) > >the module is named __builtin__, and must be imported before >it can be used. > >__builtins__ is a CPython implementation detail (it's used to cache >a reference to the builtin modules, and are initialized on demand). > >for more info, see the "Overloading functions from the __builtin__ >module" here: > > http://effbot.org/zone/librarybook-builtin.htm Weird -- netscape 4.5 claims that document "contains no data" wget got it though. Maybe time to reboot windows ;-/ > I think I agree with Francis. Why is __builtins__ set up in the interactive namespace differently from an imported module's namespace? To show what he was saying again, I made and empty module (nothing but an empty line in its source): >>> file('empty.py').read() '\n' >>> import empty >>> dir(empty) ['__builtins__', '__doc__', '__file__', '__name__'] Ok, now in the interactive namespace: >>> __builtins__ And in the 'empty' module's namespace: >>> `empty.__builtins__`[:60] "{'help': Type help() for interactive help, or help(object) f" (I knew I would be getting the whole dict repr if I just typed empty.__builtins__ ;-) >>> type(__builtins__) >>> type(empty.__builtins__) >>> __builtins__.__dict__ is empty.__builtins__ True >>> Seems inconsistent. Why not __builtins__ is empty.__builtins__ => True and hence __builtins__.__dict__ is empty.__builtins__.__dict__ => True (or maybe both __builtins__ bindings could be to the dict, though that would bypass potential getattr magic that might be needed somewhere?) Regards, Bengt Richter From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Fri Nov 14 10:03:28 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Fri, 14 Nov 2003 18:03:28 +0300 Subject: Trouble with regex In-Reply-To: <52p9rvs6av0dqe59t733o5netcd9t6r7q2@4ax.com> References: <52p9rvs6av0dqe59t733o5netcd9t6r7q2@4ax.com> Message-ID: Fernando Rodriguez wrote: > Hi, > > I'm trying to write a regex that finds whatever is between ${ and } in a text > file. > > I tried the following, but it only finds the first occurrence of the pattern: > > >>>>s = """asssdf${123} > > dgww${one} ${two}""" > >>>>what = re.compile("\$\{([^}]*)\}") >>>>m = what.search(s) >>>>m.groups() > > ('123',) > > What am I doing wrong? O:-) Nothing ;) search just finds first match. If you want to find all non-overlapping matches try finditer: import re s = """asssdf${123} dgww${one} ${two}""" what = re.compile("\$\{([^}]*)\}") for m in what.finditer(s): print m.groups() prints: ('123',) ('one',) ('two',) regards, anton. From bignose-hates-spam at and-benfinney-does-too.id.au Tue Nov 11 18:50:49 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 12 Nov 2003 10:40:49 +1050 Subject: Which of the best choice ? References: Message-ID: On 11 Nov 2003 15:54:50 -0800, SungSoo, Han wrote: > There are two coding style when python import module. This is more than coding style; it has two distinct effects. > (1) import sys Allows 'sys' module objects to be used within the 'sys' namespace. > (2) from import sys (or from import *) Isn't syntactically correct (refers to a non-existent module called 'import', then has the non-keyword 'sys'). Assuming you mean: from sys import * this has the effect that all objects from the 'sys' module are available in the default namespace. > I prefer (1) style. Because it's easy to read, understand module in > any category More importantly, (1) doesn't pollute the main namespace; any objects that have the same name in the main namespace are unambiguously referenced with the 'sys' namepace. >>> maxint = 23 >>> maxint 23 >>> import sys >>> maxint 23 >>> sys.maxint 2147483647 Whereas, with (2), the symbols from 'sys' pollute the main namespace: >>> maxint = 23 >>> maxint 23 >>> from sys import * >>> maxint 2147483647 > Which prefer ? It's usually preferable to use (1), because there is no namespace collision, and it has the added benefit of making it unambiguous which module the symbols come from when they are later used. -- \ "Why, I'd horse-whip you if I had a horse." -- Groucho Marx | `\ | _o__) | Ben Finney From jimmy at retzlaff.com Mon Nov 17 21:39:11 2003 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Mon, 17 Nov 2003 18:39:11 -0800 Subject: ActivePython Installation problem on win95 Message-ID: Tom Semple wrote: > Python 2.3.2 (build 232) > > After installing (completes without error) I cannot start the PythonWin > IDE; > get an error: "The application can not locate win32ui.pyd for Python > (1157). > One of the library files needed to run this application cannot be found." > Certainly a file with this name exists so it is probably a dependent DLL > that is missing. Suggestions? > > Thanks > tom semple PythonWin is a part of win32all which, in turn, is a part of ActivePython. win32all no longer supports Windows 95. Here is a recent comment from Mark Hammond (win32all's author) about it: http://google.com/groups?selm=bp0u39%242h1a%241%40arachne.labyrinth.net. au Jimmy From newsgroups at jhrothjr.com Wed Nov 12 19:22:07 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 12 Nov 2003 19:22:07 -0500 Subject: loop does not count... References: Message-ID: "Jonathan Driller" wrote in message news:a8cff9fb.0311121513.521ca948 at posting.google.com... > I am very new to this and would greatly appreciate some insight. > I am trying to learn Python by doing something useful; write a script > that will count and output my aggregated visits to my website. I have > a separate text file that holds the list of uri strings that I want to > count and then this code. The log is sampleLog.txt. > > The problem is that it says all the preceding uris are 0 (they are > not) and only the last string actually is counted....why is that? > > def stats(): > import sys > import string > #read the file of current urls - presumes it exists already > x = open('urlList.txt') > # note this reads as a file, not a list > urlFile = x.read() > # don't need to close but should > x.close() > #list what is in text file of urls > print "Here is what we check now:\n", urlFile > print "\n" > > # len(listName) gives # of list elements > > #turn url listings into list > z = open('urlList.txt') > urlList = z.readlines() > #open log file > log = open('sampleLog.txt') > logFile = log.read() > #initialize counter at 0 > i = 0 > # loop through to search for urls > while i < len(urlList): > # put element into var > check = urlList[i] > #print out # found and what it was > print check, " found" , string.count(logFile, check) ,"times > \n" > # increment for next item - can't do i ++ > i = i + 1 > z.close() The lines you're reading from your test file all end in a newline, so that may be the reason you're not finding them in the log file. I suspect that you didn't end your test file with a return, so that line was found. change check = urlList[i] to check = urlList[i].strip() and it might work better. Also, your imports belong at the module level, not inside the definition. John Roth From bignose-hates-spam at and-benfinney-does-too.id.au Fri Nov 21 06:49:25 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 21 Nov 2003 22:39:25 +1050 Subject: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com> <3FBC2025.B2A33B6F@alcyone.com> <87d6bncbaj.fsf@einstein.electron.net> <3FBD3D6F.E4068821@alcyone.com> <878ymad3ga.fsf@einstein.electron.net> <3FBD6419.A5A863C8@alcyone.com> <874qwyaqqj.fsf@einstein.electron.net> Message-ID: On 21 Nov 2003 12:46:44 +0100, Curt wrote: > Erik Max Francis writes: >> You don't really think the sequence [flirty, curty, curty, flirty] is >> sorted, do you? > > Well, you did do _something_ to the sample for which you fail to find > a more descriptive word than "tweak". He contrived an example that demonstrated his point. You seem to be fascinated with finding some definition of "sort" that can be bent to this. > I certainly do think that the > proper word for the modified sample is "sorted"; yes, you sorted the > file on the word "curty", by which I mean that you performed "an > operation that segregates items into groups according to a specified > criterion" (WordNet). This is ridiculous. What makes you think he applied "the curty criterion", presuming there can be some meaningful definition of that? Why could he not, perhaps, have "sorted" it based on the arrangement of monitor toys he could see? Or on the output of /dev/random ? Are you saying that *any* list which has had *any* concievable criterion applied to its generation, must therefore have been "sorted"? None of this is the case. The contrived example showed that 'uniq' *does* have an effect on a list which has not been sorted (i.e. not sorted into the default order one would assume when hearing the term "sorted", i.e. alphanumeric ascending). Writhing to attempt to force the term "sorted" to apply to an unsorted list is rather psychotic. -- \ "Any sufficiently advanced bug is indistinguishable from a | `\ feature." -- Rich Kulawiec | _o__) | Ben Finney From rm at rm.net Thu Nov 13 16:00:49 2003 From: rm at rm.net (rm) Date: Thu, 13 Nov 2003 21:00:49 GMT Subject: checking for ASCII character In-Reply-To: References: Message-ID: <5iSsb.116839$di.28756285@amsnews02.chello.com> Greg Krohn wrote: > Daniel wrote: > >> Hi, is there a way to check if a letter entered is an uppercase ASCII >> character? >> >> Thanks >> >> Daniel > > > If you just want to know if a character is uppercase: > > if character.isupper(): > > > If it needs to be ASCII, the simplest way is probably: > > if ord(character) in range(65, 91): > > > > > greg > one could check for ascii by doing: try : character.encode('ascii') except UnicodeDecodeError : ascii = False else : ascii = True if ascii and character.isupper() : pass or something like it bye, rm From tool_man at spamcop.net Tue Nov 4 14:49:31 2003 From: tool_man at spamcop.net (Tim Lavoie) Date: Tue, 04 Nov 2003 13:49:31 -0600 Subject: best GUI toolkit for python: tkinter, wxPython or what? References: <3fa13dd3.2565248@news.dsl.pipex.com> Message-ID: <87he1j52yc.fsf@theasylum.dyndns.org> >>>>> "Frithiof" == Frithiof Andreas Jensen writes: Frithiof> Actually, *I* didn't have any trouble with Tkinter Frithiof> look&feel - The reason I do not use it is beacuse there Frithiof> are no - well none that I could find anyway - tools Frithiof> available to design Tkinter GUI's with! Perhaps this might help: http://vtcl.sourceforge.net/ -- Outside of a dog, a book is a man's best friend. Inside a dog it's too dark to read. -- Groucho Marx From SBrunning at trisystems.co.uk Wed Nov 5 07:53:46 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Wed, 5 Nov 2003 12:53:46 -0000 Subject: from python1.5.2 to pytghon2.2.2 Message-ID: <31575A892FF6D1118F5800600846864D01200C82@intrepid> > From: alberto.mantovaniNOSPAM at bologna.marelli.it > [SMTP:alberto.mantovaniNOSPAM at bologna.marelli.it] > I have a lot of scripts written in python1.5.2 that I have to bring in > python2.2.2 , someone could give me some informations about the sintax > differences between the two versions?. Better answer this, of he'll *never* stop asking. ;-) See the following, one per interim release: http://www.amk.ca/python/2.0/ http://www.amk.ca/python/2.1/ http://www.python.org/doc/2.2.3/whatsnew/ http://www.python.org/doc/2.3/whatsnew/ > Are there some tools that can do this automatically? Not that I'm aware of. Cheers, Simon B, http://www.brunningonline.net/simon/blog/ --LongSig ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From nav+posts at bandersnatch.org Wed Nov 12 11:04:56 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 12 Nov 2003 11:04:56 -0500 Subject: What do you think of this Python logo? References: <3FB00D3B.2BCE081A@engcorp.com> <3FB0D741.F416E987@engcorp.com> Message-ID: Oren Tirosh writes: > Perhaps a python digesting a camel after having swallowed it whole? But wouldn't that just look like a hat? Nick (Apologies to Antoine de Saint-Exupery...) -- # 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 infoNOSPAM at PythonRAD.tk Sun Nov 2 13:09:54 2003 From: infoNOSPAM at PythonRAD.tk (PythonRAD) Date: Sun, 02 Nov 2003 18:09:54 GMT Subject: Textbox with ScrollBar Message-ID: Hi at all, I looking for the widget that admit the multiline with scrollbar for Tkinter... any idea? Help me please Michelangelo -- ########################## # Yahoo Messenger: ShineMiku # Ti aspetto per chiccherare su # Programmazione, Tecnologie # Collaborazioni di Lavoro ########################## From tim at worthy.demon.co.uk Tue Nov 25 07:53:48 2003 From: tim at worthy.demon.co.uk (Tim Howarth) Date: Tue, 25 Nov 2003 12:53:48 GMT Subject: win32com (VBScript to Python) problem References: <6e24de564c.tim@worthy.demon.co.uk> Message-ID: <4700e5564c.tim@worthy.demon.co.uk> In message Duncan Booth wrote: > Tim Howarth wrote in > news:6e24de564c.tim at worthy.demon.co.uk: > > > I want to use this to shutdown all machines in the school in which I > > work from a schedule on a server. > > This isn't a Python solution at all, but have you looked at PsTools > (http://www.sysinternals.com)? Yes, very handy tools. It's just that I'd like to do the shutting down myself - why call pshutdown if I can call the shut down mechanism directly. -- ___ |im ---- ARM Powered ---- From 3seasA at Tthreeseas.DOT.not Mon Nov 10 18:03:13 2003 From: 3seasA at Tthreeseas.DOT.not (3seas) Date: Mon, 10 Nov 2003 23:03:13 GMT Subject: "Autocoding Reloaded" (was Re: Matrix - Metaphors, Analogies and the REAL References: <3FB008DB.A4F3E01@engcorp.com> Message-ID: 3seas wrote: > As to those who have said to me in the past that my communication suck, It > sure did seem to suck when I was communicating to a code writer.... NOT!!! -- 3 S.E.A.S -- Virtual Interaction Configuration (VIC) Changing how we preceive and use computers email @ translate not to net, remove capitol letters, one . web @ http://threeseas.net From nav+posts at bandersnatch.org Fri Nov 21 13:40:18 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 21 Nov 2003 13:40:18 -0500 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <7xad6sb7cd.fsf@ruckus.brouhaha.com> <87smkjw55g.fsf@pobox.com> <7xy8ubdl1f.fsf@ruckus.brouhaha.com> <87smkitutw.fsf@pobox.com> <7xr801zm2q.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Rotor is not needed to provide that barrier. You can do the same thing > with a simple xor against the key. Since rotor is there, though, people have used it. It's also a nice homage to one of the defining periods of "modern" cyptography. But that doesn't mean it needs to be in the standard library. 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 rooting_j00 at hotmail.com Fri Nov 7 00:40:57 2003 From: rooting_j00 at hotmail.com (Code_Dark) Date: 6 Nov 2003 21:40:57 -0800 Subject: Creating a random integer.... Message-ID: <8f43ba42.0311062140.344ed651@posting.google.com> Hi, sorry to bore you with my newbie questions, but I _am_ a newbie so.. right. Anyway, I was working out a "number guessing game", which works fine, except I wanted to make the number a random number so it's different every time... can you please tell me what to do to get python to create a random number? Thanks, - Code Dark From seberino at spawar.navy.mil Fri Nov 21 16:56:59 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 21 Nov 2003 13:56:59 -0800 Subject: How send LIST to C extension? Message-ID: I already sent a post about problems sending list as argument in a C extension. I think I'll start over and just ask if anyone has done this successfully. Can you send me code that does this?? (I tried PyArg_ParseTuple("[ii]",...) but apparently there is more to it than just adding brackets. chris From sross at connectmail.carleton.ca Sat Nov 29 22:11:11 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 29 Nov 2003 22:11:11 -0500 Subject: referencing an object attribute sort of indirectly from within list References: Message-ID: Hi. I've made some small changes to your code. It appears to be doing what you're looking for now. HTH, Sean class BackupSet: fileGroupList = [] class FileGroup: sourceDir = '' destinDir = '' def __init__(self): self.sourceDir = r'c:\folder' # use a raw string or escape the '\' self.destinDir = r'd:\folder' # like so, 'c:\\folder' fileGroup = FileGroup() # backupSet = BackUpSet() <-- NameError! backupSet = BackupSet() backupSet.fileGroupList.append(fileGroup) # print bkset.fileGroupList[0].sourceDir <-- where did 'bkset' come from? # using backupSet instead .... print backupSet.fileGroupList[0].sourceDir # outputs "c:\folder" From mis6 at pitt.edu Mon Nov 24 09:03:53 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 24 Nov 2003 06:03:53 -0800 Subject: Bug or Feature? References: Message-ID: <2259b0e2.0311240603.549943b3@posting.google.com> Stephan Diehl wrote in message news:... > I was playing around with defining new types and have seen the > following behaviour: > > Python 2.3.1 > ============ > > >>> class Int(int):pass > ... > >>> a = Int(7) > >>> b = Int(8) > >>> c = a + b > >>> type(c) > > > Basicly: Int is not closed under it's defined operations. :-( > You want my "innermethods" module. Originally I wrote it as a recipe for the cookbook, but then I forgot to post it ;) """ A method of a class ``C`` is said to be an ``inner method`` of ``C`` if it returns an instance of ``C``. For instance, the ``.replace`` method of the string class is an inner method of ``str``, since invoked by a string, it returns a string: >>> s='s' >>> r=s.replace('s','r') >>> print r,type(r) r In general, the property of being an inner method is not preserved by inheritance. For instance, if I define a subclass of the string class, >>> class Str(str): ... pass then ``Str`` has still a ``.replace`` method (inherited from ``str``), but it is not an inner method of ``Str``: >>> s=Str('s') >>> r=s.replace('s','r') >>> print r,type(r) # the type of r is 'str', not 'Str'! r In many circumstances, this is not a problem. However, sometimes it is important to keep the inner methods safe under inheritance. If we are writing the methods from scratch, this can be done by returning ``self.__class__(returnvalue)`` instead of the simple ``returnvalue``. However, if the methods have been written by others and we are simply inhering them, we need a more sophisticated solution. This module provides a ``protect_inner_methods`` metaclass-like function which guarantees that the inner methods of the class invoking it are safe under inheritance. As an exemplication and a commodoty, the module also provides a ``Str`` class with protected versions of all the inner methods of the builtin ``str`` class. The only exception are ``__str__`` and ``__repr__``: it is better than they stay unprotected, so the string representation of subclasses of ``str`` is a simple plain string, not an enhanced one. In this way ``str(x)`` continues to convert ``x`` instances in ``str`` instances. If ``Str`` instances are wanted, use ``Str()``! Here is an example, showing that ``Str.replace`` is an inner method of ``Str``: >>> from innermethods import Str >>> s=Str('s') >>> r=s.replace('s','r') # .replace invoked from an instance of 'Str' >>> print r,type(r) # returns an instance of 'Str', i.e. it is inner method r Let me show that the inner methods of ``Str`` are protected under inheritance, i.e. they continues to be inner methods of the subclasses: >>> class MyStr(Str): ... pass >>> s=MyStr('s') >>> r=s.replace('s','r') # .replace invoked from an instance of 'Str' >>> print r,type(r) # returns an instance of 'Str', i.e. it is inner method r """ def protect_inner__method(cls,methname): """Given a class and an inner method name, returns a wrapped version of the inner method. Raise an error if the method is not defined in any ancestors of the class. In the case of duplicated names, the first method in the MRO is taken.""" def _(self,*args,**kw): supermethod=getattr(super(cls,self),methname) return self.__class__(supermethod(*args,**kw)) return _ def protect_inner_methods(name,bases,dic): """Metaclass-like function. Returns a new class with inner methods protected under inheritance. The calling class must provide a ``__innermethods__`` attribute containing the list of the method names to be protected, otherwise nothing will be done.""" cls=type(name,bases,dic) # generate the new class innermethods=dic.get('__innermethods__',[]) # look for the list of methods to wrap and wrap them all for methname in innermethods: setattr(cls,methname,protect_inner__method(cls,methname)) return cls class Str(str): """A string class with wrapped inner methods.""" __metaclass__=protect_inner_methods __innermethods__="""__add__ __mod__ __mul__ __rmod__ __rmul__ capitalize center expandtabs join ljust lower lstrip replace rjust rstrip strip swapcase title translate upper zfill""".split() def __radd__(self,other): # inner method """Guarantees ``'a'+Str('b')`` returns a ``Str`` instance. Also ``s='s'; s+=Str('b')`` makes ``s`` a ``Str`` instance.""" return self.__class__(other.__add__(self)) From ken at perfect-image.com Sun Nov 2 16:15:24 2003 From: ken at perfect-image.com (Ken Godee) Date: Sun, 02 Nov 2003 14:15:24 -0700 Subject: PyQt, Qt, Windows and Linux In-Reply-To: <200311021949.34594.phil@riverbankcomputing.co.uk> References: <200311021949.34594.phil@riverbankcomputing.co.uk> Message-ID: <3FA573EC.5060109@perfect-image.com> Phil Thompson wrote: > On Sunday 02 November 2003 7:28 pm, Alex Martelli wrote: > >>Vamsi Mudrageda wrote: >> >>>I am kind of new to Python, and after trying and using wxPython, I found >>>it kind of lacking in easy-to-read documentation, speed at loading, and >>>GUI response-time. >>> >>>So I am looking for an another GUI toolkit that is cross-platform for >>>Python, and am leaning toward PyQt (PyGTK is kind of dull looking in >>>comparison). Unfortunately, although TrollTech says Qt is >>>cross-platform, its license strategy has me a bit confused. So here is >>>to hoping someone can help... >>> >>>Objective: >>> Develop/Write a program for personal use on my Linux using PyQt. Be >>>able to also run it on Windows. >>> >>>Questions: >>>1) Is it legally possible to do that? >> >>Yes. >> >> >>>2) Do I need to buy a license from TrollTech? >> >>Yes, or from one of Trolltech's licensed resellers of licenses. The >>cheapest way you can proceed, I believe, is to buy Blackadder, personal >>edition, from theKompany.com: it comes with personal-use licenses of >>PyQt and Qt for both Linux and Windows (I _think_ mac, too, but I don't >>know about that). I believe it currently costs US $70 . > > > No - not Mac. > > Phil > Maybe I'm missing something new here......... But as far as I know, you "DO NOT" need to buy a license from TrollTech or PyQt or buy anything to give it a try, as long as use is personal and not used in a commercial enviroment. The only thing is you would have to make do with the older ver.2.3(?) on windows and many do. Although I do think BlackAdder is a heck of a deal and would get you the newest versions for both win and linux. This is the kind of thing that can scare away someone who just wants to give it a try to see if they like it. Once they give it a try, they'll be hooked forever!!! If I'm wrong, someone let me know. Hands down, PyQt is the way to go!!!!!! From peter at engcorp.com Tue Nov 4 10:44:54 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 04 Nov 2003 10:44:54 -0500 Subject: Testing & stdout References: <6250403b.0311040151.32fd4754@posting.google.com> <3FA7A9B1.D09ED381@engcorp.com> Message-ID: <3FA7C976.7AF9749D@engcorp.com> Peter Hansen wrote: > > Miki Tebeka wrote: > > > > In my test suite I also test some function that output messages to stdout. > > Is there an easy way to temporary divert stdout to another location? > > > > Currently I'm using: > [snip] > > This works fine if no one is caching stdout somewhere. > > "Caching stdout"? What's that mean? Who would do such a thing? Ah, reading John's reply I think I figured out what you meant. You mean some of the code being called is using a saved reference to sys.stdout, and so it won't dynamically pick your changed version of that name. I encountered the same problem once, and found no solution. -Peter From hungjunglu at yahoo.com Mon Nov 24 23:41:57 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 24 Nov 2003 20:41:57 -0800 Subject: code blocks in Python References: <8ef9bea6.0311221215.804bdb3@posting.google.com> <8ef9bea6.0311231634.1ca497ac@posting.google.com> <8ef9bea6.0311232220.4e308a4c@posting.google.com> <8ef9bea6.0311241105.e53c47d@posting.google.com> <8ef9bea6.0311241527.61a27b6c@posting.google.com> Message-ID: <8ef9bea6.0311242041.92f108a@posting.google.com> "John Roth" wrote in message news:... > I'm probably representative. If you don't manage a compelling > case for why dynamic binding is a useful option, then you're not going > to get anywhere with this proposal. Wow, I did not even know there was a proposal. :) I thought the purpose of my message was to find out whether there have been previous attempts. I still have not gotten an answer, and I see already lots of fire. For no good reason. As I have said, I refuse to believe I am the first person to bring up this topic. Because it seems such a simple issue, such a simple feature. (Bear in mind that the compile() function exists since a long long time ago.) So, I am prepared to listen to experts comment on why everything is wrong and un-doable, and that the topic has been covered many times before and is dead since a long time ago. So that I can simply stop. Yet, I have heard none to the effect. ------------------ Like someone said once about metaclasses: if you need to ask if you need to use metaclasses, the answer is "you don't". Same thing with metaprogramming. If you need to ask whether you need metaprogramming, the answer is: "you don't". People that get into metaclasses and metaprogramming know what they want to do. If you have really read and digested my comment about thinking first on compile() function and post later, you wouldn't have posted your message. There are two issues here: (1) The usefulness of meta-programming. (2) Codeblock feature. You are asking the question about (1), not (2). My impression is that you have no experience using compile() function, nor general idea about metaprogramming. (Feel free to correct me.) But you decide to use it as an argument to attack (2) anyway, instead of (1). Your firepower is misplaced, and causes only colateral damages. Usefulness of meta-programming (in particular, linear meta-programming) is a completely different subject. If you don't like metaprogramming, you should have attacked Guido a long time ago, when the compile() function and code object appeared in Python. That's what I mean by you need to keep the compile() function in mind before you make senseless comments about dynamic binding and linking it to (2). You need to first make that distinction in mind. Your mistake and of the others comes from your unfamiliarity with the usage of code objects. Your questions are not regarding codeblock implementation. Your questions are about metaprogramming in general. Sure, I'm more than glad to discuss about linear metaprogramming, despite of having discussed with tons of other Python regulars lots of times before. But before that, I'd like to make sure about my original point: has the idea of codeblock ever been discussed in Python? When and where and the URL links. I am still waiting. regards, Hung Jung From Ax10 at gmx.de Sun Nov 30 02:10:49 2003 From: Ax10 at gmx.de (Mike Abel) Date: Sun, 30 Nov 2003 08:10:49 +0100 Subject: Tkinter "Expected boolean value" References: Message-ID: Grzegorz Dostatni wrote: > File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 2310, in selection_present > return self.tk.getboolean( > TclError: expected boolean value but got "" I guess: Tcl needs a boolean value and gets an empty string? Try to look in this direction. Mike From fumanchu at amor.org Tue Nov 25 12:36:11 2003 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 25 Nov 2003 09:36:11 -0800 Subject: Web Authentication to AD Message-ID: I haven't tried *writing* that myself, but I've *used* samba's winbindd daemon to good effect. You might check their approach and see if that would work for you. http://us2.samba.org/samba/docs/man/winbindd.8.html Robert Brewer MIS Amor Ministries fumanchu at amor.org > -----Original Message----- > From: Jason Tesser [mailto:JTesser at nbbc.edu] > Sent: Tuesday, November 25, 2003 4:10 AM > To: Python List (E-mail) > Subject: RE: Web Authentication to AD > > > Has nobody tried to do this kind of thing? > > -----Original Message----- > From: python-list-bounces+jtesser=nbbc.edu at python.org > [mailto:python-list-bounces+jtesser=nbbc.edu at python.org]On Behalf Of > Jason Tesser > Sent: Monday, November 24, 2003 7:00 AM > To: Python List (E-mail) > Subject: Web Authentication to AD > > > I would like to write a python web service that would take a > username and password entered on a > web form and authenticate to Active directory. A few > questions about this. > > 1. How can I do it :-) > 2. I would like the script to be in the same server as the > websites which is a linux box. So I need it to call active > directory on a M$ box. If this is too hard could someone at > least explain the process if I make this a service > on the M$ box. Which I guess I can do if keeping it on the > Linux box is too much. > 3. I would like to expand the service so that I could check > the computer the user is on and not make them enter a > username and password if they are already logged in to the > domain. I huess I would have to use Java Script for > this. Any ideas here? > > Thank you in advance. > > Jason Tesser > Web/Multimedia Programmer > Northland Ministries Inc. > (715)324-6900 x3050 > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list > From woodsplitter at rocketmail.com Sat Nov 15 01:27:22 2003 From: woodsplitter at rocketmail.com (David Rushby) Date: 14 Nov 2003 22:27:22 -0800 Subject: Help with Kinterbasdb SQL Error -206 Column unknown References: Message-ID: <7876a8ea.0311142227.175e6315@posting.google.com> "R Baumann" wrote in message news:... > I'm a newbie with Python, and trying to connect to the Interbase/Firebird > 'EMPLOYEE.GDB' file to play with it. [but] > OperationalError: (-206, 'Unable to determine field precison from system > tables: Dynamic SQL Error. SQL error code = -206. Column unknown. > FIELD_SPEC.RDB$FIELD_PRECISION. At line 1, column 19.. ') Here: http://sourceforge.net/forum/message.php?msg_id=2287846 From emile at fenx.com Sun Nov 2 03:14:34 2003 From: emile at fenx.com (Emile van Sebille) Date: Sun, 2 Nov 2003 00:14:34 -0800 Subject: xmlrpc via local proxy References: Message-ID: "Ben" wrote in message news:d99e1341.0311012336.1eb95116 at posting.google.com... > Hi all, > > I'm trying to connect to URL such as http://betty.userland.com through > my LAN proxy. I've read earlier postings on this newsgroups but still > i haven't been able to figure out the way to do it. It doesn't look so > simple. It's very easy to do it using httplib and urllib but xmlrpc > looks a bit complicated. Can someone tell me if there is an easy way > around this problem? > > My code is like this: > > import xmlrpclib > > betty = xmlrpclib.Server("http://betty.userland.com") > print betty.examples.getStateName(32) > Results from pasting exactly this: ActivePython 2.3.2 Build 230 (ActiveState Corp.) based on Python 2.3.2 (#49, Oct 24 2003, 13:37:57) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import xmlrpclib >>> >>> betty = xmlrpclib.Server("http://betty.userland.com") >>> print betty.examples.getStateName(32) New York >>> This is from behind a MonMotha iptables firewall configured with Squid as transparent proxy. So, it works for me... ;-) Emile van Sebille emile at fenx.com From peter at engcorp.com Mon Nov 3 00:45:16 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Nov 2003 00:45:16 -0500 Subject: Experienced programmer evaluating Python References: Message-ID: <3FA5EB6C.A9E480D0@engcorp.com> "Michael L. Labbe" wrote: > > So, to answer your question, can I amicably not distribute my source code or > Python's alongside the binary distribution? :) Have you actually tried to read the license? If so, and you haven't got an answer to the above question, perhaps you would be so good as to post the relevant sections and try to explain what it is you don't understand about them. That way at least someone could consider improving the license (or maybe making some notes to go with it) for a later time. The last time I read the license, it was quite clear on the areas touching on your question, so I'm surprised it wasn't equally clear for you. -Peter From jfranz at neurokode.com Wed Nov 26 13:05:23 2003 From: jfranz at neurokode.com (Jon Franz) Date: Wed, 26 Nov 2003 13:05:23 -0500 Subject: Database connect / PDO References: <3FC248D1.3090603@ghaering.de> <030d01c3b2d9$4220a970$7401a8c0@voidmk9> <3FC3323A.3050209@egenix.com> <046d01c3b37e$f74fd000$7401a8c0@voidmk9> <3FC3BACB.9090705@egenix.com> <04ca01c3b3bc$00f7a8c0$7401a8c0@voidmk9> <3FC47788.2070700@egenix.com> Message-ID: <052c01c3b447$dd672cf0$7401a8c0@voidmk9> > Ah, now I understand: for VARCHAR columns, that information is > available in the precision field of .descpription. It may sound > like the wrong entry, but that's where ODBC put's this > information. Doh, it looks like you found my source of confusion though. > OTOH, what the optional description entries really mean is not > defined anywhere in the DB API. Perhaps we should fix that (on > the db-sig mailing list where these discussions usually happen) ?! I was ready to mention this today, I'll move this to the db-sig list. Good catch :) ~Jon Franz NeuroKode Labs, LLC From tim at zope.com Mon Nov 24 18:39:01 2003 From: tim at zope.com (Tim Peters) Date: Mon, 24 Nov 2003 18:39:01 -0500 Subject: need object crafts csv module pre-compiled for 2.3 In-Reply-To: <68aadb4a.0311241514.21498f8c@posting.google.com> Message-ID: [rabbits77] > I need a binary version of object craft's csv > parser(http://www.object-craft.com.au/projects/csv/) for 2.3. For which machine architecture and operating system? > I do not have the appropriate C environment for Windows and getting > one is an impossibility(in the short term anyway). I am working on a > project which uses this module. The project needs to work under 2.3 > but this module is used so extensively refactoring the code to use > another parsing method would be an undertaking that I would prefer > not to do at the moment and instead concentrate on other areas of the > code. ... Well, this just gets more confusing. Are you aware that a very capable csv module comes with Python 2.3? You don't have to do anything to get it -- it's already there. It started with Dave Cole's module (which you linked to above), and Skip Montanaro did a lot of work on it after. So is there a reason you can't use the csv module that comes with Python 2.3? http://www.python.org/doc/current/lib/module-csv.html From FBatista at uniFON.com.ar Thu Nov 6 13:50:43 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 6 Nov 2003 15:50:43 -0300 Subject: prePEP: Decimal data type Message-ID: Aahz wrote: #- >#- >2. The value could be of the type: #- >#- > #- >#- > - another Decimal #- >#- > - int or long #- >#- > - float #- >#- > - string #- >#- #- >#- Also a tuple of int/longs. #- > #- >I didn't include that in the prePEP because it seems that the actual #- >implementation support this just to dec == #- Decimal(repr(dec)), for every #- >Decimal as dec. #- > #- >Has any other advantage? #- #- Yes: it means that someone who has numeric values #- representing a Decimal #- does not need to convert them to a string. Ok. I'll modify the item 2. . Facundo From mcfletch at rogers.com Mon Nov 17 17:12:04 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 17 Nov 2003 17:12:04 -0500 Subject: Origin of the term "first-class object" In-Reply-To: <8ef9bea6.0311171335.356a7af6@posting.google.com> References: <8ef9bea6.0311171335.356a7af6@posting.google.com> Message-ID: <3FB947B4.1080502@rogers.com> Hung Jung Lu wrote: >Hi, > >Does anybody know where this term comes from? > >"First-class object" means "something passable as an argument in a >function call", but I fail to see the connection with "object class" >or with "first-class airplane ticket". I just find the name a bit >strange. Also, if there are first-class objects, what would the >second-class objects or economy/tourist class objects be? :) > > "Second class citizens" are those denied the rights afforded to "first class citizens". In this context, first class objects are those which can participate in the (object) environment in the same manner as any other "normal" object. In many languages, classes are not able to be processed in the same manner as regular objects (e.g. being passed into functions, introspected for their type, holding properties). HTH, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From logan at phreaker.nospam Sat Nov 29 12:46:48 2003 From: logan at phreaker.nospam (Logan) Date: Sat, 29 Nov 2003 18:46:48 +0100 Subject: HOWTO: Python 2.3 on Fedora Core 1 Linux References: Message-ID: On Wed, 26 Nov 2003 03:51:36 +0100, Logan wrote: > > Installing wxPython with wxGTK (Python bindings for wxWindows) > > > ... ... ... > > > ../configure --with-gtk \ > --prefix=$WXPREF \ > --enable-rpath=$WXPREF/lib \ > --with-opengl \ > --enable-geometry \ > --enable-optimise \ > --enable-debug_flag \ > --with-libjpeg=builtin \ > --with-libpng=builtin \ > --with-libtiff=builtin \ > --with-zlib=builtin \ > --enable-gtk2 \ > --enable-unicode \ > There seems to be a problem with wxPython on Fedora Core 1 Linux, if you install it as described above (s. main posting). E.g. when right clicking on a TextCtrl, no popup-window appears but the script crashes (seg fault). (More on this: s. the mailing list for wxPython.) To avoid this (i.e. the seg faults), use the following to configure wxGTK (instead of the above): ../configure --prefix=$WXPREF \ --enable-rpath=$WXPREF/lib \ --with-opengl \ --enable-geometry \ --enable-optimise \ --enable-gtk2 \ --enable-unicode \ L. -- mailto: logan at phreaker(NoSpam).net From aleax at aleax.it Thu Nov 13 12:13:16 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Nov 2003 17:13:16 GMT Subject: conceiling function calls.. References: Message-ID: Carlo v. Dango wrote: > It is possible to conceil access to methods using the "property()" > function so method access looks like field access.. is the same possible > for functions (not taking any args... ) It's possible as long as the functions are accessed as attributes of some object -- it may be horrible, but you CAN, if you wish, write a __getattribute__ for the "some object" to force any access to the attribute to become a CALL to that attribute. Thankfully, it at least can't be done for access to barenames. You could, of course, wrap the function into an object (of the same name if you wish) that calls it whenever "an attribute of that name" is accessed (SHUDDER). Alex From s-rube at uselessbastard.net Mon Nov 17 08:13:39 2003 From: s-rube at uselessbastard.net (Eric Williams) Date: Mon, 17 Nov 2003 14:13:39 +0100 Subject: trouble with os.path.exists() and wildcards References: Message-ID: Fernando Rodriguez wrote: > Hi, > > How can I check for the xistence of any file that matches a wildcard? > > For example: ppis-*.iss > > os.path.exists() doesn't expand the wildcard... have you taken a look at glob.glob? import glob, os dirname="." filespec="ppis-*.iss" print glob.glob(os.path.join(dirname, filespec)) cya, Eric -- --- s- should be removed to contact me... From dman at dman13.dyndns.org Tue Nov 18 15:08:21 2003 From: dman at dman13.dyndns.org (dman at dman13.dyndns.org) Date: Tue, 18 Nov 2003 20:08:21 GMT Subject: xml.dom - reading from a file References: Message-ID: On Tue, 18 Nov 2003 13:58:47 +0000 (UTC), Magnus Lie Hetland wrote: > In article , Bengt Richter wrote: >>On Mon, 17 Nov 2003 09:54:37 GMT, Alex Martelli wrote: >> >>>sashan wrote: >>> >>>> Is the way to use DOM for an xml file as follows: >>>> 1) Read the file into a string >>>> 2) Call xml.dom.minidom.parseString(string) >>> >>>It's one way, but xml.dom.minidom.parse(f) is generally better. f can >>>be a filename OR a file object open for reading. >>> >>That reminds me ... >> >>Is there a BDFL pronouncement or dev consensus on implementation of >>accepting either filename or file-object? > [snip] > > The standard in such cases is usually the "leap before you look" > idiom, I should think, using try/except and catching signature-related > exceptions. In this case you might try to call read() and revert to > opening the file if there is no read method. Another ordering would be to make the parameter a file, without trying to read first : def my_function( f ) : try : f = file(f, "r") except TypeError : pass f.read() If 'f' is a valid path, then you'll have an open file. If it is already a file you'll get a type error ("coercing to Unicode: need string or buffer, file found"). If it is neither, then the .read() will fail. -- Q: What is the difference between open-source and commercial software? A: If you have a problem with commercial software you can call a phone number and they will tell you it might be solved in a future version. For open-source sofware there isn't a phone number to call, but you get the solution within a day. www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From joe.flynt at mail.portland.co.uk Sat Nov 8 17:49:44 2003 From: joe.flynt at mail.portland.co.uk (Joe Flynt) Date: 8 Nov 2003 14:49:44 -0800 Subject: displaying properly formatted output of ipconfig.exe Message-ID: <601be7f8.0311081449.24b3f7e2@posting.google.com> I'm try to display the output of ipconfig.exe to the web browser using: Apache/2.0.48 (Win32) mod_python/3.1.2b Python/2.3.2 but when I view http://server/cgi-bin/test.py i get the following format of output: ['\r\n', 'Windows IP Configuration\r\n', '\r\n', etc. How do I get it to display the same output as if I had executed the program in cmd.exe? This is the source of test.py: #!C:\Python23\python.exe import os print "Content-type: text/html\r\n\r\n" cmdpipe = os.popen("ipconfig","r") lines = cmdpipe.readlines() print lines From curty at freeze.invalid0 Sat Nov 22 12:02:47 2003 From: curty at freeze.invalid0 (Curt) Date: 22 Nov 2003 17:02:47 GMT Subject: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com> <3FBC2025.B2A33B6F@alcyone.com> <87d6bncbaj.fsf@einstein.electron.net> <3FBD3D6F.E4068821@alcyone.com> <878ymad3ga.fsf@einstein.electron.net> <3FBD6419.A5A863C8@alcyone.com> <874qwyaqqj.fsf@einstein.electron.net> <87znepa954.fsf@einstein.electron.net> <3FBE897B.B75537F0@alcyone.com> Message-ID: On Fri, 21 Nov 2003 13:54:03 -0800, Erik Max Francis wrote: > Curt wrote: > > No, he didn't contrive an example. Please don't invent things. > I posted another example, totally unrelated to your flirty/curty Oh yes, you did. Was that the contrived example he was referring to? I actually thought he was alluding to your contrived example which was a variation on the theme of my contrived example. Why did I think that? Let's go back to the context of the whole shebang which you've cut. He quotes you, then me, then speaks out himself: You: "You don't really think the sequence [flirty, curty, curty, flirty] is sorted, do you?" Me: "Well, you did do something to the sample for which you fail to find a more descriptive word than "tweak"." Him: "He contrived an example that demonstrated his point." Then I say the following thing, which you truncated: "No, he didn't contrive an example. Please don't invent things. He tooked my perfectly good and reasonable example of a file containing redundant entries and "tweaked" it in order to make the entries of type "curty" contiguous. Well, the whole thing is not as clearly a case of bad reading as you say it is. > nonsense, that demonstrated that uniq could do something meaningful with > a totally unsorted file. Please read things. From mk at net.mail.penguinista Fri Nov 7 05:38:51 2003 From: mk at net.mail.penguinista (=?UTF-8?B?0LTQsNC80ZjQsNC9INCzLg==?=) Date: Fri, 07 Nov 2003 11:38:51 +0100 Subject: web server - accept() method References: Message-ID: <3fab763b@news.mt.net.mk> > Just trying to figure out what the accept() method in socket.py does. On Unix you can check "man 2 accept", or even beter try to find the book ?UNIX Network Programming? by Richard W. Stevens. Its a great book > Here accept() returns newSock and addr. In my case "addr" holds the > value something like: ('127.0.0.1', 2571). What is 2571? This value > keeps changing each time i make a connection to above webserver. What > does this mean? That's the client address and port number. > And also what is "newSock"? It holds value such as: > > What do i mean by this? newsock is a "socket", this one you use for communicating with the client. The original socket is a listening one only... -- ?????? (jabberID:damjan at bagra.net.mk) The NOC says: echo '16i[q]sa[ln0=aln100%Pln100/snlbx]sbA0D4D465452snlbxq'|dc From http Mon Nov 24 16:55:46 2003 From: http (Paul Rubin) Date: 24 Nov 2003 13:55:46 -0800 Subject: Delete common entries between two dictionaries References: <4Guwb.7197$9O5.6638@fed1read06> Message-ID: <7x8ym55t3x.fsf@ruckus.brouhaha.com> "Amy G" writes: > Now that I have the two, I want to delete each entry from one that the two > have in common, leaving only those that are unique to the dictionary? > > Say I have a dictionary called domains_black > and another domains_white... for k in domains_white(): if k in domains_black: del domains_black[k] From geert at cs.uu.nl Tue Nov 4 03:32:38 2003 From: geert at cs.uu.nl (G.J.Giezeman) Date: Tue, 04 Nov 2003 09:32:38 +0100 Subject: nearest neighbor in 2D In-Reply-To: <7i65i2yqun.fsf@enark.csis.hku.hk> References: <7i65i2yqun.fsf@enark.csis.hku.hk> Message-ID: Isaac To wrote: >>>>>>"John" == John Hunter writes: > > > John> Given a new point x,y, I would like to find the point in the list > John> closest to x,y. I have to do this a lot, in an inner loop, and > John> then I add each new point x,y to the list. I know the range of x > John> and y in advance. > > John> One solution that comes to mind is to partition to space into > John> quadrants and store the elements by quadrant. When a new element > John> comes in, identify it's quadrant and only search the appropriate > John> quadrant for nearest neighbor. This could be done recursively, a > John> 2D binary search of sorts.... > > By recursion your solution would work in O(log n) time. The construction > would take O(n log n) time. Unluckily, it can return the wrong point, as > the nearest point within the nearest quadrant might not be the nearest > point. > > The problem is a well-studied basic computational geometry problem, although > I don't really know any Python code that actually do it. Try to look at the > web for "Voronoi diagrams" and "radial triangulation" to understand how to > solve it properly in the above mentioned (perhaps randomized) time > complexity. > > Regards, > Isaac. A solution in C++ is using the CGAL-library (www.cgal.org). Look in the index of the basic library and search for 'nearest'. It will point you to Delaunay triangulations, which, together with a triangulation hierarchy, will give O(log n) time complexity, except in pathological cases. You can call C++ code from python. B.t.w., there will be a new release of the CGAL library very soon (probably this week). From phil at riverbankcomputing.co.uk Wed Nov 12 13:25:24 2003 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 12 Nov 2003 18:25:24 +0000 Subject: GUI - Qt Designer In-Reply-To: References: Message-ID: <200311121825.24988.phil@riverbankcomputing.co.uk> On Wednesday 12 November 2003 6:04 pm, John Bradbury wrote: > Is there any way to take the output produced by Qt designer (or any other > GUI designer) and use it in Python to create a screen? There must be a > better way of creating screens than having to use the TkInter routnes and > add every widget one by one in the program. Use the pyuic utility that comes with PyQt. Phil From philh at invalid.email.address Fri Nov 7 13:36:23 2003 From: philh at invalid.email.address (phil hunt) Date: Fri, 7 Nov 2003 18:36:23 +0000 Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <3fa6a75e$0$12666$fa0fcedb@lovejoy.zen.co.uk> Message-ID: On Fri, 07 Nov 2003 10:50:20 +0000, Richie Hindle wrote: > >[Richie] >> Your website (http://www.totalrekall.co.uk) says "The GPL version would be >> free for non-commercial use", which is a contradiction. > >[Phil] >> There's nothing innacurate or contradictory in that statement. After >> all, the GPL *is* "free for non-commercial use"; it just happens to >> be free for commerical use as well -- and the website doesn't say >> that it isn't, it just omits to mention that it is. > >You are right of course. Let me be more precise (addressing John again): > >The words used on your website seem to me to imply that the GPL version >could not be used commercially. If that is the intention of those words, >you are mistaken about either the meaning of the GPL, or your power as a >copyright owner to control the application of the GPL to your code. If >you release your code under the GPL, it can be used commercially, and you >cannot change that. > >(I vote Phil for pedant of the week. 8-) Weeee! I get an award! -- "It's easier to find people online who openly support the KKK than people who openly support the RIAA" -- comment on Wikipedia (Email: , but first subtract 275 and reverse the last two letters). From tim.one at comcast.net Sat Nov 15 03:58:53 2003 From: tim.one at comcast.net (Tim Peters) Date: Sat, 15 Nov 2003 03:58:53 -0500 Subject: Python's simplicity philosophy In-Reply-To: Message-ID: [Andrew Dalke] > There's also a __reduce__ and __reduce_ex__ in the pickle > protocol. See http://www.python.org/peps/pep-0307.html . > It's by far the most mentioned 'reduce' in the Python standard > library. Does it have anything to do with the 'reduce' function? > Not that I can tell. It doesn't -- reduce() and __reduce__() have no intersection. > But I can't find an explaination for that choice of a name. Well, this comes from the tradition that thought it made good sense to call a serialized object representation "a pickle". Applying the same kind of real-life common sense, what do you call the act of changing a real-world object, like a refrigerator or a wide-screen plasma TV, into a string, a (function, args) tuple, or a (function, args, state) tuple sufficient to reproduce the fridge or TV? Of course everyone calls that "reducing the refrigerator" or "reduce_exing the wide-screen plasma TV". Hence the kind of people who thought "pickle" was a good name also thought it was a good idea to stick underscores around "reduce" and "reduce_ex" . Possibly more likely is that they knew they wouldn't remember how to spell __cerealeyes__. Give a pro a reduce and he can re-pro-duce. From stephenlee at exe-coll.ac.uk Mon Nov 10 04:34:05 2003 From: stephenlee at exe-coll.ac.uk (Steve Lee) Date: 10 Nov 2003 01:34:05 -0800 Subject: Request for simple a customisable Python editor References: Message-ID: <22107734.0311100134.1dcc237@posting.google.com> > Much better would be to allow the editor used to be chosen by the user, > and supply a reasonable default. Editors are powerful beasts, and > forcing someone familiar with one to use a different one for your > application is not a user-friendly design choice. > > Pick an editor that you think is a good default, but invoke it with a > command-line only, *don't* build it into your application. That way, > you can provide a customisation option to change the editor command > line, and the user can substitute their favourite editor if they choose. A nice idea and I agree that we all have our own fave editor. However I had thought of making the opening of the data from the database 'look' similar to opening a file which suggests tweeking the 'open' UI of an existing editor. I think your idea requires selecting files first and then invoking the editor. I'll give it some thought as I am not really opposed to such a method of opening files - thanks for the idea. Steve From rainerd at eldwood.com Thu Nov 27 13:36:00 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Thu, 27 Nov 2003 18:36:00 GMT Subject: python-unicode doesn't support >65535 symbols? References: <2c60a528.0311270946.4233a55c@posting.google.com> Message-ID: Andrew Clover wrote: > gabor wrote: > >> so text[3] (which should be \U00010330), >> was split to 2 16bit values (text[3] and text[4]). > > The default encoding for native Unicode strings in Python in UTF-16, > which cannot hold the extended planes beyond 0xFFFF in a single > character. That's not quite right. UTF-16 encodes unicode characters as either single 16 bit values and pairs of 16 bit values. However, one character is still one character. Python makes the mistake of exposing the internal representation instead of the logical value of unicode objects. This means that, aside from space optimization, unicode objects have no advantage over UTF-8 encoded plain strings for storing unicode text. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From bokr at oz.net Sat Nov 22 23:41:21 2003 From: bokr at oz.net (Bengt Richter) Date: 23 Nov 2003 04:41:21 GMT Subject: code blocks in Python References: <8ef9bea6.0311221215.804bdb3@posting.google.com> <8ef9bea6.0311221913.427cb53e@posting.google.com> Message-ID: On 22 Nov 2003 19:13:19 -0800, hungjunglu at yahoo.com (Hung Jung Lu) wrote: >"John Roth" wrote in message news:... >> Just some random observations. First, I'm not at all clear on >> what you want it to do. Some examples would be helpful. There >> are entirely too many different ways I could interpret your reference >> to metaprogramming for me to understand the usage you have in >> mind. > >codeblock A: > x = 1 > y = 2 > >codeblock B: > z = x + y > print z > >exec A >exec B > >This will be equivalent to writing the program: > >x = 1 >y = 2 >z = x + y >print z > >> If you want it as a replacement for the badly crippled lambda statement, >> then I think there's quite a bit of interest. What's holding that up is >> syntax, and an appropriate syntax isn't entirely obvious. > >Lambda is a totally different thing. Lambda is an anonymous >*function*. I emphasize *function* because functions take parameters >and return values. Code blocks are, well, blocks of code. No >parameters, no nothing else. Simple and plain blocks of code. Once you >have codeblocks, you wire them anyway you want. Think of them as >macros in C++, only that in Python you can wire them dynamically >during runtime. Python already does that. It's just that you need the >compile() function, your code string is not compiled until the >compile() function is executed, and the resulting object type is >"Code" (which is a fine name, even if the new keyword were >"codeblock".) Have you tried the compile() function? > I note that: >>> compile('a=123','','single') >>> import dis >>> dis.dis(compile('a=123','','single')) 1 0 LOAD_CONST 0 (123) 3 STORE_NAME 0 (a) 6 LOAD_CONST 1 (None) 9 RETURN_VALUE >>> def foo(): a=123 ... >>> dis.dis(foo) 1 0 LOAD_CONST 1 (123) 3 STORE_FAST 0 (a) 6 LOAD_CONST 0 (None) 9 RETURN_VALUE So which code will you want when the compiler compiles an in-context block? Will you want it to be a first-class object? Should you be able to pass the code-block name to an arbitrary function or bind it globally, like you can with compile's output? Are you willing to forego the optimized local access? Or want to exec it later from anywhere? What should happen? You could call for magic creation of special closures so that an exported code block would still refer back to the local name space (which BTW could be interesting for generators to yield, to give external access to their internal state). And what should assigning a function local codeblock to a global mean? Maybe creating a one-shot generator where the codeblock could be used to preset state for a single ordinary function call that re-uses previous state. Or should it just die like a weak reference? IOW, there are some things to think about, because the semantics could get interesting ;-) It would be nice to have efficient local blocks, so you could write exec(locals()[switcharg]) or perhaps some more efficient builtin switch/case thing using them. The efficiency of a large jump table (dict or tuple/list based) vs a chain of elifs is a good motivation for some uses, but I wonder how common/important they are. Regards, Bengt Richter From python at meyer-luetgens.de Wed Nov 5 09:03:19 2003 From: python at meyer-luetgens.de (=?ISO-8859-1?Q?Jan-Erik_Meyer-L=FCtgens?=) Date: Wed, 05 Nov 2003 15:03:19 +0100 Subject: dictionary keys, __hash__, __cmp__ In-Reply-To: <7h3fzh3hsb7.fsf@pc150.maths.bris.ac.uk> References: <7h3fzh3hsb7.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson wrote: > Jan-Erik Meyer-L?tgens writes: >> >> 3. "If a class does not define a __cmp__() method it >> should not define a __hash__() operation either." >> >> >>Can I asume that: >> >> -- I can savely ignore the 3rd statement, because python >> falls back to cmp(id(obj1), id(obj2)), if __cmp__() >> is not defined. > > > Don't understand. > Ok, let me ask the following question: What is the reason for that rule? -- Jan-Erik From Henrik.Weber at sdm.de Wed Nov 26 09:56:07 2003 From: Henrik.Weber at sdm.de (Henrik Weber) Date: 26 Nov 2003 06:56:07 -0800 Subject: Pychecker under Windows References: <153fa67.0311252016.2e02b575@posting.google.com> Message-ID: <44254d3d.0311260656.612e1b79@posting.google.com> kylotan at hotmail.com (Kylotan) wrote in message news:<153fa67.0311252016.2e02b575 at posting.google.com>... > Is there a practical way to use Pychecker in Windows? It doesn't work > under IDLE. (In fact, it seems to end up breaking everything, and > every subsequent statement and expression I execute gets ignored.) > Running it from the Python interpreter in DOS means everything scrolls > off the screen. Ideally I'd like to redirect it to a file, or be able > to use it in IDLE. I don't know what kind of problem pychecker causes with IDLE but I have managed to plug it into Pythonwin. There should be a similar way to make it work with IDLE. You can find the thread here: http://groups.google.de/groups?hl=de&lr=&ie=UTF-8&selm=44254d3d.0308050441.3ae97677%40posting.google.com -- Henrik From ville.spammehardvainio at spamtut.fi Thu Nov 13 15:40:35 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 13 Nov 2003 22:40:35 +0200 Subject: Too much builtins (was Re: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <653b7547.0311121826.65b6b2d4@posting.google.com> Message-ID: Douglas Alan writes: [reduce] > >> If someone can't understand this quickly, then they shouldn't be > >> programming! > > > Again, it's not "can't", it's whether they need to or not. > > If you don't want to learn a cool concept that will only take you 60 > seconds to learn, then you shouldn't be programming! Or you can stick > to loops. As far as reduce goes, ppl will undoubtedly take a look at the description, understand it in well under 60 seconds, can't think of any use for the feature during the next 60 seconds (that wouldn't be clearer with explicit iteration), and forget it soon after turning the page. I didn't forget it, just wondered why such an oddball feature was a builtin. Obviously reduce can rock someone's world, but life is too short to bother if it doesn't rock yours. > and powerful feature with a slew of specific, tailored features. If > reduce() can be relegated to a library or for the user to implement > for himself, then so can sum(). If the language is to only have one, > it should be reduce(). I also think that reduce, sum, map and filter (and lots of others, __builtins__ has *too much stuff*) should be removed from builtins, but that will probably take some time (1997 years?). LC's and genexpes will take care of most of that stuff. And people can always do: from funtional import * # map, filter, reduce, curry, ... (I want lots of these :) There are also tons of functions that should be in sys, math or whatever: reload, repr, divmod, max, min, hash, id, compile, hex... What's your pet deprecation candidate? I have always thought `backticks` as repr has got to be the most useless feature around. -- Ville Vainio http://www.students.tut.fi/~vainio24 From missive at frontiernet.net Sun Nov 30 11:13:15 2003 From: missive at frontiernet.net (Lee Harr) Date: Sun, 30 Nov 2003 16:13:15 GMT Subject: custom sorting and __cmp__ Message-ID: Let's say I have a class class A: def __init__(self, level): self.level = level and I want to put some of these in a list and sort the list by level a1 = A(1) a2 = A(2) l = [a1, a2] l.sort() Am I better off creating a __cmp__ method for my class or making a cmp function to pass to sort? My thought was that __cmp__ would be perfect, but then I started thinking about this ... >>> class A: ... def __init__(self, level): ... self.level = level ... def __cmp__(self, other): ... if self.level > other.level: ... return 1 ... elif self.level < other.level: ... return -1 ... else: ... return 0 ... >>> a1 = A(1) >>> a2 = A(2) >>> class C: ... pass ... >>> c = C() >>> a1 == a2 False >>> a1 < a2 True >>> a1 == c Traceback (most recent call last): File "", line 1, in ? File "", line 5, in __cmp__ AttributeError: C instance has no attribute 'level' Should I be catching comparisons to objects that do not have my 'level' attribute and falling back to id comparison? Or am I worried about nothing (YAGNI :o) ? Is this related in any way to interfaces? From sholden at holdenweb.com Wed Nov 26 01:17:47 2003 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 26 Nov 2003 01:17:47 -0500 Subject: Pychecker under Windows References: <153fa67.0311252016.2e02b575@posting.google.com> Message-ID: "Kylotan" wrote ... > Is there a practical way to use Pychecker in Windows? It doesn't work > under IDLE. (In fact, it seems to end up breaking everything, and > every subsequent statement and expression I execute gets ignored.) > Running it from the Python interpreter in DOS means everything scrolls > off the screen. Ideally I'd like to redirect it to a file, or be able > to use it in IDLE. > You can redirect python output to a file from the Windows command line. The only caveat is for *some* command processors (NT in particular, IIRC) output redirection only works if you explicitly call the python interpreter (i.e. use the command "python prog.py > file.out") rather than implicitly call it (i.e. use the command "prog.py > file.out"). regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ "I'd spoll my own name wring if I didn't have a spilling chocker" From aahz at pythoncraft.com Sun Nov 9 12:19:45 2003 From: aahz at pythoncraft.com (Aahz) Date: 9 Nov 2003 12:19:45 -0500 Subject: Why text-only? (was Re: Leo + Python: the ultimate scripting tool: Conclusion) References: Message-ID: In article , Edward K. Ream wrote: > >It seems to me that simulating Leo on a character-cell display is >going to be all work and no gain. I have no interest in designing a >dumbed-down model for Leo that would work in paleolithic environments. >Besides, Emacs probably has a curses mode. Why would I want to compete >with that? That's fine, although for me you're competing with vi[m]. There are two reasons why I stick with my requirement for text-only systems: * As I said earlier, I do much of my work from text consoles, and much of that is also remote. I think trying to run GUIs over Net connections is poor use of bandwidth. Not to mention the fact that until a month ago, my only Net access was still direct-dial shell (yes, vt100 emulator, no PPP). Even now that I do have DSL, I still do much of my GUI browsing (when forced to use JavaScript) with images turned off. * Requiring a text-only system is a reasonable proxy for requiring a keyboard-centric system, because text-only systems by definition have to work with a keyboard. Too many GUI-based systems have at least one oddball corner that just doesn't work well with the keyboard, and it's invariably one of those corners that I need to be productive. This is an old argument, of course. I've been using the .sig I'm including below for more than five years. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ I surf faster than you do, monkey boy. (My take on Netscape vs. Lynx) From alanmk at hotmail.com Fri Nov 14 09:34:23 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 14 Nov 2003 14:34:23 +0000 Subject: Palindrome References: <20031112223135.29045.00000109@mb-m12.aol.com> <3FB3C016.56BCA546@hotmail.com> <2pi9rvotmcdah2mij27a4mn9ggb9me4t0j@4ax.com> Message-ID: <3FB4E7EF.DC6D9814@hotmail.com> Ron Adam wrote: > I notice right after I posted it, I can simplify the test function a > bit more. > > import re > def palindrome_test(p): > p = p.lower() > p = re.sub(r'\W','',p) > while p and p[:1] == p[-1:]: > p = p[1:-1] > return (len(p) <= 1) Ron, If I were going to follow this approach, I would try to eliminate any copying, like so: def palindrome_test(p): p = p.lower() p = re.sub(r'\W','',p) plen = len(p) for i in xrange(plen/2): if p[i] != p[plen-i-1]: return False return True regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From salvadorindali at gmx.de Sat Nov 29 16:51:51 2003 From: salvadorindali at gmx.de (sven) Date: Sat, 29 Nov 2003 21:51:51 +0000 (UTC) Subject: list: from 2 to 3 dimensions..looking for a nice way Message-ID: I've got a nested list-> a = [[1,'house'],[2,'house'],[3,'garden']] and I want to get one level deeper with the lists having the same value in index value 1 b =[[[1, 'house'], [2, 'house']], [[3, 'garten']]] I' achieving this with an ugly syntax: a = [[1,'house'],[2,'house'],[3,'garden']] b = [[]] b[0].append(a.pop(0)) for id in range(len(a)): if(b[-1][0][1]==a[id][1]): b[-1].append(a[id]) else: b.append([a[id]]) What is the pythonic way to do this? Thanks for any insight From aleax at aleax.it Tue Nov 11 10:07:46 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 11 Nov 2003 15:07:46 GMT Subject: Am I the only one who would love these extentions? - Python 3.0 proposals (long) References: Message-ID: <6X6sb.5586$9_.242826@news1.tin.it> Alexander Schmolck wrote: ... >> > AND, ASSERT, BREAK, CLASS, etc == "AND, ASSERT, BREAK, CLASS, >> > etc".split(", ") >> >> Unfortunately, this breaks the "once, and only once" principle: you >> have to ensure the sequence of words is the same on both sides -- any >> error in that respect during maintenance will cause small or big >> headaches. > > True, but I'd still prefer this one (+ editor macro) in most cases to > (ab)using numbers as symbols (this was my main point; I'm sure I could I'm used to take bus 20 to go downtown. And perhaps some of my ancestors fought in the VII Legio (also known by nicknames such as Gemina and Felix, and not to be confused with the _other_ VII Legio, also known as Claudia and Pia). If using numbers just as arbitrary tags used to distinguish items is "abuse", then there's been enough of that over the last few millennia -- and there's by far enough of it in everyday life today -- that to keep considering it "abuse" is, IMHO, pedantry. All the more so, when we also want our "tags" to have _some_ of the properties of numbers (such as order) though not all (I'm not going to "add" buses number 20 and 17 to get bus number 37, for sure). > also think of various hacks to avoid the duplication and do the the > stuffing in the global namespace implicitly/separately -- if it must go > there at all costs). The main advantage the above has over custom enum > types is that it's immediately obvious. Maybe the standard library should > grow a canonical enum module that adresses most needs. "A canonical enum module" would be great, but the probability that a design could be fashioned in such a way as to make _most_ prospective users happy is, I fear, very low. Anybody's welcome to try their hand at a pre-PEP and then a PEP, of course, but I suspect that enough consensus on what features should get in will be hard to come by. >> Keeping enum values in their own namespace (a class or instance) is >> also generally preferable to injecting them in global namespace, >> IMHO. > > Yep, this would also be my preference. I'd presumably use something like > > DAYS = enum('MON TUE WED [...]'.split()) > > maybe even without the split. Sure, if you have an 'enum' factory function or type you may choose to have it do its own splitting. But if DAYS.MON and DAYS.WED are just strings, so you cannot _reliably_ test e.g. "x > DAYS.WED" in the enumeration order, get "the next value after x", and so on, then I fear your enum will satisfy even fewer typical, widespread requirements than most other proposals I've seen floating around over the years. >> If you want each constant's value to be a string, that's easy: > > Doesn't have to be, strings are just the simplest choice for something > with a sensible 'repr' (since you might want some total order of your > enums a class might be better -- if one goes through the trouble of > creating one's own enum mechanism). I don't think a repr of e.g. 'TUE' is actually optimal, anyway -- "DAYS.TUE" might be better (this of course would require the enum builder to intrinsically know the name of the object it's building -- which again points to a metaclass as likely to be best). But representation has not proven to be the crucial issue for enums in C, and this makes me doubt that it would prove essential in Python; the ability to get "the next value", "a range of values", and so on, appear to meet more needs of typical applications, if one has to choose. Sure, having both (via a type representing "value within an enumeration") might be worth engineering (be that in a roll-your-own, or standardized PEP, for enum). I _think_ the rocks on which such a PEP would founder are: -- some people will want to use enums as just handy collections of integer values, with the ability, like in C, to set FOO=23 in the middle of the enum's definition; the ability to perform bitwise operations on such values (using them as binary masks) will likely be a part of such requests; -- other people will want "purer" enums -- not explicitly settable to any value nor usable as such, but e.g. iterable, compact over predecessor and successor operations, comparable only within the compass of a single enum; -- (many will pop in with specific requests, such as "any enum must subclass int just like bool does", demands on str and/or repr, the ability to convert to/from int or between different enums, and so on, and so forth -- there will be many such "nonnegotiable demands", each with about 1 to 3 proponents); -- enough of a constituency will be found for each different vision of enums to make enough noise and flames to kill the others, but not enough to impose a single vision. This may change if and when Python gets some kind of "optional interface declarations", since then the constraints of having enums fit within that scheme will reduce the too-vast space of design possibilities. But, that's years away. >> class myenum(Enum): >> AND = ASSERT = BREAK = CLASS = 1 >> >> with: >> >> class Enum: __metaclass__ = metaEnum >> >> and: >> >> class metaEnum(type): >> def __new__(mcl, clasname, clasbases, clasdict): >> for k in clasdict: >> clasdict[k] = k >> return type.__new__(mcl, clasname, clasbases, clasdict) > > Yuck! A nice metaclass demo but far too "clever" and misleading for such a > simple task, IMO. I disagree that defining an Enum as a class is "clever" or "misleading" in any way -- and if each Enum is a class it makes a lot of sense to use a metaclass to group them (with more functionality than the above, of course). Of course, values such as 'myenum.ASSERT' should be instances of myenum (that is not shown above, where I made them strings because that's what you were doing -- the only point shown here is that there should be no duplication). >> The problem with this is that the attributes' _order_ in the >> classbody is lost by the time the metaclass's __new__ runs, as >> the class attributes are presented as a dictionary. But if the >> values you want are strings equal to the attributes' names, the >> order is not important, so this works fine. >> >> But many applications of enums DO care about order, sigh. > > If that prevents people from using the above, I'd consider it a good thing > ;) Oh, it's not hard to substitute that with e.g. class myenum(Enum): __values__ = 'AND ASSERT BREAK CLASS'.split() (or, ditto w/o the splitting) so that order is preserved. But then we have to check explicitly at class creation time that all the values are valid identifiers, which is a little bit of a bother -- being able to _use_ identifiers in the first place would let us catch such errors automatically and as _syntax_ errors. Unfortunately, we can't do it without counting, or having an alas very hypothetical construct to mean "and all the rest goes here", as below. >> > in combination with iterators).I'd also like to have the apply-* work >> > in assignments, e.g. ``first, second, *rest = someList``. This would >> > also make python's list destructuring facilities much more powerful. >> >> Yes, I agree on this one. Further, if the "*rest" was allowed to >> receive _any remaining iterable_ (not just necessarily a list, but >> rather often an iterator) you'd be able to use itertools.count() >> and other unbounded-iterators on the RHS. > > Indeed, as I noted in my previous post, iterators and such extensions > would go very well together. Now _that_ is a PEPworthy idea that might well garner reasonably vast consensus here. Of course, getting it past python-dev's another issue:-). Alex From skip at pobox.com Wed Nov 5 18:01:19 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 5 Nov 2003 17:01:19 -0600 Subject: Perl file::find module equivalent in Python? In-Reply-To: References: Message-ID: <16297.33087.332178.345416@montanaro.dyndns.org> Greg> Hi. Does anyone know if there's an equivalent of Perl's file::find Greg> module in Python? It traverses a directory. I've googled Greg> extensively and checked this newsgroup and can't find anything Greg> like it for Python. I've never used file::find, but from your short description ("traverses a directory"), I suspect you're looking for os.listdir, os.path.walk or perhaps glob.glob: listdir(...) listdir(path) -> list_of_strings Return a list containing the names of the entries in the directory. path: path of directory to list The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory. walk(top, func, arg) Directory tree walk with callback function. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), call func(arg, dirname, fnames). dirname is the name of the directory, and fnames a list of the names of the files and subdirectories in dirname (excluding '.' and '..'). func may modify the fnames list in-place (e.g. via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in fnames; this can be used to implement a filter, or to impose a specific order of visiting. No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern, or a mutable object designed to accumulate statistics. Passing None for arg is common. glob(pathname) Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. Skip From mike at nospam.com Mon Nov 3 16:56:21 2003 From: mike at nospam.com (Mike Rovner) Date: Mon, 3 Nov 2003 13:56:21 -0800 Subject: EIBTI References: Message-ID: Emile van Sebille wrote: > What does this mean? Explicit Is Better Than Implicit Try 'python -c "import this"' for The Zen of Python ;) Mike From light at soton.ac.uk Thu Nov 20 10:20:38 2003 From: light at soton.ac.uk (Mark Light) Date: Thu, 20 Nov 2003 15:20:38 -0000 Subject: regular expression to extract text Message-ID: Hi I have a file read in as a string that looks like below. What I want to do is pull out the bits of information to eventually put in an html table. FOr the 1st example the 3 bits are: 1.QEXZUO 2. C26 H31 N1 O3 3. 6.164 15.892 22.551 90.00 90.00 90.00 ANy ideas of the best way to do this - I was trying regular expressions but not getting very far. Thanks, Mark. """ Using unit cell orientation matrix from collect.rmat NOTICE: Performing automatic cell standardization The following database entries have similar unit cells: Refcode Sumformula ------------------------------------------ QEXZUO C26 H31 N1 O3 6.164 15.892 22.551 90.00 90.00 90.00 ------------------------------------------ ARQTYD C19 H23 N1 O5 6.001 15.227 22.558 90.00 90.00 90.00 ------------------------------------------ NHDIIS C45 H40 Cl2 6.532 15.147 22.453 90.00 90.00 90.00 """ From bdesth.nospam at removeme.free.fr Mon Nov 3 06:44:40 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Mon, 03 Nov 2003 12:44:40 +0100 Subject: [OT] thanks a lot... In-Reply-To: References: Message-ID: <3fa63c21$0$27035$626a54ce@news.free.fr> Haoyu Zhang wrote: > Dear Friends, > Thanks so much for your reply. Now I feel much clearer. Especially > Stephen Horne's answer is very clear to the question. And also thanks > a lot for further explanations about builtin objects. > > Best, > haoyu Dear Haoyu, I'm sure that everyone concerned, and specially Stephen Horne, will be glad to know they could help you. But they (and us) would have less trouble relating this post to your question if you had posted this in the same thread as the question !-) Best regards Bruno From asp16 at alu.ua.es Mon Nov 24 17:55:53 2003 From: asp16 at alu.ua.es (Adeodato =?iso-8859-1?Q?Sim=F3?=) Date: Mon, 24 Nov 2003 23:55:53 +0100 Subject: Strange import bug In-Reply-To: <3fc2854a$1@news.iconz.co.nz> References: <3fc2854a$1@news.iconz.co.nz> Message-ID: <20031124225553.GA4352@chistera> * Colin Brown [Tue, 25 Nov 2003 11:30:24 +1300]: My experience with Python is not that large but I'll try to help: > I have instances where Python 2.3.2 import both does not work or error. It > can be demonstrated under Win2k and Linux by doing the following: > 1. Create a subdirectory "abc" > 2. In directory "abc" create a blank "__init__.py" > 3. In directory "abc" create a file "abc.py" containing "print 'this is > abc'" > 4. Interactively run python interpreter > >>> import sys > >>> sys.path.append('./abc') > >>> import abc > It sometimes works for me (in similar situations) if you do: > 5. Interactively run python interpreter > >>> import sys > >>> sys.path.insert(0,'./abc') > >>> import abc > this is abc The first (default) entry in sys.path is '', which means (I think) the current directory. So sys.path.append('./abc') appends after this entry; then, on "import abc", python uses first '' entry, which means it looks under current directory where it finds "abc" which gets imported *as a module*. But, if you place './abc' before '', python will look first *inside* ./abc, considering it a plain directory and not a module. There, under ./abc, it is abc.py, which gets imported by the second "import abc", and *executed*. -- Adeodato Sim? (a.k.a. thibaut) EM: asp16 [ykwim] alu.ua.es | IM: my_dato [jabber.org] | PK: DA6AE621 To be nobody but yourself in a world which is doing its best night and day to make you like everybody else means to fight the hardest battle any human being can fight and never stop fighting. -- e.e. cummings -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 204 bytes Desc: Digital signature URL: From fumanchu at amor.org Sun Nov 30 16:31:48 2003 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 30 Nov 2003 13:31:48 -0800 Subject: Fast attribute/list item extraction Message-ID: Peter Otten wrote: > Following variants are possible: > > # extract an attribute > extract.attr Ick. > extract(name="attr") # necessary when attribute name only > known at runtime Yes, it needs to be runtime-specifiable, for sure. I'd prefer: extract("attr1", "attr2", ... "attrN") returning a tuple, perhaps only if more than one attribute were specified. > extract[1] > extract["key"] Fine. Readable. I'm having a hard time seeing the use cases, given that I find most of them more readable if done with list comprehensions or good ol' for loops. Everyone has their language-addition line-in-the-sand, and this is looking "un-pythonic" to me; it seems to be obscuring code, not revealing it. Given current syntax, I tend to just provide _functions_ to sort() like so: def attr_sort(attrNames, descending=False): """Return a function which can be passed to list.sort().""" # We can't simply try: iteration, because we don't want strings # to be iterated over their characters. So we check type. :( if type(attrNames) not in (type(()), type([])): attrNames = (attrNames, ) def sort_func(x, y): for eachName in attrNames: try: xv = getattr(x, eachName) except AttributeError: diff = -1 else: try: yv = getattr(y, eachName) except AttributeError: diff = 1 else: diff = cmp(xv, yv) if descending: diff = -diff if diff != 0: return diff return 0 return sort_func ...obviously one might further trap the cmp() call, etc. This doesn't really address the implementation of extract() as much as it says, "how would extract() help sort()?" Robert Brewer MIS Amor Ministries fumanchu at amor.org From haris.bogdanovic at zg.htnet.hr Sat Nov 1 16:47:27 2003 From: haris.bogdanovic at zg.htnet.hr (Haris Bogdanovic) Date: Sat, 01 Nov 2003 22:47:27 +0100 Subject: simple echo server In-Reply-To: <3fa3fab9$0$58702$e4fe514c@news.xs4all.nl> References: <3fa3fab9$0$58702$e4fe514c@news.xs4all.nl> Message-ID: <3FA429EF.5090407@zg.htnet.hr> Irmen de Jong wrote: > Haris Bogdanovic wrote: > >> When client is trying to connect to the server everything works fine >> but when server tries to echo what it receieved from client I get >> access denied error. >> Why is that happening ? > > > Because the server has no access? > > No really-- you have to give much more detailed information. > Preferrably the exact code fragment and exact error message > that you're getting. > > --Irmen > It's the example from python docs (socket section). If you have somewhere your personal user account you can try it aswell. Tell me what you managed to do. Thanks Haris From __peter__ at web.de Wed Nov 19 14:46:40 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Nov 2003 20:46:40 +0100 Subject: Using 'string.ljust' to try and hold a fixed width....... References: <2c82369d.0311190538.3789f2a1@posting.google.com> <2c82369d.0311191123.5017eb6d@posting.google.com> Message-ID: John F Dutcher wrote: > Last shot ... then I'll leave you alone...I tried your 'fixedwidth' > function. > Almost predictably....it worked perfectly in IDLE when coded as below: > It has no effect at all when employed in the CGI script however, (the > returned > values do not have trailing spaces) ?? I am now pretty sure that fixedwidth() or str.ljust() are *not* the problem with your cgi script. Step back and look for something *completely* different, e. g.: - Is it an old file that you are checking for the extra spaces? - Do you think that print writes to a file (it can, if you do: print >> destfile, "sometext")? If you cannot track down the bug yourself, shorten the cgi script as much as you can and post it on c.l.py. Try to describe the problem you perceive and make as few implicit assumptions as possible, i. e. "This is my script's output cut and pasted" rather than "It does not do what I want". Peter From edreamleo at charter.net Sat Nov 8 11:19:29 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Sat, 8 Nov 2003 10:19:29 -0600 Subject: Leo + Python: the ultimate scripting tool #4 References: Message-ID: Reasons why Leo and Python work so well together: 4. Leo's nodes naturally separate data from meta-data. The body text of a node is the perfect place data itself (including other scripts). The headline of the node is the perfect place to _describe_ the data. That is, headlines are a natural place for meta-data. Scripts can use this meta-data in many creative ways. I first saw the power of points 2, 3 and 4 when devising regression tests for Leo. This leads us to... Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From gerrit at nl.linux.org Tue Nov 18 08:25:30 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 18 Nov 2003 14:25:30 +0100 Subject: PEP 321: Date/Time Parsing and Formatting In-Reply-To: References: Message-ID: <20031118132530.GB3790@nl.linux.org> Paul Moore wrote: > Gerrit Holl writes: > > Python 2.3 added a number of simple date and time types in the > > ``datetime`` module. There's no support for parsing strings in various > > formats and returning a corresponding instance of one of the types. > > This PEP proposes adding a family of predefined parsing function for > > several commonly used date and time formats, and a facility for generic > > parsing. > > I assume you're aware of Gustavo Niemeyer's DateUtil module > (https://moin.conectiva.com.br/DateUtil)? I was not, actually. Thanks for the link. It looks like a very comprehensive library! The example actually calculates the next time I'm having birthday on friday the 13th :) > [After reading through this PEP and commenting, I'd say that my > preference (which may not be Gustavo's!) would be to add dateutil to > the standard library, with the following changes/additions: Sounds like a good idea. > > > * Formats commonly written by humans such as the American > > "MM/DD/YYYY", the European "YYYY/MM/DD", and variants such as > > "DD-Month-YYYY". > > UK format DD/MM/YYYY is worth adding (in my UK-based opinion :-)) But > you can get all of these via strptime (wrapped to return a datetime > value). I don't think so. One you just as well add the German "D.M.YY", and many others. > > 3) Add a separate module (possible names: date, date_parse, parse_date) > > or subpackage (possible names: datetime.parser) containing parsing > > functions:: > > > > import datetime > > d = datetime.parser.parse_iso8601("2003-09-15T10:34:54") > > I'd go for this option. It depends on how comprehensive it would be. Gustavo's DateUtil module does a lot more than this PEP suggests. For an implementation of this PEP, I think a seperate module is not necessary. For DateUtil, I think it is. yours, Gerrit. -- 185. If a man adopt a child and to his name as son, and rear him, this grown son can not be demanded back again. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From aleaxit at yahoo.com Tue Nov 11 16:39:07 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 11 Nov 2003 21:39:07 GMT Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: <%Fcsb.10225$hV.422723@news2.tin.it> Bob Gailer wrote: ... > The use of zip(seq[1:], [:-1]) to me is more obscure, and Very obscure indeed (though it's hard to say if it's _more_ obscure without a clear indication of what to compare it with). Particularly considering that it's incorrect Python syntax, and the most likely correction gives probably incorrect semantics, too, if I understand the task (give windows of 2 items, overlapping by one, on seq?). > memory/cpu-expensive in terms of creating 3 new lists. Fortunately, Hettinger's splendid itertools module, currently in Python's standard library, lets you perform this windowing task without creating any new list whatsoever. Wen seq is any iterable, all you need is izip(seq, islice(seq, 1, None)), and you'll be creating no new list whatsoever. Still, tradeoffs in obscurity (and performance for midsized lists) are quite as clear. Alex From fredrik at pythonware.com Sat Nov 22 09:59:59 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Nov 2003 15:59:59 +0100 Subject: "compile()" portability References: Message-ID: Just wrote: > > I would like to know if executing: > > > > c = compile('a=5\nprint a','','exec') > > > > on a Linux box, then pickling+beaming the result on a Windows box, will give > > me the expecting result: > > > > >>> exec(c) > > 5 > > > > In other words, does 'compile()' generate platform-dependent code? > > If you mean "marshal" instead of "pickle", and use the same (major) > Python version on both ends, then yes. to make sure both sites are using the same byte code revision, check the imp.get_magic() string. something like this should work: code = compile(...) data = imp.get_magic() + marshal.dumps(code) ... magic = imp.get_magic() if not data.startswith(magic): raise ValueError("cannot run this bytecode") code = marshal.loads(data[len(magic):]) (len(magic) is currently 4, and will probably remain so for the foreseeable 2.X future, but one never knows what happens in 3.X...) From st06550 at erasmus.uib.no Sun Nov 30 15:12:01 2003 From: st06550 at erasmus.uib.no (Stein Boerge Sylvarnes) Date: 30 Nov 2003 20:12:01 GMT Subject: List files without extension, was: Bug in glob.glob for files w/o extentions in Windows References: <0Zfyb.48050$dl.2119318@twister.southeast.rr.com> Message-ID: In article , Peter Otten wrote: >Georgy Pruss wrote: > >> Anyway, "*." is not a bad DOS convention to select files w/o extention, >> although it comes from the old 8.3 name scheme. BTW, how can you select >> files w/o extention in Unix's shells? > >ls -I*.* > >The -I option tells the ls command what *not* to show. > That's non-standard gnu ls behaviour, I think. (Tested on OpenBSD and SunOS) >Peter -- regards/mvh Stein B. Sylvarnes stein.sylvarnes at student.uib.no From amy-g-art at cox.net Mon Nov 24 17:58:03 2003 From: amy-g-art at cox.net (Amy G) Date: Mon, 24 Nov 2003 14:58:03 -0800 Subject: Delete common entries between two dictionaries References: <4Guwb.7197$9O5.6638@fed1read06> <97ba91-169.ln1@dman13.dyndns.org> Message-ID: <_1wwb.7232$9O5.1730@fed1read06> Don't know what I could have done wrong, but it just returned the origianl list, unchanged. "Amy G" wrote in message news:WGvwb.7230$9O5.2236 at fed1read06... > How do I do this same thing but with lists??? > > I apparently have two lists... not dictionaries. > > This is what it prints if I add > print domains_black > > [('YAHOO.COM', 118), ('buildingonline.com', 130), ('canada.com', 95), > ('china.com', 104), ('earthlink.com', 118), ('earthlink.net', 122), > ('email.com', 286), ('excite.com', 200), ('hongkong.com', 110), ('juno.com', > 233), ('lycos.com', 95), ('mail.com', 399), ('minedu.fi', 134), ('msn.com', > 764), ('shaw.ca', 259), ('stderr.windsongnews.com', 88), ('yahoo.ca', 435), > ('yahoo.co.uk', 303), ('yahoo.com.hk', 156), ('yahoo.fr', 266)] > > This is domains_white > > [('aol.com', 17), ('awci.org', 6), ('cox.net', 12), ('hotmail.com', 6), > ('yahoo.com', 11)] > > I want to be left with domains_black = > > [('YAHOO.COM', 118), ('buildingonline.com', 130), ('canada.com', 95), > ('china.com', 104), ('earthlink.com', 118), ('earthlink.net', 122), > ('email.com', 286), ('excite.com', 200), ('hongkong.com', 110), ('juno.com', > 233), ('lycos.com', 95), ('mail.com', 399), ('minedu.fi', 134), ('msn.com', > 764), ('shaw.ca', 259), ('stderr.windsongnews.com', 88), ('yahoo.ca', 435), > ('yahoo.co.uk', 303), ('yahoo.com.hk', 156), ('yahoo.fr', 266)] > > ie. minus the entries in domains_white. > > Thanks again guys. > > AMY > "Derrick 'dman' Hudson" wrote in message > news:97ba91-169.ln1 at dman13.dyndns.org... > > On Mon, 24 Nov 2003 13:24:17 -0800, Amy G wrote: > > > I have received such good help on this message board. I wonder if I > > > might not get a little more help from you on this. > > > > > > I am at the point where I have two dictionaries, with information of > > > a domain and a frequency of that domain. > > > > > > Now that I have the two, I want to delete each entry from one that > > > the two have in common, leaving only those that are unique to the > > > dictionary? > > > > This would be great for sets, if a set adequately models your data. > > (with two sets, this would simply be (s1-(s1&s2))) > > > > > Say I have a dictionary called domains_black and another > > > domains_white... > > > > Did you want to define equality by key or by (key, value) pair? > > > > for key in domains_white.keys() : > > if key in domains_black: del domains_black[key] > > > > for key in domains_white.keys() : > > if key in domains_black and domains_white[key] == domains_black[key] : > > del domains_black[key] > > > > -D > > > > -- > > He who scorns instruction will pay for it, > > but he who respects a command is rewarded. > > Proverbs 13:13 > > > > www: http://dman13.dyndns.org/~dman/ jabber: > dman at dman13.dyndns.org > > From trentm at ActiveState.com Mon Nov 24 14:34:55 2003 From: trentm at ActiveState.com (Trent Mick) Date: Mon, 24 Nov 2003 11:34:55 -0800 Subject: COM makepy broken in ActivePython 2.3.2? In-Reply-To: <3fbeef11.665828@news.t-online.de>; from gerson.kurz@t-online.de on Sat, Nov 22, 2003 at 05:08:27AM +0000 References: <3fbe51ff.47726500@news.t-online.de> <3fbeef11.665828@news.t-online.de> Message-ID: <20031124113455.A11520@ActiveState.com> [Gerson Kurz wrote] > On Sat, 22 Nov 2003 11:28:13 +1100, Mark Hammond > wrote: > >Try creating a "gen_py" directory under the installed win32com > >directory. The directory need only exist, not contain anything. This > >should make it start working. I'm not sure if the recent APy update > >fixed that... > > You are right, this fixes both problems. So maybe the installer does > not correctly create the directory? Anyway, many thanks! Yes, ActivePython 2.3.2 build 231 for Windows had this bug. A new build was recently released (build 232) that fixed this issue. Trent -- Trent Mick TrentM at ActiveState.com From mis6 at pitt.edu Tue Nov 18 08:02:21 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 18 Nov 2003 05:02:21 -0800 Subject: Can this be written more concisely in a functional style References: <92c59a2c.0311171648.6360213d@posting.google.com> Message-ID: <2259b0e2.0311180502.5737437b@posting.google.com> jcb at iteris.com (MetalOne) wrote in message news:<92c59a2c.0311171648. > return True in map(test,xs) return True in itertools.imap(test,xs) ? M. From __peter__ at web.de Mon Nov 17 17:42:19 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Nov 2003 23:42:19 +0100 Subject: syntax philosophy References: Message-ID: No direct answer, but if you need histograms that often, you might consider putting something along these lines into your toolbox: import copy class histogram(dict): def __init__(self, default): dict.__init__(self) self.default = default def __getitem__(self, key): return self.setdefault(key, copy.copy(self.default)) h = histogram(0) sample = [(1, 10), (2, 10), (0, 1), (1, 1)] for key, freq in sample: h[key] += freq print h h = histogram([]) for key, item in sample: h[key].append(item) print h While 0 and 0.0 are certainly the most frequent default values, they are not the only options. Peter From ConfuseYourSpamBot-parzp at ConfuseYourSpamBot.shaw.ca Sat Nov 15 00:58:32 2003 From: ConfuseYourSpamBot-parzp at ConfuseYourSpamBot.shaw.ca (Parzival) Date: Sat, 15 Nov 2003 05:58:32 GMT Subject: What's an "atomic" operation (in a threaded context)? References: <3FB2B8E6.247500D1@engcorp.com> Message-ID: Dieter Maurer wrote: > Peter Hansen writes on Wed, 12 Nov 2003 17:49:10 -0500: >> > 9 STORE_SUBSCR >> In a nutshell, your "single bytecode operation" theory is correct, >> and each of the above lines represents a single bytecode. Therefore >> the only line which matters is STORE_SUBSCR (the actual assignment) >> and it is atomic > > Are you sure? "STORE_SUBSCR" may dereference an object causing > Almost surely (I trust the Python developpers), this happens > after the assignment has been made (but before "STORE_SUBSCR" finished). > Maybe, this is enough "atomicity" for you. Do you really think this is a sound approach? You are obviously concerned about correct concurrency, yet you are prepared to disassemble Python byte code and to speculate about the actions, and then you are going to risk the correctness of your program on what you observe and deduce? I'll wager that nobody who is somebody in the Python world is going to offer *any* guarantees about what source code generates what byte-code. AFAIK, the Python GIL guarantees that at least one bytecode operation is atomic, but the _language_ makes absolutely no commitments as to what source code construction is guaranteed to be (now and forever) atomic. If I am wrong about this, I want to see it in writing in the official documentation. Until then, for correct concurrent operation, you *must* lock around all shared concurrent data accesses. (-: Stop, smile, and enjoy your breathing :-) -- Parzival -- Reply-to is confuggled: parzp (@) shaw (.) ca From mark at hahnca.com Wed Nov 12 17:11:51 2003 From: mark at hahnca.com (Mark Hahn) Date: Wed, 12 Nov 2003 14:11:51 -0800 Subject: COG sample code problem Message-ID: I'm running COG 0.5 with python 2.3.2 windows build #49. When I ran the sample code benchmark.py I got this error: while saving Traceback (most recent call last): File "C:\Python23\lib\site-packages\cog\db.py", line 368, in save_objects self.io.save_obj(obj, oid, self) File "C:\Python23\lib\site-packages\cog\io.py", line 252, in save_obj pickler.dump(obj.__class__) PicklingError: Can't pickle : it's not the same object as cog.registry.Registry Has anyone seen this problem before? Can anyone give me a hand? I'm trying out COG because pickle was not able to handle the task of pickling my object graph. Now I'm getting a pickle error in COG. It's as if pickle is out to get me. I wonder if COG is going to have the same recursion limit pickle had since it uses pickle. From jbublitzno at spamnwinternet.com Thu Nov 6 23:25:45 2003 From: jbublitzno at spamnwinternet.com (Jim Bublitz) Date: Fri, 07 Nov 2003 04:25:45 GMT Subject: ANN: PyKDE now does KDE plugins Message-ID: The latest release of PyKDE (3.8.0) includes the ability to write KDE panel applets completely in Python -- absolutely no C++ required. This is the first in what's planned to be a number of extensions for PyKDE that allow plugins and related objects to be created entirely in Python; David Boddie is nearing release of modules for authoring KParts for export (PyKDE already imports KParts), KDE Control Center modules, and IOSlaves. Future plans include allowing QWidget subclasses created in Python to be imported into Qt Designer with complete functionality, and possibly Python scripting and plugins for KDE apps like KOffice and Kontact. The underlying mechanisms and code are similar in all cases. In some cases, specific .so libs will still be required (depends on the plugin loader), but the Python modules will include autogeneration of the necessary C++ code, along with installers to simplify the task of making the plugins available. PyKDE 3.8.0 requires SIP 3.8 and PyQt 3.8. While the PyKDE 3.8.0 tarball is available now, it will be several days or more before RPM and Debian packages are available. You can check the PyKDE mailing list for more info. PyKDE-3.8.0 supports any version of KDE from 3.0.0 through 3.1.4. PyKDE 3.8.0 is also the last release that will support Python versions below 2.3, and the last that will work with sip 3.8 (sip 4.0 is already in pre-release). However, support on 3.8.0 (bug fixes and some enhancements) will continue for the forseeable future. PyKDE, PyQt and sip are available at: http://riverbankcomputing.co.uk Info on KDE panel applets is at: http://www.riverbankcomputing.co.uk/pykde/docs/panapp1.html The PyKDE mailing list is at: http://mats.imk.fraunhofer.de/mailman/listinfo/pykde Jim From dave at pythonapocrypha.com Wed Nov 19 11:09:54 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 19 Nov 2003 09:09:54 -0700 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <3FBB805D.40A8DA75@engcorp.com> Message-ID: <08aa01c3aeb7$92387e90$6400000a@YODA> Peter Hansen wrote: > "John J. Lee" wrote: > > > > "Dave Brueck" writes: > > > > > Robin wrote: > > > > It seems that the rotor module is being deprecated in 2.3, but there > > > > doesn't seem to be an obvious alternative. I'm using it just for > > [...Dave has switched to AES] > > > Since I'm not going to great lengths to hide the key, it works out to be about > > > the same strength of encryption as rotor. ;-) > > > > Quite. I don't understand why it's deprecated. We've known since the > > fifties that the algorithm is broken, so wasn't it clear from the > > start that this was for obfuscation, not strong encryption? Shouldn't > > we just add a warning to the docs (if there's not one there already)?? > > If it's really for obfuscation, wouldn't a simpler algorithm be > sufficient, such as "XOR each byte with 0x5A" or something like that? > > If the answer is "no, that's too easy to break", then it's not really > just for obfuscation, is it? I understand what you mean, but obfuscation _is_ a form of encryption, just one that's understood to be on the weak side (so the above may be considered "too weak"). Rather than being _either_ obfuscation _or_ encryption, they really are just different points on a broad data protection spectrum. Rotor was nice because for very little costs in terms of CPU / coding nuisance you could protect semi-sensitive data from nearly everyone. Sure it's strength-per-bit-of-key-size doesn't stack up well against more modern algorithms, but for the vast majority of users (including myself) data encrypted with rotor or AES is, for all practical purposes, equally untouchable. As a built-in data obfuscator, rotor filled about 99% of my "security" needs. Hmmm... the more I think about it I guess the root cause of the problem is the archaic, goofy encryption export laws of the U.S.. If Python could ship with AES or 3DES and I'd use that, but right now adding an external encryption package just to tell casual snoopers, "it's not worth your time to crack this file - keep moving" seems so over the top. -Dave From davecook at nowhere.net Sat Nov 22 03:57:48 2003 From: davecook at nowhere.net (David M. Cook) Date: Sat, 22 Nov 2003 08:57:48 GMT Subject: Database bind variables? References: Message-ID: In article , Andrew Fabbro wrote: > I haven't found a way to do this yet with pygresql (or should I be > using something else? if only the docs where there...;) All the postgresql adaptors I'm aware of use "pyformat" interpolation, which is similar to python's dictionary string interpolation, e.g. cursor.execute("select * from baz where foo=%(foo)s", {'foo' : 1234}) This does any necessary quoting for you. Dave Cook From ark at acm.org Sun Nov 2 16:32:12 2003 From: ark at acm.org (Andrew Koenig) Date: Sun, 02 Nov 2003 21:32:12 GMT Subject: Two naive Tkinter questions References: Message-ID: > In the specific example, you could just *know* that setcolor deals > with self.b1. In the more general example, you can create dynamic > callback functions: > > self.b1 = Button(self, bg = "red", > command = lambda: self.b1.config(bg="blue")) > > This uses a number of tricks: the lambda function has no arguments, > yet it uses self - so it is a nested function. Also, inside a lambda > function, you can have only expressions, so self.b1['bg']='blue' would > not be allowed. In the general case, and not assuming nested > functions, you would write > > def createWidgets(self): > def b1_setcolor(self=self): > self.b1['bg']='blue' > self.b1 = Button(self, bg = "red", command=b1_setcolor) I worked out something similar, but I must confess that it appears needlessly complicated. I was hoping for a simpler solution, such as a variation of the "command" attribute that would cause its associated argument to be called with the button rather than its parent. Your first suggestion, knowing that setcolor deals with self.b1, doesn't work with my application because I'm going to have lots of these buttons, and I want to be able to set their colors independently. > > > 2) The window in which these buttons appear is the wrong size, and does not > > depend on the height and width given to self.place in __init__. Yet the > > height and width arguments do something, because if I set width to 75, it > > cuts off half the right-hand button. How do I say how large I want the > > window to be? > > The problem is that there is another toplevel widget around your > frame; the frame itself has the size you have specified. You could > either use Toplevel instead of Frame as a base, or you could adjust > the size of the root window, e.g. through > > app.master.wm_geometry("100x50") Gotcha -- thanks. From blk at srasys.co.in Thu Nov 27 23:41:27 2003 From: blk at srasys.co.in (bala) Date: Fri, 28 Nov 2003 10:11:27 +0530 Subject: How to GetClassName in Python Message-ID: <000c01c3b569$e30428c0$440210ac@Bala> Hi, I want to know how to getclassname of application from python..In python There is no method like GetClassName... Is there any other Method ...I kindly give some example in python.. If anyone answer to the above problem....I will be very thankfull to you... Note:- Using Python Application, I want to Get the ClassName of any Application. -------------- next part -------------- An HTML attachment was scrubbed... URL: From biner.sebastien at ouranos.ca Fri Nov 28 13:57:31 2003 From: biner.sebastien at ouranos.ca (biner) Date: 28 Nov 2003 10:57:31 -0800 Subject: newbie : using python to generate web-pages Message-ID: Hello all, I am taking up on the work of a coleague who developed a big perl script to generate a bunch of html files. I am taking over his task and I looked at his code. It is quite messy because he used simple "print" command to print the html code into files so the script is a mix of html an perl. Quite ugly. I don't know much about perl but I know that there are html shortcuts in the CGI module that could allow me to make the code more readable. Something like "print em(toto)" that would print "toto" Is there anything like that in Python. I did not find anything yet. I don't know much about python (even less than perl) but I hear good things about it all the time so I would like to use this project to get familiar with python. Any help would be welcome. Thanks. Ciao! From news at grauer-online.de Wed Nov 26 20:57:33 2003 From: news at grauer-online.de (Uwe Grauer) Date: Thu, 27 Nov 2003 02:57:33 +0100 Subject: kinterbas db column type In-Reply-To: References: Message-ID: Uwe Grauer wrote: > > more explanation: > > It's different from other modules cause it does a implicit type > conversion to the Python-types. > So for a DATETIME-column in mysql you get a type_code 12 (which is > indeed DATETIME in MySQLdb) but in kinterbasdb you get t_tuple. This > does not help me very much since the information i need is different > from what i get. > > Uwe > Got the answer in db-sig, thought i should share it: David Rushby wrote: This is a known problem in 3.1_pre6 and earlier. It's fixed in the CVS version, which I plan to release soon as 3.1_pre7. Here's the relevant SF bug report: http://sourceforge.net/tracker/index.php?func=detail&aid=814276&group_id=9913&atid=109913 If you're not compiler- or CVS- constrained, use the CVS version right now; it's quite stable. From __peter__ at web.de Sat Nov 1 03:20:43 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 01 Nov 2003 09:20:43 +0100 Subject: HTMLParser problems. References: <87y8v1krwl.fsf@pobox.com> Message-ID: John J. Lee wrote: > [...] >> The simplest solution is to replace the above line with >> >> parser.feed(socket.read().replace(" ", "NaN") > [...] > > That's platform-dependent, if you're relying on float("NaN"). Actually, I'm not, any non-empty string would have done as well, given the original poster's parser implementation. Peter From op73418 at mail.telepac.pt Fri Nov 14 07:39:12 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Fri, 14 Nov 2003 12:39:12 +0000 Subject: conceiling function calls.. References: Message-ID: <20j9rvsi2a1gi6emn1totgqipff6v5vr4a@4ax.com> On Wed, 12 Nov 2003 23:30:24 +0100, "Carlo v. Dango" wrote: >It is possible to conceil access to methods using the "property()" >function so method access looks like field access.. is the same possible >for functions (not taking any args... ) > >I would like something like > > >def f(): > return tnaheusnthanstuhn > > >class A(object): > def foo(self): > f.bar() > > >as it is now I have to write > >class A(object): > def foo(self): > f().bar() > Can you explain why you would want to do that? What possible gain can you have by counfounding name lookup with calling? Btw, as far as I know it can't be done. Even if functions were subclassable (and they're not) I just don't know how to instruct Python such that every time you look up a bare name referencing a function you end up calling it. But then again this request sounds so bizarre... With my best regards, G. Rodrigues From tjreedy at udel.edu Fri Nov 21 21:11:15 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 Nov 2003 21:11:15 -0500 Subject: what do you use python for? References: Message-ID: <8uGdnVXR0qdZWCOiRVn-gQ@comcast.com> "Jason Tesser" wrote in message news:mailman.961.1069419297.702.python-list at python.org... >Ok my question is are any of you doing this kind of stuff in Python and what do >you think about our project? Our project will include everything from >registration stuff to busness office to >POS system. There may be projects on SourceForge relevant to your needs under category admin or business. tjr From mrroach at okmaybe.com Sun Nov 23 18:38:38 2003 From: mrroach at okmaybe.com (Mark Roach) Date: Sun, 23 Nov 2003 23:38:38 GMT Subject: new guy References: Message-ID: On Tue, 18 Nov 2003 12:03:50 +0000, nards_collective wrote: > if e>= 1 : > a=e > else : > a=0 > > > I keep getting a syntax error. > This piece of code is meant to keep the value of a equal to or grater > than 0. Any odeas would be appreciated. you could also use a = max(0, e) -Mark From dwelch91.nospam at comcast.net Mon Nov 24 22:18:35 2003 From: dwelch91.nospam at comcast.net (djw) Date: Tue, 25 Nov 2003 03:18:35 GMT Subject: String Regex problem In-Reply-To: <7b454334.0311241844.210b4846@posting.google.com> References: <7b454334.0311241844.210b4846@posting.google.com> Message-ID: Fazer wrote: > Hello, > > I have a string which has a url (Begins with a http://) somewhere in > it. I want to detect such a url and just spit out the url. Since I > am very poor in regex, can someone show me how to do it using a few > examples? > > Thanks a lot! I would look here to improve your re-ex skills: http://www.amk.ca/python/howto/regex/ Also, I find Kodos to be invaluable in developing and debugging regexs. Highly recommended. http://kodos.sourceforge.net Of course, you could just use urlparse in the standard library... Good luck, Don From fgrimm at inneo.de Mon Nov 10 10:49:27 2003 From: fgrimm at inneo.de (flori) Date: 10 Nov 2003 07:49:27 -0800 Subject: __slots__ References: <9d5f9ae4.0311070836.7503de86@posting.google.com> Message-ID: <9d5f9ae4.0311100749.362e8cdf@posting.google.com> fgrimm at inneo.de (flori) wrote in message news:<9d5f9ae4.0311070836.7503de86 at posting.google.com>... > i try to greate somthing like this > sorry for silly question my prob is when i try to do this class ca(object): __slots__ = ("a",) class cb(ca): __slots__ = ("a","b") class cc(ca): __slots__ = ("a","c") class cd(cb,cc): __slots__ = ("a","b","c","d") in line "class cd(.." thorws a exception TypeError: multiple bases have instance lay-out conflict (if cb (or cc) doesn't define __slots__ it works.) My only solution is to generate a "unsloted" class (_ca) and genererate a "sloted" class (ca) with only the __slots__ attribute. when i had to inherit the class i use the "unsloted" class. like that: class _ca(object): pass class ca(object): __slots__ = ("a",) class _cb(_ca): pass class cb(_cb): __slots__ = ("a","b") class _cc(_ca): pass class cc(_cc): __slots__ = ("a","c") class _cd(_cb,_cc): pass class cd(_cd): __slots__ = ("a","b","c","d") my source does this a metaclass my question is is their a nicer way to do this? From francisgavila at yahoo.com Sun Nov 30 00:35:05 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 30 Nov 2003 00:35:05 -0500 Subject: The namespace for builtin functions? References: <3FC926ED.7070906@irl.cri.nz> Message-ID: Jay O'Connor wrote in message ... >Blair Hall wrote: > >> Can anyone please tell me how to correctly use a built in function >> when there is a function of the same name in local scope? > > > >Save yourself a lot of trouble, just give it a different name. > This is the best advice. However... I don't understand why in __main__, the name __builtins__ refers to the module object __builtin__, but in any other namespace, __builtins__ is the __dict__ of __builtin__! E.g.: --- a.py --- a = lambda: __builtins__ --- END --- >>> __builtins__ >>> id(__builtins__) 6577648 >>> id(__builtins__.__dict__) 6584048 >>> import a >>> id(a.a()) 6584048 Why not 6577648?! -- Francis Avila From edreamleo at charter.net Sat Nov 8 08:08:28 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Sat, 8 Nov 2003 07:08:28 -0600 Subject: Leo 4.1 beta 1 An outlining editor References: Message-ID: Leo 4.1 beta 1 does not work on most (all?) Linux systems: "mbcs" is not a valid encoding on Linux. Leo 4.1 beta 2 corrects this problem. You may download beta 2 from Download: http://sourceforge.net/project/showfiles.php?group_id=3458 Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From tweedgeezer at hotmail.com Wed Nov 12 18:39:08 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 12 Nov 2003 15:39:08 -0800 Subject: program surgery vs. type safety References: <9a6d7d9d.0311120822.553cd347@posting.google.com> Message-ID: <698f09f8.0311121539.e699627@posting.google.com> aaron at reportlab.com (Aaron Watters) wrote in message news:<9a6d7d9d.0311120822.553cd347 at posting.google.com>... > If I were forced to do the transformation in a type safe way > I would not be able to do as much experimentation and backtracking > because each step between type safe snapshots that could be tested > would be too painful and expensive to throw away and repeat. This entire post is the "musing" of a dynamic typing enthusiast and primarily subsists of simply assuming the point you're apparently attempting to prove, that dynamic typing allows you to do what you're doing, and static typing would not. I am curious, however -- what are these "type unsafe" stages you have to go through to refactor your program? I've refactored my personal project several times and haven't yet gone through what I'd consider a type-unsafe stage, where I'm *fundamentally* required to use operations that aren't type-safe. Jeremy From rudy.schockaert at pandoraSTOPSPAM.be Thu Nov 6 08:38:52 2003 From: rudy.schockaert at pandoraSTOPSPAM.be (Rudy Schockaert) Date: Thu, 06 Nov 2003 13:38:52 GMT Subject: Strange problems with encoding In-Reply-To: References: Message-ID: Sebastian Meyer wrote: > Hi newsgroup, > > i am trying to replace german special characters in strings like > str = re.sub('?', 'oe', str) > > When i work with this, i always get the message > UniCode Error: ASCII decoding error : ordinal not in range(128) > > Yes i have googled, i searched the faq, manual and python library and > searched all known soruces of information. I played with the python > builtin function encode to enforce the rigth encoding, but the error > stays the same. I ve read a lot about UniCode and internal conversion > about Strings done by python, but somehow i ve missed the clue. > Nope, python says Huuups... ordinal not in range(128), ;-( > > Anyone of you having any idea?? Seems like i am too stupid to read > documentation carefully., perhaps i misunderstand something... > > thanks for your help in advance > > Sebastian I'm experiencing something similar for the moment. I try to base64-encode Unicode strings and I get the exact same errormessage. >>> s = u'?' >>> s u'\xf6' >>> s.encode('base64') Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\encodings\base64_codec.py", line 24, in base64_encode output = base64.encodestring(input) File "C:\Python23\lib\base64.py", line 39, in encodestring pieces.append(binascii.b2a_base64(chunk)) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128) When I don't specify it's unicode it works: >>> s = '?' >>> s '\xf6' >>> s.encode('base64') '9g==\n' The reason I want to base64-encode these unicode strings is because I get those as input and want to store them in a MySQL database using SQLObject. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Nov 1 06:35:45 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 01 Nov 2003 12:35:45 +0100 Subject: My first Python program.. Calculating pi geometrically. In-Reply-To: References: Message-ID: <3fa39a91$0$58703$e4fe514c@news.xs4all.nl> Ron Adam wrote: > Doing it geometrically was strictly a learning exercise. And I did > learn quite a bit by doing it. And you only scratched the surface of what Python offers you :-) While it's nice to hear that you learned a lot by making this arithmetic python program, it certainly is not the most inspiring thing that Python is capable of... I even think you learned more about calculating Pi than you did about programming in Python ;-) --Irmen From Mike at DeleteThis.Geary.com Wed Nov 19 02:56:41 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 18 Nov 2003 23:56:41 -0800 Subject: New Guy References: Message-ID: Is that the *exact* program? Nothing is indented, so I get this error, as I would expect: File "C:\TempTest\Test.py", line 11 gen=gen+1 ^ IndentationError: expected an indented block If I indent everything following the "while" statement, then I get this error which I would also expect, because the line after the "if" statement is not indented: File "C:\Test\PythonTest\Test.py", line 21 a=e ^ IndentationError: expected an indented block Do those errors resemble the ones you are getting? Could I make a couple of suggestions, which I think were already made? When you post some code asking for advice about an error message, post the exact code and the exact error message. Don't just say you got an error on an "if" statement. That doesn't give anyone much to go on. As it is, there's no way to tell if you simply didn't indent anything as required, or you did indent your code properly but somehow the formatting got stripped out when you posted the code. If you used tabs to format your code, redo it with spaces instead--that will make sure it gets posted correctly. Also, it would be helpful if you could use "subject" lines that describe the problem, and take a couple of minutes and proofread what you post. I'm not just being picky here--when there are so many spelling errors, it slows people down who read your message and may actually discourage people from helping you out. So it's to your benefit to dot your i's and cross your t's. Read the "how to ask questions the smart way" page that someone referred you to earlier--it really has some good advice that you'll find useful. -Mike "nards_collective" wrote in message news:mailman.865.1069224343.702.python-list at python.org... > Thanks for the advise gys, but I still can't decipher the problem. > Below is a copy of the entir progra, the erro is stil in the first > 'if' command. > > NArDS > > > > > a = input ("Value for A? ") > b = input ("Value for B? ") > c = input ("Value for C? ") > d = input ("Value for D? ") > gen=0 > > print gen,a,b,c,d > > while gen <=40 : > > gen=gen+1 > e= (b+d)/2+ (b-c) > f= (a+c)/2+(b-d) > g=(b+d)/2+(c-a) > h=(a+c)/2+(d-b) > > print gen,a,b,c,d > print gen,e,f,g,h > > if e >= 1: > a=e > else : > a=0 > > if b>= 1 : > b=f > else: > b=0 > > if g >= 1: > c=g > else: > c=0 > > if h >= 1: > d=h > else: > d=0 > > i=a/(a+b+c+d)*100 > j=b/(a+b+c+d)*100 > k=c/(a+b+c+d)*100 > l=d/(a+b+c+d)*100 > > a = i > b = j > c = k > d = l > > print gen,a,b,c,d > > From davidcfox at post.harvard.edu Thu Nov 13 00:28:00 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Thu, 13 Nov 2003 05:28:00 GMT Subject: True inconsistency in Python In-Reply-To: References: Message-ID: Scott Chapman wrote: > > if var == True: # only works if var is 1 > blah > > ' Must use: > > if var: # works if var is not 0 > blah Just because something isn't True doesn't mean it isn't true. David From bokr at oz.net Sat Nov 8 19:46:00 2003 From: bokr at oz.net (Bengt Richter) Date: 9 Nov 2003 00:46:00 GMT Subject: simple float numbers problem References: <3FAB9F7C.3060901@sympatico.ca> Message-ID: On Fri, 7 Nov 2003 17:50:16 +0100, "Fredrik Lundh" wrote: >Vio wrote: > >> I need to test for equality between simple 2 decimal numbers. For example: >> >> if (10 + 15.99) == 25.99: >> do some stuff... >> >> The preceding sentence should be TRUE, but to Python it appears FALSE. >> Which is wrong. > With exact decimals you can do it: >>> from exactdec import ED >>> ED(10)+ED('15.99') == ED('25.99') True but if I get all the bits from floating point values instead of exactly interpreting string literals, we can see what happened to you: >>> print '%s\n%s'%(ED(10+15.99, 'all'), ED(25.99,'all')) ED('25.99000000000000198951966012828052043914794921875') ED('25.989999999999998436805981327779591083526611328125') Grabbing less bits: >>> print '%s\n%s'%(ED(10+15.99, 15), ED(25.99, 15)) ED('25.990000000000002') ED('25.989999999999998') 15 fractional decimals still shows a difference, but >>> print '%s\n%s'%(ED(10+15.99, 14), ED(25.99, 14)) ED('25.99') ED('25.99') So we can expect >>> ED(10+15.99, 14) == ED(25.99, 14) True >that's how floating point numbers work. see: > > http://www.python.org/doc/current/tut/node14.html > Or play with the new toy. I posted it to the "prePEP: Decimal data type" thread ;-) >> Perhaps because Python translates "25.99" to "25.98999999999999998" and >> not "25.99", which may be the reason for this error (me guessing...). If >> that's the case, how do I force Python to only use 2 decimal points, and >> not "make up" superfluous decimals? Or if that's not the cause for the >> problem, how do I make Python see my math expression as TRUE (as it >> "should" be)? > >convert both terms to strings, and compare the strings. > >or calculate the absolute value of the difference between the two >numbers (abs(x-y)) and compare that to a small constant. > >or use a data type designed to handle decimal numbers, such as: > > http://fixedpoint.sourceforge.net/ > Still, note the difference beween enforcing rounding to a number of fractional bits as you go (maybe it doesn't do that??) vs keeping exactness until rounding is explicitly invoked by a method or during construction from another value. Also note that exact values can be expensive (time, space) to keep, because there is a kind of rational type hiding in there ;-) Regards, Bengt Richter From rmunn at pobox.com Fri Nov 21 10:43:25 2003 From: rmunn at pobox.com (Robin Munn) Date: Fri, 21 Nov 2003 15:43:25 GMT Subject: Chinese input for python and MySQL References: <49LZ6H$DO6@wretch.csie.nctu.edu.tw> Message-ID: tinmean wrote: > hi, > > I have some problem when I use MySQLdb.connect.cursor() > > to create some Chinese(Big5) strings data, but it is no use. > > The reference is from the Deitel's "How to program:Python". > > The code can't work when the strings are Chinese. > > Thanks > > --Tinmean You haven't given us enough information to help you. What do you mean when you say "the code can't work"? Does it throw an exception? Which one? What's the exact error message? Or does the code work but return the wrong result? If that's the case, give us an example run: the input data, what the correct result *should* be, and what the result you're actually getting is. How are you creating the strings? Are you using Unicode? (You should be.) See http://www.reportlab.com/i18n/python_unicode_tutorial.html to get started if you're not. Read http://www.catb.org/~esr/faqs/smart-questions.html then come back and ask your question again. -- Robin Munn rmunn at pobox.com From fjh at cs.mu.oz.au Tue Nov 4 04:13:02 2003 From: fjh at cs.mu.oz.au (Fergus Henderson) Date: Tue, 04 Nov 2003 09:13:02 GMT Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> <3f9d556c$1@news.unimelb.edu.au> <3f9f8f49$1@news.unimelb.edu.au> <3f9fe9b1$1@news.unimelb.edu.au> <3fa26092$1@news.unimelb.edu.au> Message-ID: <3fa76d99$1@news.unimelb.edu.au> Lex Spoon writes: >Fergus Henderson writes: >>>If you are simply doing "x := y" then there is no checking required. >> >> Yes, we covered that already. But that's not what is happening in >> the scenario that I was describing. The scenario that I'm describing is >> >> Collection c; >> >> ... >> foreach x in c do >> use(x); >> >> where use(x) might be a method call, a field access, or similar. >> For example, perhaps the collection is a set of integers, and you >> are computing their sum, so use(x) would be "sum += x". > >I see. "sum += x" would indeed tend to cause a lot of checks, but >then again the checks might well end up costing 0 overall CPU cycles. Occaisionally, perhaps. But I think that would be rare. >The general technique of optimizing methods for common types, plus the >likelihood that a CPU will have multiple functional units, can make a >big difference. Even with an unlimited number of functional units, there's still the extra CPU cycles to wait for instruction cache misses or page faults caused by the greater code size. -- Fergus Henderson | "I have always known that the pursuit The University of Melbourne | of excellence is a lethal habit" WWW: | -- the last words of T. S. Garp. From joshway_without_spam at myway.com Fri Nov 14 14:50:40 2003 From: joshway_without_spam at myway.com (JCM) Date: Fri, 14 Nov 2003 19:50:40 +0000 (UTC) Subject: for what are for/while else clauses References: Message-ID: John Roth wrote: ... > Yep. It's one of the three termination conditions for a loop. What are the three conditions? I know of two: 1 Reaching the end of the iteration 2 Breaking out From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Wed Nov 26 16:09:45 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Thu, 27 Nov 2003 00:09:45 +0300 Subject: Newbie: Running two threads... In-Reply-To: References: Message-ID: Siddharth Choudhuri wrote: > I am trying to come up with an app that reads data out of socket > (concurrent server) and display a graph on the UI. I have one program that > uses asyncore.loop() to read data out of a port. The second program uses > Tkinter to have the UI and uses mainloop() to respond to mouse-click and > other events. > > Now, the problem is how do I combine the two ? since there are two event > loops. If I put the asyncore.loop() within the UI, the code blocks waiting > for input and does not update the UI. > > TIA > -siddharth > > _____________________________________________________________________ > Unix is user friendly - its just picky about its friends. > _____________________________________________________________________ IMHO standard solution is to use Queue---socket process polpulates a queue and UI pulls data from it. regards, anton. From rkern at ucsd.edu Sat Nov 22 19:42:18 2003 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 23 Nov 2003 00:42:18 +0000 (UTC) Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> Message-ID: In article <7xislcjh4k.fsf at ruckus.brouhaha.com>, Paul Rubin writes: > rkern at ucsd.edu (Robert Kern) writes: >> Note that the question is phrased as a "proprietary vs. GPL" >> dichotomy. I think the following entry is more appropriate: >> >> http://www.gnu.org/licenses/gpl-faq.html#TOCGPLModuleLicense > > No I don't think it's more appropriate. That entry is about adding > your own module to a GPL'd program. Such a module doesn't have to be > GPL'd, as long as its license is "GPL-compatible". The original > question was not about that. It was about using part of a GPL'd > program in another program. That is prohibited unless the second > program is also GPL'd. I think the same principles apply in both the OP's question and the FAQ answer. Note that the FAQ answer mixes things up a bit in the following sentence: "But you can give additional permission for the use of your code. You can, if you wish, release your *program* under a license which is more lax than the GPL but compatible with the GPL" [emphasis added]. I think the actual answer tries to answer both the literal question in the FAQ and the OP's question. If I have an application ("C") that uses the readline module ("B"), and I wish to distribute it, I must distribute it under the GPL. Under my interpretation of the FAQ answer, I can also give the recipients of the application more rights to *my* code (the parts that are C and not B) such that they can, say, use a routine that has no relationship to B (for example, a computational routine that doesn't have a UI and therefore doesn't use readline at all) in a GPL-incompatible project. I don't think that the GPL makes the distinction between putting a GPLed module into a GPL-compatible program and putting a GPL-compatible module into a GPLed program. C.f. >From RMS http://mail.gnome.org/archives/foundation-list/2001-December/msg00034.html IANAL, and of course, RMS INAL, either, but until there's a court case examining this issue in particular, I think we're safe. -- 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 edvard+news at majakari.net Tue Nov 18 03:28:49 2003 From: edvard+news at majakari.net (Edvard Majakari) Date: Tue, 18 Nov 2003 10:28:49 +0200 Subject: context-sensitive completion using readline.set_completer Message-ID: <87wu9ym666.fsf@titan.staselog.com> Suppose you have a program containing commands and file name parameters. A simple class providing completion could first read all the commands to list, and extend that list later using all file names in given directory. This way a user could tab-complete (using readline.parse_and_bind('tab: complete')) any command and any file. Eg. if a command 'move' is implemented and there are files 'foo.txt' and 'bar.txt', the user could type mo f b expanding to move foo.txt bar.txt But the problem is that user is also able to type "f m" getting "foo.txt move", which makes no sense. The ideal completion would work as follows: when completing the first word in command line, use set 1 (s1) as possible completion targets. When completing anything else (second or any other word), use set 2 (s2) as possible completion targets. Thus, having commands 'move', 'copy' and 'help' with previous two files the session would go as follows: copy move help c -> copy foo.txt bar.txt f -> copy foo.txt However I am not able to make it work, because I don't see how I could store state information to my completer (it has no idea whether I'm completing the first word or say, 4th word). -- #!/usr/bin/perl -w $h={23,69,28,'6e',2,64,3,76,7,20,13,61,8,'4d',24,73,10,'6a',12,'6b',21,68,14, 72,16,'2c',17,20,9,61,11,61,25,74,4,61,1,45,29,20,5,72,18,61,15,69,20,43,26, 69,19,20,6,64,27,61,22,72};$_=join'',map{chr hex $h->{$_}}sort{$a<=>$b} keys%$h;m/(\w).*\s(\w+)/x;$_.=uc substr(crypt(join('',60,28,14,49),join'', map{lc}($1,substr $2,4,1)),2,4)."\n"; print; From fredrik at pythonware.com Sun Nov 30 13:00:16 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 30 Nov 2003 19:00:16 +0100 Subject: The namespace for builtin functions? References: <3FC926ED.7070906@irl.cri.nz> Message-ID: Blair Hall wrote: > Can anyone please tell me how to correctly use a built in function > when there is a function of the same name in local scope? > > Here is an example. Suppose the following is in myApply.py: > > def apply(func,seq): > # > # Code can default to > # built-in definition in some cases: > return __builtins__.apply(func,seq) the module is named __builtin__, and must be imported before it can be used. __builtins__ is a CPython implementation detail (it's used to cache a reference to the builtin modules, and are initialized on demand). for more info, see the "Overloading functions from the __builtin__ module" here: http://effbot.org/zone/librarybook-builtin.htm From __peter__ at web.de Sat Nov 1 14:56:25 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 01 Nov 2003 20:56:25 +0100 Subject: what is this? References: Message-ID: Herbert Fritsch wrote: >>>> b / (2.0 + a) > 0.80000000000000004 > > There must be something wrong. I' running the new Suse 9.0. No :-) That's the way *all* floating point operations work, nothing python-specific here. See http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate Peter From robin at jessikat.fsnet.co.uk Tue Nov 11 06:39:20 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 11 Nov 2003 11:39:20 +0000 Subject: Python's simplicity philosophy (was Re: reduce()--what is it good for?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> In article , Alex Martelli writes >Robin Becker wrote: > ... >> This whole thread is reminiscent of vi vs emacs or an os war or similar. >> It's a pity that people with a preferred style should be so dogmatic >> that they want to remove language features to prevent others using them. > >Python's essence is simplicity and uniformity. Having extra features >in the language and built-ins runs directly counter to that. no disagreement, reduce is in line with that philosophy sum is a shortcut and as others have said is less general. > >> The whole 'only one way to do it' concept is almost certainly wrong. > >Bingo! You disagree with the keystone of Python's philosophy. Every >other disagreement, quite consequently, follows from this one. > not so, I agree that there ought to be at least one way to do it. >Want "maximal freedom to express algorithms"? You can choose among ... you may be right, but I object to attempts to restrict my existing freedoms at the expense of stability of Python as a whole. >But can't you let us have *ONE* language that's designed according I am not attempting to restrict anyone or change anyone's programming style. I just prefer to have a stable language. -- Robin Becker From dave at pythonapocrypha.com Wed Nov 12 12:41:48 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 12 Nov 2003 10:41:48 -0700 Subject: Python's simplicity philosophy References: <2259b0e2.0311112248.3be2d304@posting.google.com><17lsb.109042$fl1.4548960@twister.southeast.rr.com><20031112170100.GA32388@godzilla.fibrespeed.net> <04ac01c3a942$d4ba4a20$891e140a@YODA> Message-ID: <04f801c3a944$404f1260$891e140a@YODA> > > On Wed, Nov 12, 2003 at 08:28:29AM +0000, Robin Becker wrote: > > > sequence.sum() > > > sequence.reduce(operator.add[,init]) > > > sequence.filter(func) etc etc > > > > > > That would make these frighteningly incomprehensible ;) > > > concepts seem less like functional programming. Personally I wouldn't > > > like that to happen. > > > > I'm hoping you were being sarcastic ... but I get the feeling you aren't. > > > > Why, pray-tell, would you want an OO program to do: > > > > results = [ func(x) for x in sequence ] > > > > ... instead of ... > > > > results = sequence.map(func) ?? My apologies: my goofy mailer isn't adding the "On , wrote:" lines, so it sort of confuses what Robin wrote with what Michael wrote. Sorry! -Dave From socraticquest at hotmail.com Mon Nov 3 16:19:17 2003 From: socraticquest at hotmail.com (socraticquest) Date: 3 Nov 2003 13:19:17 -0800 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <87he1vsopi.fsf@pobox.com> <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> <2259b0e2.0311012219.73aa445f@posting.google.com> Message-ID: <8d667de1.0311031319.24894d26@posting.google.com> Hello all, The Author's October 26th post in this newsgroup 'AI and Cognitive Psychology Rant' "hit the nail on the head" as to my experiences with Asperger Syndrome. thanks Stephen Horne wrote in message news:... > On 3 Nov 2003 00:13:58 GMT, bokr at oz.net (Bengt Richter) wrote: > > >On 1 Nov 2003 22:19:11 -0800, mis6 at pitt.edu (Michele Simionato) wrote: > > > >>Stephen Horne wrote in message news:... > [...] > >>> The evidence suggests that conscious minds exist > >>> within the universe as an arrangement of matter subject to the same > >>> laws as any other arrangement of matter. > > >If there is some "stuff" whose state can eventually be shown to have 1:1 relationship > >with the state of a particular individual's conscious experience > > No-one has ever shown that. Actually, exactly the opposite. Our > consciousness is a very poor substitute for reality. You may see you > conscious awareness as detailed, but that is only because as soon as > you shift you focus on some detail it naturally enters the > consciousness (indeed it often gets backdated, so that you think it > was in your consciousness at a time that it simply wasn't there at > all). > > What would be a particularly valued aspect of consciousness? How about > 'agency' - the sense of owning and controlling our own actions - the > sense of free will? > > Well, if electrodes are placed on your brain in the right place, they > can directly move your arm. So what? Well, you will be completely > unaware of the remote control - unless you are told about it, you will > claim that you chose to move your arm of your own free will. You will > even have an excuse for why you moved your arm which you believe > implicitly. > > In fact you don't even need electrodes on the brain - the same effect > can be seen with people whose left and right brains are separated > (corpus callosum cut). Hold up a card saying 'get a drink' so that it > is visible only to one eye and they will go to get a drink. Hold up a > card saying 'why did you get a drink?' to the other eye and they will > show no awareness of the first card, insisting they just felt thirsty > or whatever. > > Quite simply, consciousness is nothing special. It is a product of > information processing in the brain. Sometimes that information > processing goes wrong for some reason or another, and consciousness > gets distorted as a result. > > The 'transducers' are our senses, providing information about reality > (imperfectly) to our brains. > > >From the fact that my consciousness goes out like a light almost every night, I speculate that > >that what persists day to day (brains, synaptic connections, proteins, etc) is not the _essential_ > >basis of my experience, but rather, those persistent things somehow _shape_ the medium through > >whose state-changes my conscious experience arises. > > What if the thing that woke up the next day was a perfect copy of you, > complete with the same memories, rather like Arnie in the Sixth Day? > > No - not a clone. A clone is at best an identical twin with a > different age as well as different memories, and identical twins do > not have identical brains even at birth - there isn't enough > information in our DNA to give an exact blueprint for the initial > connections between the neurons in our brains. > > But assume a perfect copy of a person, complete with memories, could > be made. How would it know that it wasn't the same self that it > remembered from yesterday? > > Now consider this... > > The brain really does change during sleep. In a way, you literally are > not the same person when you wake up as when you went to sleep. > > More worryingly, the continuity of consciousness even when awake is > itself an illusion. Think of the fridge light that turns off when the > fridge is shut - if you didn't know about fridge lights, and could > only see it when the door is open, you would assume the light was > always on. Similarly, whenever you try to observe your state of > consciousness it is inherently on so it apears to be always on and > continuous, but science strongly suggests that this appearance is > simply wrong. > > So do we have any more claim to our conscious sense of self than this > hypothetical copy would have? > > The fact is that no-one has shown me anything to make me believe that > we have 'experience' separate from the information processing capacity > of the brain. So far as I can see, the copy would have as much claim > to the conscious sense of self, 'continuing on' from prior memory, as > the original. > > >Now consider the experience of being "convinced" that a theory "is true." What does that mean? > > Science suggests that all subjective meaning is linked to either > direct senses or action potentials in the brain. If you think of the > concept 'democracy', for instance, you may actually generate the > action potentials for raising your hand to vote (depending on your > particular subjective understanding of that abstract term) - though > those potentials get instantly suppressed. > > In fact a key language area (Brocas area IIRC) is also strongly linked > to gesture - hence sign language, I suppose. > > This makes good sense. Evolution always works by modifying and > extending what it already has. The mental 'vocabulary' has always been > in terms of the bodily inputs and outputs, so as the capacity for more > abstract thought evolved it would of course build upon the existing > body-based 'vocabulary' foundations. > > I can easily suggest possible associations for the term 'convinced' by > referring to a thesaurus - 'unshakeable', for instance, is a clear > body/motion related metaphor. > > Or maybe it relates to the body language action potentials associated > with the appearance of being convinced? > > At which point I'm suddenly having an a-ha moment - maybe the verbal > and nonverbal communication deficits in Asperger syndrome and autism > are strongly linked. Maybe a person who is unable to associate an idea > to its body language, for instance, loses a lot of the intuitive sense > of that idea. Thus the idea must be learned verbally and the verbal > definition inherently gets taken too literally. > > Basically, if a person has to give the concept a new, abstract, > internal symbol instead of using the normal body-language associated > internal symbol, then any innate intuitions relating to that concept > will be lost. The neurological implementation of the intuitions may > exist but never get invoked - and therefore it will tend to atrophy, > even if its normal development doesn't depend on somatosensory > feedback in the first place. > > That could explain some odd 'coincidences'. > > Hmmmm. > > I think I might post this idea somewhere where it is actually on topic > ;-) > > >Is it pain and pleasure at bottom > > Nope - the innate circuitry of our brain brings a lot more than that. > 'Pain' and 'pleasure' are actually quite high level concepts, things > which we experience as 'good' or 'bad' only because we have the > information processing machinery that makes those associations. > > >I think we will find out a lot yet. Beautiful, subtle stuff ;-) Too bad we are > >wasting so much on ugly, dumb stuff ;-/ > > 'Ugly' and 'dumb' are themselves only subjective perceptions. If you > really want to know the truth, you must accept that it will not always > be what you want to hear. > > >>I am also quite skeptical about IA claims. > >Yes, but AI doesn't have to be all that "I" to have a huge economic and social impact. > > I thought IA != AI, though I have to admit I'm not sure what IA stands > for. Instrumentalist something-or-other? > > As for AI, I'd say I agree. Having a human-style consciousness is not > necessarily a practical asset for an intelligent machine. From keflimarcusx at aol.comNOSPAM Sat Nov 1 23:33:19 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 02 Nov 2003 04:33:19 GMT Subject: It's still I, Miville References: Message-ID: <20031101233319.09088.00000022@mb-m06.aol.com> >You say in the definition of mappings that at present Python has only >one type of it, the dictionnary. I suggest another one, the sparse >array, where absence of key would mean not absence of element but >presence of a default-value element, such as zero for sparse arrays in >the mathematical sense. >From my understanding, this would be extremely easy: simply derive a new class from the 'dict' type and add the functionality. In fact I think Guido van Rossum used this very example in demonstrating the power of deriving from basic types. There's no need to build spare-arrays into the language when we can already do them without much trouble, though perhaps they could be added to the library -- if they're not there already. I'm too lazy to look it up. ;) - Kef From mhammond at skippinet.com.au Wed Nov 12 17:20:47 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 13 Nov 2003 09:20:47 +1100 Subject: ADO and Makepy In-Reply-To: <2Xxsb.1046331$uj6.2632860@telenews.teleline.es> References: <2Xxsb.1046331$uj6.2632860@telenews.teleline.es> Message-ID: Alv Mart wrote: > Hi, > > I ran makepy for ADO. After I installed a new version of python I have this > error: > > Do you know why could I have this error? > > >>> from ADODB import Connection,Recordset > > >>>>conn = Connection() You shouldn't need to import the makepy generated module manually. You should just be able to use win32com.client.Dispatch("ADO.Connection"). This will magically use a Connection class from the makepy module. You can also avoid manually running makepy, by calling gencache.EnsureModule - run "makepy.py -i" for details. Mark. From andy at fourkochs.com Sat Nov 29 18:12:33 2003 From: andy at fourkochs.com (Andy Koch) Date: Sat, 29 Nov 2003 23:12:33 GMT Subject: Python Book Message-ID: I am looking to purchase a good introductory python book. "The Quick Python Book" by Darly Harms and Kenneth McDonald has caught my eye; I was wondering if anyone has read this book. If you have, I would love to hear your opinion of it. Thanks, Andy From bokr at oz.net Mon Nov 17 15:46:24 2003 From: bokr at oz.net (Bengt Richter) Date: 17 Nov 2003 20:46:24 GMT Subject: for what are for/while else clauses References: Message-ID: On Fri, 14 Nov 2003 19:31:08 +0100, "Diez B. Roggisch" wrote: >Hi, > >today I rummaged through the language spec to see whats in the for ... else: >for me. I was sort of disappointed to learn that the else clauses simply >gets executed after the loop-body - regardless of the loop beeing entered >or not. > >So where is an actual use case for that feature? > >I imagined that the else-clause would only be executed if the loop body >wasn't entered, so I could write this > >for r in result: > print r >else: > print "Nothing found, dude!" > >instead of > >if len(result): > for r in result > print r >else: > print "Nothing found, dude!" > > > >waiting for enlightment, > My mnemonic is to think of the mysterious elses as coming after prefixed pseudo-code like: if this_code_is_interfered_with: else: # got to end of loop or end of try block without interference hence >>> for x in []: pass ... else: print 'got to end of nothing without interference ;-)' ... got to end of nothing without interference ;-) >>> try: pass ... except: pass ... else: print 'got to end of try: without interference.' ... got to end of try: without interference. >>> while raw_input('while> '): ... if raw_input('break? ')=='y': break ... else: print 'got to end of while w/o interference' ... while> asdad break? asad while> asdasd break? while> got to end of while w/o interference >>> while raw_input('while> '): ... if raw_input('break? ')=='y': break ... else: print 'got to end of while w/o interference' ... while> asd break? y Regards, Bengt Richter From theller at python.net Tue Nov 25 13:18:33 2003 From: theller at python.net (Thomas Heller) Date: Tue, 25 Nov 2003 19:18:33 +0100 Subject: Shared Memory Modules References: <3FC390AA.3DFDE27F@engcorp.com> Message-ID: <65h89urq.fsf@python.net> Peter Hansen writes: > Thomas Heller wrote: >> >> steven.green3 at baesystems.com (S Green) writes: >> >> > Does any one now if a shared memory module exists, written in python >> > for a windows platform. I now one exists for unix? >> > >> > >> > help most appreciated, >> > >> > S Green >> >> import mmap > > The docs suggest that mmap.mmap(x, x, mmap.MAP_SHARED) will work under > Unix but not Windows. > > Does the Windows version really support shared memory, or is the > multiple-maps-per-file feature only valid within a single process? Yes, it does. You have to give this memory block a name, though: sharedmem = mmap.mmap(0, 16384, "GlobalSharedMemory") This allows to access 16384 bytes of memory, shared across processes, not backed up by a file in the filesystem. Thomas From kkto at csis.hku.hk Mon Nov 10 00:17:36 2003 From: kkto at csis.hku.hk (Isaac To) Date: Mon, 10 Nov 2003 13:17:36 +0800 Subject: recursion vs iteration References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> Message-ID: <7ihe1cn6of.fsf@enark.csis.hku.hk> >>>>> "David" == David Eppstein writes: David> That sounds dishonest. But Fibonacci can be a good example of David> both memoization and dynamic programming, and I would expect the David> iterative linear version to be faster (by a constant factor) than David> the memoized recursive one (also linear due to the memoization). Fibonacci can be computed in logarithmic time with repeated squaring of an appropriate 2x2 matrix. And this, as Terry pointed out, can be done by either recursion or iteration. Actually the phrase "can be done by either recursion or iteration" can be omitted, since every iteration can be turned into a tail recursion without losing efficiency (given the appropriate compiler optimization), and every recursion can be turned into an iteration using a stack; and the primary difference is how they looks (and people disagree even on whether a tail recursion is easier or harder to read than an iteration). Regards, Isaac. From http Wed Nov 19 14:38:01 2003 From: http (Paul Rubin) Date: 19 Nov 2003 11:38:01 -0800 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <3FBB805D.40A8DA75@engcorp.com> <3FBBA68A.6D819C5C@engcorp.com> Message-ID: <7xd6bop2sm.fsf@ruckus.brouhaha.com> Peter Hansen writes: > That's kind of the heart of the matter right there: just how good _is_ > rotor, compared to modern algorithms? Can anyone describe it perhaps > in comparison with DES/3DES using a kind of "equivalent key size" estimate? That's not really a sensible question to ask. The WW2 Enigma machine, for example, had much more key space than DES/3DES, but it was vulnerable to cryptanalytic attacks that were far more effective than brute force. Rotor itself looks to have been written quite carelessly. It's basically a bunch of linear-congruential PRNG's which are notoriously weak as ciphers. > My guess is that it's so insecure that most people wouldn't really want > to use it if they knew how insecure it was, or they would actually decide > that something like XORing the data is actually adequate and stick with > that. It's best to go with that assumption even if breaking rotor is actually a bit harder. > I suspect that those who want rotor actually want something stronger > than it really is, but could actually get by with something even weaker > than it is (though they don't believe that), and leaving it out of the > standard library isn't a real problem, just a perceived one. Actually it's the other way, lots of people think they can get by with rotor or with something weaker, when they really need something stronger. Leaving rotor IN the standard library is a real problem. From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Wed Nov 26 15:11:56 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Wed, 26 Nov 2003 23:11:56 +0300 Subject: How to call functions with list and keyword arguments? In-Reply-To: References: Message-ID: John Z. Smith wrote: > Thanks. I didn't event know that's legal syntax. Just checked the tutorial > and reference > manual but didn't find it. Could you point me to it? Thanks again. > You're welcome. In my ActiveState distributive it's under Python Documentation\Language Reference\Expressions\Primaries\Calls. I hope ActiveState follows standard reference. regards, anton. From vze4rx4y at verizon.net Wed Nov 12 10:26:28 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 12 Nov 2003 15:26:28 GMT Subject: More user feedback on Sets.py References: <1hSqb.1167$bQ3.696@nwrdny03.gnilink.net> Message-ID: [Raymond] > > I have added some backwards compatability code so that Sets.py will run > > Python 2.2. Please give it a test drive: > > > > http://cvs.sourceforge.net/viewcvs.py/*checkout*/python/python/dist/src/Lib/se > > ts.py?content-type=text%2Fplain&rev=1.44.8.4 [Dave Eppstein] > Thanks! Doesn't quite work out of the box, though... > > Python 2.2 (#1, 07/14/02, 23:25:09) > [GCC Apple cpp-precomp 6.14] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import sets > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/site-packages/sets.py", line 79, in ? > class BaseSet(object): > File "/usr/lib/python2.2/site-packages/sets.py", line 109, in BaseSet > def _repr(self, sorted=False): > NameError: name 'False' is not defined Okay, I've added code to make this run with older versions of Py2.2. Still, it's worth downloading the bugfix release 2.2.3 which has True/False in it and a number of important fixups. Raymond Hettinger From jegenye2001 at fw.hu Thu Nov 13 20:06:42 2003 From: jegenye2001 at fw.hu (Jegenye 2001 Bt) Date: Fri, 14 Nov 2003 02:06:42 +0100 Subject: Making a maze.... References: <1PSsb.44675$jy.34613@clgrps13> Message-ID: I saw an annotated and explained piece of C++ code in Crystal Space. Actually the algorithm was described, too, I think Mikl?s Bernard Fields wrote in message news:1PSsb.44675$jy.34613 at clgrps13... > Greets, all. > > > As the title suggests, I'm trying to make a maze. Specifically, it's a > top-down, 2-d maze, preferably randomly generated, though I'm willing to > forego that particular aspect as this point. > > I've done many, many web-searches, but nothing that I've found so far has > provided any clues.... > > From jfranz at neurokode.com Mon Nov 17 05:20:29 2003 From: jfranz at neurokode.com (Jon Franz) Date: Mon, 17 Nov 2003 05:20:29 -0500 Subject: Python Database Objects (PDO) 1.2.0 Released References: <8rtgrvkl8vae90116u3opgdn2inias1ti4@4ax.com> Message-ID: <009c01c3acf4$6d2f25f0$7401a8c0@voidmk9> I'll reply to this, if that's ok. Keep in mind I can't sleep, so typos may abound. I guess what PDO comes down to is (an attempt at) ease-of-learning and ease-of-use without sacrificing power. PDO is built on the DBAPI, but just provides a (hopefully) higher-level interface. Having said that, lets dive into the differences between a DBAPI cursor and a PDO Resultset. A Resultset is actually very different from a cursor - The first and most blatant difference being that with a Resultset, you get column access by name. With a DBAPI cursor, you create the cursor first, then perform an execute on the cursor, then do a fetchXXX (depending upon if you want one row at a time or many, or all). The data returned is separate from the cursor, and is a sequence of sequences. If you do a fetchmany or fetchall, iteration over the results is your responsibility. Also, data about the result columns is stored separately from the columns themselves, in a .description field of the cursor. PDO Resultset objects are created with the same statement in which you perform your query, no manual cursor creation required beforehand. PDO Resultsets also allow for easy transversal of the results, in a forwards or backwards or random manner, via the .move(x), .next(), .prev(), .moveto(n) and other methods. Each method will return 0 if the destination is out-of-bounds. Data about the columns is accessed as if it were intrinsic to the columns - thus Resultset columns in PDO are objects with member variables. Here's a quick example of a simple query and loop-over results, first via DBAPI, then via PDO. DBAPI: import MySQLdb mycon = MySQLdb(user='test', passwd='foobar', db='sample') mycursor = mycon.cursor() mycursor.execute("SELECT * FROM Customers") results = mycursor.fetchall() for row in range(0, len(results)): print "Name: " + row[1] print "Address: " + row[3] print "Size of 'Name' column in the db: " + str(mycursor.description[1][3]) ------------ PDO: import pdo mycon = pdo.connect("module=MySQLdb;user=test;passwd=foobar;db=sample") results = mycon.open("SELECT * FROM Customers") while results.next(): print "Name: " + results['Name'].value print "Address: " + results['Address'].value print "Size of 'Name' column in the db: " + str(results['Name'].length) -------------------------------- ~Jon Franz NeuroKode Labs, LLC ----- Original Message ----- From: "Rene Pijlman" To: Sent: Monday, November 17, 2003 2:27 AM Subject: Re: Python Database Objects (PDO) 1.2.0 Released > Bryan J Gudorf: > >PDO, an open source python module for interfacing with RDBMS (SQL > >databases), has now reached 1.2.0! > > I just browsed the documentation, but I don't quite understand what > advantages PDO offers over using DBAPI directly. A resultset object looks > very similar to a cursor. > > What are the advantages IYO? > > -- > Ren? Pijlman > > From bgailer at alum.rpi.edu Thu Nov 6 21:08:50 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 06 Nov 2003 19:08:50 -0700 Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) In-Reply-To: References: <3fbqb.97878$e5.3584611@news1.tin.it> Message-ID: <6.0.0.22.0.20031106185516.0305fdf8@66.28.54.253> At 03:41 PM 11/5/2003, Francis Avila wrote: >"Alex Martelli" wrote in message >news:3fbqb.97878$e5.3584611 at news1.tin.it... > > Stephen C. Waterbury wrote: > > If you want to abuse reduce at all costs for this purpose, > > reduce(lambda x, y: x.update(y) or x, l) might work. > >Just out of curiosity, for what kind of problems do we find reduce to just >be the Right Way? I mean, summing a big list of numbers is fun and all, but >I never find any use for it otherwise. I *often* try to think if reduce >would be useful when I come across some collection-of-values manipulation >task, but usually one wants to repeat an operation on a whole set of values, >not reduce the set to one value. > >So, are there any *non-trivial* and *unabusive* uses of reduce, where any >other way would be tedious, repetitive, slow, unclear, etc.? I'm very >curious to see them. One's prior programming experience can affect one's view of reduce. My favorite language, prior to Python, was APL. APL's native data container is the array, and reduce is a native operator in APL. So we used reduce a lot, sometimes to add things up, other times to check for all or any conditions, other times for other at this moment forgotten purposes. A companion of reduce in APL is scan, which did reduce but preserved all the intermediate values (cumulative sum for example). To expand your reduce horizons in Python, consider reduce as a way to examine the relationship between successive pairs of a sequence. For example one might wants the difference between successive elements: given seq = [1,3,4,7] we'd like a differences == [2,1,3]. differences = [] def neighborDifference(left, right): differences.append(right - left) return right reduce(neighborDifference, seq) Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.532 / Virus Database: 326 - Release Date: 10/27/2003 From alan.gauld at btinternet.com Fri Nov 7 03:59:02 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 07 Nov 2003 08:59:02 GMT Subject: Need help with OOP References: Message-ID: <3fab5cd1.210539750@news.blueyonder.co.uk> On Fri, 7 Nov 2003 05:36:57 +0100, sinisam wrote: > Object oriented programming is not a new term to me, but ... > I did my share of programming several years ago... Don't worry if OOP takes aq while to sink in, thats pretty common, especially if you've been trained in procedural styule programming - you have to learn to change your approach to problem solving. It might be worth going through some of the beginners tutors on the Python web site, most of which - including mine! ;-) - have a section on OOP. > "Make class for the IP address. It should be initialized from the > string. Later on, we can add functions to it." > > [1] What in the world I have to do here? Turn an IP address into an OOP object. > [1a] How to make class for the IP address? What does it mean? Read the tutorials, they will take you step by step through the comcepts. > [2] "Initialization from the string" means something like passing > arguments from the command line...? A little bit, but as part of the initialisation call of your object. Python contains lots of objects. For example files are objects. You create a file object by passing the filename as a parameter: f = file("foo.txt") f is now a file object that you can maniplulate. You are being asked to provide a similar facility for IP addresses: ip = IPaddress("123.234,321.34") > I started looking for good literature. Try the beginners tutors and also for the theoretical understanding visit www.cetus-links.org which is a huge OOP portal site. > P.P.S. Speaking of being illiterate, no, English is not my native > language. Just in case someone wanders... :o) You're doing just fine on that front. Better than some who do ave English as their native tongue! :-) Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From phil at riverbankcomputing.co.uk Mon Nov 17 17:50:47 2003 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Mon, 17 Nov 2003 22:50:47 +0000 Subject: PyQt, Qt, Windows and Linux In-Reply-To: <2biirvglh445uvfgba500mkmu3o3sjo0oj@4ax.com> References: <2biirvglh445uvfgba500mkmu3o3sjo0oj@4ax.com> Message-ID: <200311172250.47696.phil@riverbankcomputing.co.uk> On Monday 17 November 2003 10:21 pm, Jim wrote: > >> One person (I think is was someone from theKompany) said that there was > >> no functional difference between the Personal Edition and the Business > >> Edition but I think you just told me the opposite. If I buy the Personal > >> Edition and use it to write my program, I won't have the capability to > >> run that software on any other computer besides my own (personal to me) > >> ... not even my wife's computer downstairs, i.e., so the runtime > >> elements don't come with the Personal Edition - which makes it > >> functionally different? > > > >No, the functionality is the same (but is a subset of "normal" PyQt). > > Yikes, what is "normal" PyQt? So the version of PyQt that comes with > BlackAdder is just a subset of "normal" PyQt ... How does one obtain the > "normal" version of PyQt and what are the advantages? If I'm spending > money, I want to get it right the first time around ;) "Normal" PyQt is what is available from www.riverbankcomputing.co.uk, either under the GPL (not for Windows) or a commercial license. It does not include a copy of Qt - you need to get that separately with an appropriate license. Functionally BlackAdder PyQt is based on the Professional Edition of Qt (plus a couple of extras - see theKompany website for details). "Normal" PyQt is based on the Enterprise Edition (which is the same as the GPL version) plus QScintilla support. Phil From pf_moore at yahoo.co.uk Wed Nov 12 18:19:32 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Wed, 12 Nov 2003 23:19:32 +0000 Subject: What's an "atomic" operation (in a threaded context)? References: <3FB2B8E6.247500D1@engcorp.com> Message-ID: Peter Hansen writes: > In a nutshell, your "single bytecode operation" theory is correct, > and each of the above lines represents a single bytecode. Therefore > the only line which matters is STORE_SUBSCR (the actual assignment) > and it is atomic, so you can have any number of threads running but > no matter how they try, they won't be able to interrupt each other's > STORE_SUBSCR operations and the dictionary will stay in a consistent > state. Thanks. I think I'd got bogged down in C-level thinking ("STORE_SUBSCR can reallocate the dictionary, so it's address changes, so doesn't that mean another thread might have loaded its address and then it moves...") > Much or most of the time, basic operation such as this on the standard > mutable primitive types (i.e. lists, dictionaries) are atomic/safe for > use in the way you wish to use them, without needing locks. That's good to know. And the trick of using dis to analyze it will help as well. Thanks for the explanation, Paul -- This signature intentionally left blank From peter at engcorp.com Thu Nov 27 16:15:15 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 27 Nov 2003 16:15:15 -0500 Subject: Ques From CS Grad Student References: Message-ID: <3FC66963.2F74392F@engcorp.com> suenacita1 wrote: > > Hi. I'm a masters student at the George Washington University > currently taking an Open Source Software Development course. One of > our assignments was to do a presentation on an open source project > and i chose Python. I have most of my presentation done but had a > couple questions where I want the help of the Python community to > help me answer. > > 1. How many members are involved directly, and how many peripherally? > 2. What do you use to drive releases? > 3. How often does the project release major and minor revisions? > 4. What tools do they use to manage the source? > 5. How does the Python project resolve conflicts between members? I'm sorry to say it, but the fact that you haven't got an answer to question 3, at least, hints strongly that you've made very little effort at all to research this on your own! Go to www.python.org and spend a few minutes in surfing and thought and you'll at least answer that one question on your own. I suspect several of the other questions would be almost as easily answered, perhaps with reference to the list archives. And some of the questions are next to useless, and appear to be repeated verbatim from some generic questionnaire that everyone in the course is expected to use. "Drive releases"? What is that supposed to mean? The text editor used? The revision control system? The process? What type of car they used to get to the sprints? :-) -Peter From stuartf at the-i-junction.com Fri Nov 7 02:45:30 2003 From: stuartf at the-i-junction.com (Stuart) Date: Fri, 7 Nov 2003 09:45:30 +0200 Subject: Unicode Hell Message-ID: <2SmdnSziee5L0DaiU-KYhg@is.co.za> I'm trying to do something seemingly easy yet it is proving incredibly frustrating. Perhaps it is due to my relatively new acquaintance with Python. In a web environment (ASP with python scripting) I have one form posting information to another form. The contents of the posting variable (lets call it cVal1 for simplicity) is non ascii characters, lets say ????? for example. On the second page a simple: cVal1 = Request("cVal1 ") Response.Write(cVal1) Writes the values to the screen correctly. What I really want to do is replace a field place holder with those values. So if we have a string cReplaceString = "I want to replace #here#" I'd like to replace the #here# with the values of a (or ?????) Please help Regards Stuart From rm at rm.net Sun Nov 16 06:48:28 2003 From: rm at rm.net (Roel Mathys) Date: Sun, 16 Nov 2003 11:48:28 GMT Subject: Bug or Feature with (overriding) Class Variables? In-Reply-To: References: Message-ID: # on python 2.3.2 class foo (object) : dict = {} string = "foostring" def bar(self): self.dict["bar-key"] = "bar-value" # is the same as # self.dict.__setitem__( "bar-key" , "bar-value" ) # which tries to look up self.dict # try: # self.dict2["bar-key"] = "bar-value" # which results in an attribute error self.string = "bar-string" # is adding an attribute string to the instance # foo.string remains accessible baz = foo() baz.string is foo.string => True baz.bar() baz.string is foo.string => False bye, rm From adalke at mindspring.com Tue Nov 11 14:42:07 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 11 Nov 2003 19:42:07 GMT Subject: response time References: <1jSrb.2419$9_.105379@news1.tin.it> <87d6bzetsz.fsf@pobox.com> <3FB01787.529425BC@engcorp.com> <87u15bf6qs.fsf@pobox.com> Message-ID: Alex: > We _are_ talking about more than 20 years ago, after all (and I'm > sure none of those designers could possibly dream that their numbers > had to be chosen, not for ONE computer model, but for models that > would span 15 or more turns of Moore Law's wheel...!_). I am hoping for symbolic reasons that in another couple of years it will be possible to buy a 4.77 GHz processor. Then place it side-by-side with an original PC and gape at the differences. 1000x clock speed (and 100,000x performance?), 200,000x more memory, 1,000,000x more disk space. Andrew dalke at dalkescientific.com From mwh at python.net Wed Nov 5 07:47:16 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 5 Nov 2003 12:47:16 GMT Subject: Memory leak in python-2.2.3 on solaris? References: <6205cf4c.0311040750.461213e9@posting.google.com> Message-ID: <7h3llqvhtoo.fsf@pc150.maths.bris.ac.uk> edahl at mindspring.com (Erwin Dahl) writes: [...] > I'm on solaris 2.8 and python is built with gcc 3.2.2. The program > doesn't use many libraries the ones that I haven't been able to pull > when debuging are socket and select so I suspect them. Some dusty memory says something about leaks in the socket module. You might want to look at the CVS logs (or even try release22-maint, I guess). Cheers, mwh -- ROOSTA: Ever since you arrived on this planet last night you've been going round telling people that you're Zaphod Beeblebrox, but that they're not to tell anyone else. -- The Hitch-Hikers Guide to the Galaxy, Episode 7 From hrmrv at yahoo.com Sat Nov 1 07:07:38 2003 From: hrmrv at yahoo.com (Harish Vaidya) Date: Sat, 1 Nov 2003 04:07:38 -0800 (PST) Subject: multiple check boxes In-Reply-To: Message-ID: <20031101120738.11099.qmail@web41511.mail.yahoo.com> thanks sir...... it worked thanks once agian it served my purpose regards --- Peter Otten <__peter__ at web.de> wrote: > Harish Vaidya wrote: > > > > > hi, > > i am trying to use multiple checkboxes. > > what is happening is once select check box its > > variable is not getting set. below is the code. > what > > could be the problem? i am using python 2.0 > > thanks in advance > > I do not fully understand what you're are trying to > achieve with your code, > but this observation might help you anyway: > > [...] > > b1 = Button(top, > > text='OK!',command=TestCases()) > [...] > > b = Button(root, text='OK!',command=hostTC()) > [...] > > In both cases you do the eqivalent of > > b = Button(..., command=None) > > as both TestCases() and hostTC() do not explicitly > return a value. > You probably want the buttons to invoke TestCases() > or hostTC(), and you > therefore must omit the trailing (), e. g.: > > b = Button(root, text='OK!',command=hostTC) > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list __________________________________ Do you Yahoo!? Exclusive Video Premiere - Britney Spears http://launch.yahoo.com/promos/britneyspears/ From philh at invalid.email.address Tue Nov 11 22:33:50 2003 From: philh at invalid.email.address (phil hunt) Date: Wed, 12 Nov 2003 03:33:50 +0000 Subject: I have a question?? References: Message-ID: On Tue, 11 Nov 2003 07:06:26 -0500, Ryan Silverwood wrote: >I want to write a python program which will calculate a person's net annual income after tax, given the following rules: >*The first 1500 is tax free >*any amount earned over ?1500 and upto ?35000 is taxed at 30% >*and amount earned over ?35000 is taxed at 45% infinity = 999999 taxRates = [ [1500, 0], [35000-1500, 30], [infinity, 45] ] def calcNetIncome(gross): if youAreAskingUsenetToDoYourHomework: taxRate = 100 net = gross * (100-taxRate)/100 return net -- "It's easier to find people online who openly support the KKK than people who openly support the RIAA" -- comment on Wikipedia (Email: , but first subtract 275 and reverse the last two letters). From davesum99 at yahoo.com Fri Nov 14 10:46:23 2003 From: davesum99 at yahoo.com (smarter_than_you) Date: 14 Nov 2003 07:46:23 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <2259b0e2.0311140033.4e3ca8ea@posting.google.com> Message-ID: "Brandon J. Van Every" wrote in message news:... > Chinese philosophies, at least as received by Westerners looking for > alternatives to their high stress culture, often have the flaw of being too > Yin. The Tao is balance, not passivity. Sun Tzu ("The Art of War") was Chinese. From jcwiese at yahoo.com Tue Nov 18 18:13:49 2003 From: jcwiese at yahoo.com (Jim) Date: 18 Nov 2003 15:13:49 -0800 Subject: Pyhon Extensions linker error, unresolved symbols Message-ID: <1b998b5f.0311181513.3ff306a4@posting.google.com> All, I'm trying to debug a Python GPF while running a script that we've written. After fixing up some of the paths for the Python build and successfully building Python from ActiveState source, I compiled the Python Extensions, but am getting the following error: ------ Build started: Project: PyWinTypes, Configuration: Release Win32 ------ Linking... Creating library Build\PyWinTypes.lib and object Build\PyWinTypes.exp PyWinTypesmodule.obj : error LNK2001: unresolved external symbol "struct _object * __cdecl PyWinMethod_NewSECURITY_ATTRIBUTES(struct _object *,struct _object *)" (?PyWinMethod_NewSECURITY_ATTRIBUTES@@YAPAU_object@@PAU1 at 0@Z) PyWinTypesmodule.obj : error LNK2019: unresolved external symbol "struct _typeobject PySECURITY_ATTRIBUTESType" (?PySECURITY_ATTRIBUTESType@@3U_typeobject@@A) referenced in function _initpywintypes Build\System\PyWinTypes22.dll : fatal error LNK1120: 2 unresolved externals Build log was saved at "file://e:\Python\Source\ActivePython-2.2.3-226\src\PyWin32\win32\Build\Temp\PyWinTypes\Release\BuildLog.htm" PyWinTypes - 3 error(s), 0 warning(s) ---------------------- Done ---------------------- Build: 0 succeeded, 1 failed, 0 skipped ------ Build started: Project: PyWinTypes, Configuration: Release Win32 ------ Linking... Creating library Build\PyWinTypes.lib and object Build\PyWinTypes.exp PyWinTypesmodule.obj : error LNK2001: unresolved external symbol "struct _object * __cdecl PyWinMethod_NewSECURITY_ATTRIBUTES(struct _object *,struct _object *)" (?PyWinMethod_NewSECURITY_ATTRIBUTES@@YAPAU_object@@PAU1 at 0@Z) PyWinTypesmodule.obj : error LNK2019: unresolved external symbol "struct _typeobject PySECURITY_ATTRIBUTESType" (?PySECURITY_ATTRIBUTESType@@3U_typeobject@@A) referenced in function _initpywintypes Build\System\PyWinTypes22.dll : fatal error LNK1120: 2 unresolved externals Build log was saved at "file://e:\Python\Source\ActivePython-2.2.3-226\src\PyWin32\win32\Build\Temp\PyWinTypes\Release\BuildLog.htm" PyWinTypes - 3 error(s), 0 warning(s) ---------------------- Done ---------------------- Build: 0 succeeded, 1 failed, 0 skipped Do you have any ideas why this would happen? (FYI: I'm including the python22.lib on the linker line in case you're wondering) Thanks, Jim From s-rube at uselessbastard.net Sun Nov 9 22:31:55 2003 From: s-rube at uselessbastard.net (Eric Williams) Date: Mon, 10 Nov 2003 04:31:55 +0100 Subject: Help with Apache 2.0.47 and CGI References: Message-ID: Fausto Arinos de A. Barbuto wrote: > > Hi All; > > I have Apache 2.0.47 installed for a single user on port 8080, Python > 2.3.2 on C:\Python23 and ActiveState's Perl on C:\Perl. Everything seems > to work fine after the changes I made in httpd.conf, but I can't for some > reason run Python scripts that sit on this computer's cgi-bin directory > (Perl > scripts run ok). The message I get in either IE 6 and Netscape 7.1 is > "Internal Server Error". Have any of you had similar experience? > > Another peculiar thing is that Perl scripts run OK in Netscape 7.1, > although IE 6 tries to *download* .pl files instead of running them -- as > if I were ftp-ing a file from some web site. Any clues? > Hallo, Fausto, You might make sure there's an entry like this: AddHandler cgi-script .cgi .py .pl in either httpd.conf or an .htaccess file for your cgi-bin directory. (Or use .pyw instead of .py if your programs are like that. ) You should find a similar entry somewhere for .pl or .cgi files, so just add it there. I've never used apache on windows, but that's necessary on linux/solaris. As for the 500 error, you might try to run the files from the command-line as well, to make sure they aren't crashing and sending tracebacks before returning to the cgi-handler. Make sure python's in your path, of course. If all else fails, add the following line to the import section of your python cgi scripts: import cgitb; cgitb.enable() This can be helpful in debugging, as tracebacks get sent correctly to the cgi-handler instead of bombing out to stderr, causing an "incomplete headers" 500 error. Hope something there helps! cya, Eric -- --- s- should be removed to contact me... From aleaxit at yahoo.com Wed Nov 5 18:13:53 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 05 Nov 2003 23:13:53 GMT Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FA980A1.4C86AED0@alcyone.com> Message-ID: Erik Max Francis wrote: ... > Francis Avila wrote: > >> Just out of curiosity, for what kind of problems do we find reduce to >> just >> be the Right Way? I mean, summing a big list of numbers is fun and >> all, but >> I never find any use for it otherwise. I *often* try to think if ... > I don't use reduce extremely routinely, but I certainly do find myself > using it. Grepping through my Python sources, the most common uses I > find are summing together lists of numeric values and joining together In Python 2.3, we have sum for that (much faster, too). > (flattening) a list of lists (though only when the contained lists > themselves do not contain any sequences as elements). _UN_fortunately sums works for that too -- but almost as slowly as reduce. E.g., on a small example: [alex at lancelot bo]$ timeit.py -c -s'lol=[range(20)]*20' 'reduce(list.__add__, lol, [])' 10000 loops, best of 3: 91 usec per loop [alex at lancelot bo]$ timeit.py -c -s'lol=[range(20)]*20' -s'import operator' 'reduce(operator.add, lol, [])' 10000 loops, best of 3: 88 usec per loop [alex at lancelot bo]$ timeit.py -c -s'lol=[range(20)]*20' 'sum(lol, [])' 10000 loops, best of 3: 82 usec per loop while a simple loop is way faster: [alex at lancelot bo]$ timeit.py -c -s'lol=[range(20)]*20' 'x=[]' 'for l in lol: x.extend(l)' 10000 loops, best of 3: 26 usec per loop and can easily be sped up a little more: [alex at lancelot bo]$ timeit.py -c -s'lol=[range(20)]*20' 'x=[]' 'xe=x.extend' 'for l in lol: xe(l)' 10000 loops, best of 3: 20 usec per loop Given the typical use cases of reduce are covered by sum -- and sometimes even better by simple loops &c -- then I would say that in Python 2.3 and following reduce should not be used often at all. Alex From kylotan at hotmail.com Sun Nov 23 21:59:16 2003 From: kylotan at hotmail.com (Kylotan) Date: 23 Nov 2003 18:59:16 -0800 Subject: What exactly are bound methods? Message-ID: <153fa67.0311231859.551b673@posting.google.com> Although I see lots of references to them in various documentation, I can't find a decent explanation of exactly what they are. I'm guessing that it's a reference to a method that remembers which object it came from, and that when it's called, it passes that object as the first parameter (which would conventionally be 'self'). Is this correct? -- Ben Sizer From Raaijmakers, Vincent (IndSys, Wed Nov 19 14:59:23 2003 From: Raaijmakers, Vincent (IndSys, (Raaijmakers, Vincent (IndSys,) Date: Wed, 19 Nov 2003 13:59:23 -0600 Subject: PIL and jpg -> png conversion, do I really need java for this??? Message-ID: <971323274247EB44B9A01D0A3B424C850372A7A1@FTWMLVEM02.e2k.ad.ge.com> Guys, I gave up. I can't figure out why the PNG converted in PIL won't work in the MIDP applications written in Java. There is something different but I really don't know what. All PNG generated from ImageMagick, GIMP or whatever, they work fine, from PIL, no. The conversion in Java using JIMI works fine as well. The option of executing scripts from Python using these external tools is not really what I like. My Java colleagues are laughing at me because my statement of my giant productivity using python is gone with the wind here. I'm struggling now for 2 days. First to prove that nothing went wrong in the communication channels and secondly that it was the PIL conversion. Because I'm doing the server side, and my java colleagues the client side of the application, I'm running way behind. Please don't let me do programming with Java. I can't make any statements anymore doing server programming with python. I really need hints, tools, urls. What can I use to verify that the PNG file is correct or different from other png's or the Java libraries poor. Googles performance is already down because of my daily search activities. Help. Vincent From john_bradbury at skiptalk21.com Wed Nov 12 13:04:54 2003 From: john_bradbury at skiptalk21.com (John Bradbury) Date: Wed, 12 Nov 2003 18:04:54 +0000 (UTC) Subject: GUI - Qt Designer Message-ID: Is there any way to take the output produced by Qt designer (or any other GUI designer) and use it in Python to create a screen? There must be a better way of creating screens than having to use the TkInter routnes and add every widget one by one in the program. John Bradbury From peter at engcorp.com Mon Nov 3 16:09:20 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Nov 2003 16:09:20 -0500 Subject: Does python always need to compile ENTIRE program before it can start to run it??? References: <1093E8BAEB6AD411997300508BDF0A7C1571EE7B@ushem204.exse01.exch.eds.com> Message-ID: <3FA6C400.C0FAE7AA@engcorp.com> seberino at spawar.navy.mil wrote: > > Lance > > Thanks for the info. I agree that the initial script you > run must be compiled completely before it can execute. > Does "completely" = all the imported modules too? No, compilation is a separate step *prior* to execution, and "import" is a statement that is *executed*, not something special that happens during compilation. -Peter From alanmk at hotmail.com Wed Nov 19 16:01:16 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 19 Nov 2003 21:01:16 +0000 Subject: Looking for an http proxy server written in Python References: <3FBA38B9.42F93370@hotmail.com> Message-ID: <3FBBDA1C.A66C46A5@hotmail.com> Chris Gray wrote: > Your resource page is very helpful and your "Why" section explains > exactly why I'm interested in this. At first blush it looks like > httpMonitor is most in line with what I'm planning, namely, the > ability to do arbitrary processing on requests and responses. I've tried to make the page a little more useful now, by adding freshness dates, and a better overview of the features offered by the various proxies. http://www.xhaus.com/alan/python/proxies.html > That's why I specified production-quality and HTTP/1.1 compliance. If I > could just find a proxy server that forwarded requests and responses > seamlessly, I'd be happy. FWIW, I mostly run a very simple proxy, derived from Suzuki Hisao's Tiny proxy, to do protocol and resource logging, which I need when I'm doing functional and load testing. I store the output in python syntax, to be fed straight back into a python program. One of these days I might clean it up a little and release it. If you have any comments about the page, I'd be happy to hear them. One of these days, I'm going to a full-on software review of the proxies for a variety of different purposes. Content filtering and blocking seems to be much in demand. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From tim.one at comcast.net Mon Nov 24 13:23:27 2003 From: tim.one at comcast.net (Tim Peters) Date: Mon, 24 Nov 2003 13:23:27 -0500 Subject: strange exponentiation performance In-Reply-To: Message-ID: [Tim] >> ... Knuth Volume 2 has an extensive discussion of this ("Evaluation >> of Powers"); another algorithm based on first factoring the exponent >> (expressing it as a product of primes) is better "on average" than >> either binary method, but sometimes loses to them. [Jeff Davis] > Ahh... I'm on vol. 1. I saw that it would be a while before I made it > to page 100, so I actually loaned out vol. 2. I'll be getting that > back now I guess :) On second thought, Knuth may not be helpful here: he's overwhelmingly concerned with minimizing the number of multiplications performed, which is "interesting" only if all multiplications take the same amount of time. With ordinary care in coding, the left-to-right and right-to-left binary exponentiation methods do exactly the same number of multiplications, so there's no basis for favoring one based on that alone. But large-int multiplications vary wildly in expense. For example, it's enormously more expensive to square a million-bit int than to multiply a million-bit int by a 10-bit int. The left-to-right and right-to-left methods *do* differ in expense when that's taken into account too (left-to-right is usually cheaper, in essence because each step either squares or multiplies by the *original* base, while each step in R-to-L either squares or multiplies two ever-growing intermediate results), and I don't think Knuth talks about this complication. Offhand, I don't know of anyone who does talk about it! A few hours of Googling on it may be an interesting project for you. One reason it may be hard to find info about this is that raw exponentiation of unbounded integers has few practical use cases. In real life, modular exponentiation (Python's pow(a, b, c)) is overwhelmingly more common, and then all intermediate results are bounded above by c, so there's an upper bound on the expense of each multiply too, and then "all multiplications cost the same" is closer to being true. If a is very small compared to c, though, I still expect L-to-R to have an advantage. don't-forget-to-come-up-for-air-ly y'rs - tim From alanmk at hotmail.com Tue Nov 25 06:59:55 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 25 Nov 2003 11:59:55 +0000 Subject: Execution state persistence for workflow application References: Message-ID: <3FC3443B.92709051@hotmail.com> [Serge Orlov] >> The problem is that one day you will >> have to upgrade your program and your last dumpexec won't be >> compatible with your next loadexec(). You will have to separate >> code from data to do it. So it means execution persistence is not >> enough for real life use. Why not just use data persistence alone? [Paolo Losi] > In fact data persistence is not sufficient to stop and resume scripts > in case, for example, system reboot. > I do want my workflow scripts to resume exactly (and with the same > globals/locals setup) where they left... > > The real alternative would be to define a new script language > with standard constructs (for, while,...) but again... i don't want > to reinvent the wheel. > > I do not seen execution persistence as an alternative to data > persistence: I would need both. You might want to investigate Stackless python, an excellent research work which can save and resume execution state, to some degree. Try the following google query http://www.google.com/search?q=pickling+site%3Astackless.com HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From bokr at oz.net Sun Nov 23 12:14:34 2003 From: bokr at oz.net (Bengt Richter) Date: 23 Nov 2003 17:14:34 GMT Subject: Empty list as default parameter References: <7xislb238p.fsf@ruckus.brouhaha.com> <7xsmkf1uwk.fsf@ruckus.brouhaha.com> Message-ID: On 23 Nov 2003 16:33:37 GMT, bokr at oz.net (Bengt Richter) wrote: [...] >to code explicitly in any case. E.g., is it obvious that getattr(os, 'RD_ONLY') >should be done at call time or optimized away to def time in os.open('foo.txt', os.RD_ONLY) ? I meant during os.open('foo.txt') assuming def open(...) had a default mode expressed as an attribute expression. But that's bad as a real example. So please assume a customized file opener that uses os.open and has a default mode parameter os.RD_ONLY ;-) >I don't think you can optimize it away without telling the compiler one way or another, >or changing the dynamic nature of the language. > >In any case it would be a semantic change, and I'd hate to have the job of finding breakage ;-) > I'll leave that as is ;-) Regards, Bengt Richter From kirk at strauser.com Sat Nov 15 18:00:07 2003 From: kirk at strauser.com (Kirk Strauser) Date: Sat, 15 Nov 2003 23:00:07 GMT Subject: OT Re: Matrix - Metaphors, Analogies and the REAL References: <9447377298731260.NC-1.60.joobs@news.free-online.net> <944913851691266.NC-1.61.joobs@news.free-online.net> <1Ihtb.1378$Wy4.787@newsread2.news.atl.earthlink.net> Message-ID: <87k7612q83.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2003-11-15T04:11:41Z, 3seas <3seasA at Tthreeseas.DOT.not> writes: > Kirk S. no longer supports the FAQ that was fabricated... - From Webster's Revised Unabridged Dictionary (1913) [web1913]: Fabricate \Fab"ri*cate\, v. t. [imp. & p. p. {Fabricated}; p. 1. To form into a whole by uniting its parts; to frame; to construct; to build; as, to fabricate a bridge or ship. If that was your intented denotation, then, yes, I "fabricated" a FAQ a few years ago. It was roughly about the time you were trying to convince the world that you were, literally, the second coming of The Messiah. Please leave me out of your discussions, fantasies, and delusions. *plonk* - -- Kirk Strauser -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/tq/C5sRg+Y0CpvERAiH9AJ0WAfhWGLo0yEqXlX0iiJiq/rQ9KQCghRGK bn7ybD5W1Lq20KEkT/76XMc= =WtWP -----END PGP SIGNATURE----- From hwlgw at hotmail.com Fri Nov 7 03:52:19 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 7 Nov 2003 00:52:19 -0800 Subject: PEP 289: universal and existential operators References: <5d83790c.0310231158.65595858@posting.google.com> <9f76ee00.0311051257.45461381@posting.google.com> Message-ID: > [Jess Austin] > ...It seems like the consensus is "all" and "any". Oh no! Their mathematical names are "forall" and "exists" and that is what they should be IMO. Any programmer I can think of is familiar with "forall" and "exists" in mathematics. -- I have learned silence from the talkative, toleration from the intolerant, and kindness from the unkind. -- Kahlil Gibran From joconnor at cybermesa.com Fri Nov 21 10:40:07 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Fri, 21 Nov 2003 08:40:07 -0700 Subject: Garbage collection working improperly? In-Reply-To: References: Message-ID: Diez B. Roggisch wrote: > Hi, > >> Builds up a great list in memory and immediately deletes it. >> Unfortunately > > > if all you want is to create a loop, use xrange instead of range - it > won't create that huge list. > >> the task manager shows me that i allocated about 155MB in memory before >> del(), but del only releases about 40MB of them so i'm leaving about >> 117 MB >> of reserved memory after deleting the list. >> I'm using python 2.2.3 on WinXP. >> Any ideas about that? How can i dealloc the left memory space? > > > Nope, no idea - the only thing that I can think of is that python not > necessarily releaseses the memory because it uses its own allocation > scheme. I don't know that for sure, but I definitely would go for such > a thingy if I was to implement a virtual machine. > Its like in JAVA - each object instantiation and destruction isn't > paired with system malloc/free calls, but some internal memory manager > deals with that. And if it rans out of space, it will request more > from the system. I kinda like VisualWorks Smalltalk's approach. It uses a system whereby new objects are scavenged aggresivly and objects that survive the scavenger are moved to a different memory space that is not GC'ed nearly as much. (New objects tend to have short lives..objects that survive several generations of scavenging tend to live longer) When it's memory reaches a threshold, it makes a decision as to whether to either request more from the OS or to GC the old object memory space in an attempt to free more memory. The nice part is that you can configure a. how much memory it starts with b. at what point the threshold is set for and c.the weighting of the algorithim to determine whether to GC or allocate Take care, Jay From aleaxit at yahoo.com Fri Nov 14 02:56:35 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 14 Nov 2003 07:56:35 GMT Subject: Books I'd like to see References: <2259b0e2.0311132223.11af146a@posting.google.com> Message-ID: Michele Simionato wrote: ... > But Python is designed in such a way that a lot of it can be taught > without talking about objects. Yes, you are right that in its heart > it is very strongly object oriented (maybe even more than Java or Ruby), I don't know about "more than Ruby" -- Ruby's pretty thoroughly OO, too. I'd call it a wash. > but NOT on the surface. This is on purpose and I think it is a good > thing (for teaching purposes and for other reasons too). I would welcome To teach people coming from other procedural languages, yes. To teach total beginners, I dunno; Smalltalk (arguably even more OO than Ruby or Python, as even 'if' is not a statement but a message sent to a boolean object for example) was in part designed to teach children. I'm not sure how I would go about starting out with OO, but it's presumably a respectable theory. Are there books based on that theory for any language, btw? > a metaprogramming/advanced OOP book by the Martellibot, but this would NOT > be a book for beginners. If it had "advanced" in the title it sure wouldn't:-). > Actually I was confused by the tutorial that you liked so much, since > when I first read it I knew nothing about OOP. I don't think talking > immediately about OOP would be helpful for a total beginner. On the I don't think Guido's tutorial is oriented to total beginners at all. > other hand, if you already knew OOP from another language, then you > are an experienced enough programmer and you can learn Python from > the Nutshell, isn't it? But the Nutshell only gets into OO _after_ it has covered functions, flow control, etc; it doesn't _start_ from OO, which is the original poster's request. Alex From eppstein at ics.uci.edu Sun Nov 16 17:21:43 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 16 Nov 2003 14:21:43 -0800 Subject: Python's simplicity philosophy References: <3FAC19F0.284DCB03@alcyone.com> <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> Message-ID: In article , "Andrew Dalke" wrote: > > >That would be max(seq, key=len) in my proposal. > > > > That's a nice option for max (and min, and ??), but ISTM that it would > > also be nice to have a factory for efficient iterators of this kind. > > It would probably be pretty efficient then to write > > > > maxlen, maxitem = max(funumerate(len,seq)) > > With generator expressions this is > > maxlen, maxitem = max( ((len(x), x) for x in seq) ) > > It still has the (slight) problem that it assumes x is comparable > when there are multiple items with the same length. Nearly > all of these quicky versions make that assumption. The > quicky will-work-for-any-item version would look more like > > maxlen, pos, maxitem = max( ((len(x), i, x) for i, x in enumerate(seq)) ) The new sort(key=...) option works even when the underlying objects are incomparable. I'd expect the same of max(key=...) So (supposing such a change ever happens) you could instead write maxitem = max(seq, key=len) maxlen = len(maxitem) -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Nov 12 13:12:33 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 12 Nov 2003 19:12:33 +0100 Subject: guten tag In-Reply-To: References: Message-ID: <3fb27813$0$58699$e4fe514c@news.xs4all.nl> Gerhard H?ring wrote: > I just informed the sender that (s)he apparently sent this to the wrong > email address. Are you sure? I also got this (German) message of you in this group... --Irmen From not.available at na.no Mon Nov 3 01:03:56 2003 From: not.available at na.no (Noen) Date: Mon, 03 Nov 2003 06:03:56 GMT Subject: nearest neighbor in 2D In-Reply-To: References: Message-ID: John Hunter wrote: > I have a list of two tuples containing x and y coord > > (x0, y0) > (x1, y1) > ... > (xn, yn) > > Given a new point x,y, I would like to find the point in the list > closest to x,y. I have to do this a lot, in an inner loop, and then I > add each new point x,y to the list. I know the range of x and y in > advance. > > One solution that comes to mind is to partition to space into > quadrants and store the elements by quadrant. When a new element > comes in, identify it's quadrant and only search the appropriate > quadrant for nearest neighbor. This could be done recursively, a 2D > binary search of sorts.... > > Can anyone point me to some code or module that provides the > appropriate data structures and algorithms to handle this task > efficiently? The size of the list will likely be in the range of > 10-1000 elements. > > Thanks, > John Hunter > > You could to a for loop, and inside that loop you will have a variable lessest_distance. I dont know much geometric mathematics, but Im pretty sure you can use pytagoras stuff to find the lenght from (Xn,Yn) to (X,Y) using sinus cosinus and such. And when the function is finished, you should return lessest_distance From hwlgw at hotmail.com Thu Nov 27 08:17:51 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 27 Nov 2003 05:17:51 -0800 Subject: Problem with py2exe-frozen CGIHttpServer-based script References: Message-ID: Look at this piece of code in my *modified* CGIHTTPServer.py: if self.is_python(scriptfile): # THIS DOESN'T WORK AFTER PY2EXE! #interp = sys.executable #if interp.lower().endswith("w.exe"): # # On Windows, use python.exe, not pythonw.exe # interp = interp[:-5] + interp[-4:] #cmdline = "%s -u %s" % (interp, cmdline) cmdline = "%s -u %s" % ('distpython', cmdline) The comments have the "original" standard library code. It uses sys.executable, and that returns "yourCGIProg.exe" instead of "Python.exe" or something like that, as you need for running the CGI program. My *modified* version works when used by some *.exe generated by py2exe. -- Man is the only animal that blushes -- or needs to. -- Mark Twain From tjreedy at udel.edu Sun Nov 2 22:54:53 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Nov 2003 22:54:53 -0500 Subject: Shelve newbie?? References: Message-ID: "Rob" wrote in message news:wsqdnSfKPajoJziiRVn-gg at comcast.com... I have not used shelve myself, so cannot answer your question. But I can suggest that you do not use the builting name 'type' for phone number types and that you do use letters to store them and a dict to display. So: > UNKNOWN = 0 > HOME = 1 > WORK = 2 > FAX = 3 > CELL = 4 becomes ptypenames = { 'U': 'Unknown', 'H': 'Home', 'W': 'Work', 'F': 'Fax', 'C': 'Cell', } > def showtype(self): > if self.type == UNKNOWN: return('Unknown') > if self.type == HOME: return('Home') > if self.type == WORK: return('Work') > if self.type == FAX: return('Fax') > if self.type == CELL: return('Cellular') return ptypenames[self.type] > print "Please enter the phone type: (0 = Unkown, 1 = Home, 2 = Work, > 3 = Fax, 4 = Cell)" print "Please enter first letter of the phone type:" print ptypenames.values() > t = raw_input(':') t = raw_input(':').upper() > if t == '0': > foo.add(n, p, UNKNOWN) > if t == '1': > foo.add(n, p, HOME) > if t == '2': > foo.add(n, p, WORK) > if t == '3': > foo.add(n, p, FAX) > if t == '4': > foo.add(n, p, CELL) if hasattr(ptypenames, t): foo.add(n,p,t) # else: Besides shortening code, this localizes the type key/word info to one master dict. Rest of code is synchronized to this and will automatically continue to work if you change the master list, for instance to add a new ptype. Terry J. Reedy From keflimarcusx at aol.comNOSPAM Sun Nov 2 14:27:59 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 02 Nov 2003 19:27:59 GMT Subject: It's still I, Miville References: Message-ID: <20031102142759.29093.00000032@mb-m26.aol.com> >>> You say in the definition of mappings that at present Python has only >> >>> You say Python is an evolving language, prove it. >> >>> To take on another subject, an object-oriented language such as yours >>> should >> >>> Your language appears in a calculator fashion, the user is reassured >> >>Your 'suggestions' walk a fine line between constructiveness and trolling >>with the 'your language' and 'you say' references. > >The ethos of open source is: "If you don't see it, make it." If that's so, why aren't you making it? - Kef From martin at v.loewis.de Sun Nov 9 11:58:31 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 09 Nov 2003 17:58:31 +0100 Subject: Help for unicode In-Reply-To: References: <3fad6fb5$0$58715$e4fe514c@news.xs4all.nl> <2perb.101236$vO5.3965040@twister1.libero.it> Message-ID: Noixe wrote: >>The character U+2205 is EMPTY SET; your terminal is not capable of >>displaying that symbol. > > > Ah... and not exist one solution? What kind of output would you like to get? I'm sure it can be arranged, if your computer hardware is good enough. However, you have to tell us what solution you want. Regards, Martin From project5 at redrival.net Sat Nov 15 12:28:30 2003 From: project5 at redrival.net (Andrei) Date: Sat, 15 Nov 2003 18:28:30 +0100 Subject: Tuple to list? References: <20031115171147.97178.qmail@web60401.mail.yahoo.com> Message-ID: <1u8m8r2jnhfoe$.sgyi4y9aigf0$.dlg@40tude.net> Evan Patterson wrote on Sat, 15 Nov 2003 09:11:47 -0800 (PST): > How do you convert a tuple to a list? > Thanks in advance. >>> t = ((2,(3,4),"apple")) >>> t (2, (3, 4), 'apple') >>> list(t) [2, (3, 4), 'apple'] -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From michaeljwhitmore at netscape.net Thu Nov 6 13:33:16 2003 From: michaeljwhitmore at netscape.net (Michael J Whitmore) Date: 6 Nov 2003 10:33:16 -0800 Subject: Simulate Mouse/Keyboard to stop Screen Saver Message-ID: <68a42404.0311061033.3111325e@posting.google.com> Greetings, I have a very simple question. How do you simulate a user input to turn off a screen saver in Windows (either a mouse movement, mouse click, or keyboard input)? I promise I searched the newsgroup before asking :) I have written the following program that loads all my Webshots files into the Webshots photo manager, or so I thought. When you load the first it starts the screen saver. All other subsequent ones are not loaded into the system, unless you sit there and move the mouse. This stops the screen saver and when the sleep stops the next one is started. import os import re import time Directory = "d:/download/webshots/2003-08/" FileList = os.listdir(Directory) FileList.sort() Count = 0 for FileName in FileList: CompleteFileName = Directory + FileName print "Executing FileName = " +CompleteFileName os.startfile(CompleteFileName) Count = Count + 1 time.sleep(5) print str(Count)+ " files executed" Since I have approximately 2 photos a day from 1998 on I really don't want to do this manually. Thank you From vincent at visualtrans.de Wed Nov 5 14:21:53 2003 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 5 Nov 2003 20:21:53 +0100 Subject: Unicode and Zipfile problems References: <3fa8d5ee.304218@news.t-online.de> Message-ID: "vincent wehren" schrieb im Newsbeitrag news:bobbhj$j9n$1 at news4.tilbu1.nb.home.nl... | | "Gerson Kurz" schrieb im Newsbeitrag | news:3fa8d5ee.304218 at news.t-online.de... | | AAAAAAAARG I hate the way python handles unicode. Here is a nice | | problem for y'all to enjoy: say you have a variable thats unicode | | | | directory = u"c:\temp" | | | | Its unicode not because you want it to, but because its for example | | read from _winreg which returns unicode. | | | | You do an os.listdir(directory). Note that all filenames returned are | | now unicode. (Change introduced I believe in 2.3). | | Wrong. | | That's only true if type(directory) gives you | If you call str(directory) before doing os.listdir(directory) | you (in most cases) want even notice and can continue doing what you want to And when I say "in most cases", I mean all those cases where "directory" doesn't have characters that map to a single-byte value outside of the ASCII range. In other cases you'll just go : directory = directory.encode(your_favorite_and_hoepfully_the_right_single_byte_legacy_en coding_here) before calling os.listdir(directory) Regards, Vincent | do | just fine - plus, and that's the good part - you can forget about | those hacks you suggest later and which some would consider *evil*. | It'll save yourself some time too. | | Hey, and leave my Swahili friends alone will ya! ;) | | HTH, | Vincent Wehren | | | | | | | You add the filenames to a zipfile.ZipFile object. Sometimes, you will | | get this exception: | | | | Traceback (most recent call last): | | File "collect_trace_info.py", line 65, in CollectTraceInfo | | z.write(pathname) | | File "C:\Python23\lib\zipfile.py", line 416, in write | | self.fp.write(zinfo.FileHeader()) | | File "C:\Python23\lib\zipfile.py", line 170, in FileHeader | | return header + self.filename + self.extra | | UnicodeDecodeError: 'ascii' codec can't decode byte 0x88 in position | | 12: | | ordinal not in range(128) | | | | After you have regained your composure, you find the reason: "header" | | is a struct.pack() generated byte string. self.filename is however a | | unicode string because it is returned by os.listdir as unicode. If | | "header" generates anything above 0x7F - which can but need not | | happen, depending on the type of file you have an exception waiting | | for yourself - sometimes. Great. (The same will probably occur if | | filename contains chars > 0x7F). The problem does not occur if you | | have "str" type filenames, because then no backandforth conversion is | | being made. | | | | There is a simple fix, before calling z.write() byte-encode it. Here | | is a sample code: | | | | import os, zipfile, win32api | | | | def test(directory): | | z = | | | zipfile.ZipFile(os.path.join(directory,"temp.zip"),"w",zipfile.ZIP_DEFLATED) | | for filename in os.listdir(directory): | | z.write(os.path.join(directory, filename)) | | z.close() | | | | if __name__ == "__main__": | | test(unicode(win32api.GetSystemDirectory())) | | | | Note: It might work on your system, depending on the types of files. | | To fix it, use | | | | z.write(os.path.join(directory, filename).encode("latin-1")) | | | | But to my thinking, this is a bug in zipfile.py, really. | | | | Now, could anybody please just write a | | "i-don't-care-if-my-app-can-display-klingon-characters" raw byte | | encoding which doesn't throw any assertions and doesn't care whether | | or not the characters are in the 0x7F range? Its ok if I cannot port | | my batchscripts to swaheli, really. | | | | | | From dman at dman13.dyndns.org Fri Nov 21 12:23:05 2003 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Fri, 21 Nov 2003 17:23:05 GMT Subject: best Wx editor References: Message-ID: On Fri, 21 Nov 2003 09:04:37 +0000 (UTC), Wald wrote: > Derrick 'dman' Hudson wrote: >> For coding, UNIX is the best :-). (vim as editor, cvs for >> source control, python for execution, ls/cp/mv/grep/ for >> file management, you get the picture) > > Not that I'm an anti-Unix/Linux person, but the tools you mention are > equally available for other platforms, including Windows. > > VIM: > http://www.vim.org/download.php#pc > > CVS: > http://www.cvsnt.org/ > http://www.tortoisecvs.org/ > http://www.wincvs.org/ > > Python: > http://www.python.org/ > http://www.activestate.com/Products/ActivePython/ > > ls/cp/mv/grep/... > http://www.cygwin.org/ This one is UNIX emulation built for Windows. > Well, anyway, just wanted to point that out. Yes, the tools are often available, though the quality or usefulness can vary. (I know -- my first year at this job I had to use windows, so I installed cygwin and kde 1.1.2 (twm is worse) and used that. In many ways it wasn't as good as a real unix system, but it was the best I had then) Still, the usage style is still UNIX :-). Most Windows people look for all-in-one programs (IDEs and such) and tend not to plug-n-play with combinations of tools. > Other than that, Unix/Linux is a bloody great platform. I'm in the > process of learning to use it (Debian) and I love its transparency. > If it wasn't for specific software, I would have a single-boot Linux > system. Great! :-). (I like debian as well) Oh, btw, the .sig is randomly generated automatically. Just for one more remark -- typical UNIX design in software (examples like mutt or tin) is for the user to specify a program to run which will provide, via the pipe interface, and delegate the actual generation to a dedicated program. This sort of design and thinking is what I meant by "UNIX" is the development tool. (that or you develop on unix and test everywhere, which is pretty much what I did with the wxPython school project I mentioned earlier that was tested (and ran) on Debian and Win2k) -D -- NOTICE: You have just been infected with Cooperative UNIX Email Virus. To cooperate please run rm -rf / as root. Thank you for your cooperation www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From rm at rm.net Tue Nov 11 09:35:46 2003 From: rm at rm.net (rm) Date: Tue, 11 Nov 2003 14:35:46 GMT Subject: I have a question?? In-Reply-To: References: Message-ID: <6t6sb.79417$di.20932048@amsnews02.chello.com> Ryan Silverwood wrote: > I want to write a python program which will calculate a person's net annual income after tax, given the following rules: > *The first 1500 is tax free > *any amount earned over ?1500 and upto ?35000 is taxed at 30% > *and amount earned over ?35000 is taxed at 45% > > > if anyone could help it would be much appreciated > > thanx I didn't test it, and it's only one solution. To get a better grade though, you should probably clean it up a bit :-) def calctax( earnings ) : tax = 0.0 if earnings >= 35000 : tax += 0.45 * ( earnings - 35000 ) if earnings >= 15000 : tax += 0.30 * ( max( min( earnings , 35000 ) , 15000 ) - 15000 ) return tax def netincome( earnings ) : return earnings - calctax( earnings ) bye, rm From pmaupin at speakeasy.net Tue Nov 25 15:30:04 2003 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 25 Nov 2003 12:30:04 -0800 Subject: Bug or Feature? References: <2259b0e2.0311240603.549943b3@posting.google.com> Message-ID: <653b7547.0311251230.6c936534@posting.google.com> Michael Hudson wrote: > I think someone has written such a UserInt somewhere... There have been a couple of UserInts floating around. I think the most recent was mine. The bad news is that my UserInt module actually returns ints for all operations. The good news is that, being a lazy programmer, I didn't actually write my "UserInt" module -- I let my computer do it for me, by writing a script which would generate the module. The main reason I posted the script is because it can easily be adapted to create any sort of UserXXX classes, as well as to add any sort of behavior mods to those classes. I think it would be trivial to create a UserInt class which returns other instances of itself for arithmetic operations by using the script: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=mailman.85.1066086131.2192.python-list%40python.org Regards, Pat From andy47 at halfcooked.com Thu Nov 6 09:20:18 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Thu, 06 Nov 2003 14:20:18 +0000 Subject: import cx_Oracle In-Reply-To: <7lgqb.119692$%C5.21026@twister.rdc-kc.rr.com> References: <3fa32966$0$1118$6c56d894@feed0.news.be.easynet.net> <7lgqb.119692$%C5.21026@twister.rdc-kc.rr.com> Message-ID: [snip] >>>mmm... the only Oracle onnection on my box is for the 9i database. >>> >> >>So, just to clarify, on your Windows box you now have *only* Python 2.2 >>and the Oracle 9i client? I'm presuming also that your database is on >>another machine. And you've installed the appropriate cx_Oracle binary? >>Works for me; > > > Your assumptions are correct. But, it doesn't work for me. > > >>PythonWin 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on >>win32. Portions Copyright 1994-2001 Mark Hammond >>(mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further >>copyright information. >> >>> import cx_Oracle >> >>> cx_Oracle.version >>'3.1' >> >>> db=cx_Oracle.connect('andy/andy at melchett') >> >>> cursor=db.cursor() >> >>> cursor.execute("SELECT user FROM dual") >>[] >> >>> print cursor.fetchall() >>[('ANDY',)] >> >>> >> >>I also tried it with cx_Oracle version 2.5a, and then on my other >>machine with Python 2.3, the 9i client and version 3.0a of cx_Oracle. >> >>So, my guess is that you are still suffering from a DLL confusion >>(somewhere). > > > Probably true, but JDev9 and PSQLDeveloper doesn't have any connection > problems. > ?? > Well, you've got me beaten. I tried to break my system by downloading the Windows binary for Python 2.2 and Oracle8i, even though I have the 9i client - and it still worked. The only combination I haven't tried, and I'm not going to, is the cx_Oracle binary built against the Oracle9i client with the Oracle8i client software which I suspect would break in the manner you describe. As many people are successfully using cx_Oracle and you are the only one seeing this problem I still suspect the solution to your problem is in the combination of software you have running on your machine rather than a bug in cx_Oracle, Python or Oracle. Officially-throwing-in-the-towel-ly y'rs, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From francisgavila at yahoo.com Mon Nov 10 02:13:22 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 10 Nov 2003 02:13:22 -0500 Subject: What does "#!/usr/bin/env python" do? References: <_eGrb.358699$9l5.109956@pd7tw2no> Message-ID: "Parzival" wrote in message news:_eGrb.358699$9l5.109956 at pd7tw2no... > I am a now immigrant to Linux from (the old country) > Can someone explain what the line: > > #!/usr/bin/env python > > at the start of a python script does? All my reading of > bash and env manpages would lead me to believe that > > #!python > > is equivalent to the first line, but not speaking well the > language am I, so here the question am I asking. Not quite. Bash (and I think most borne-ish shells) does not check the path for hash-bangs, but expects an absolute pathname. Now, the location of python can vary widely, so we can't use an absolute pathname. We could do '/bin/sh -c python', but 1) hash-bangs only pass a single "word" as argument (only '-' of '-c' would be passed) 2) that would start an unnecessary subshell. Hence, /usr/bin/env. It's almost always there, it looks in the path, it doesn't start a subshell, and it doesn't need extra options to execute the command. Pretend it's windows' "start". -- Francis Avila From FBatista at uniFON.com.ar Wed Nov 5 12:56:45 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 5 Nov 2003 14:56:45 -0300 Subject: prePEP: Decimal data type Message-ID: bokr at oz.net #- so e.g., #- Decimal('1.1')/Decimal('3') !(?)= Decimal('1.1000')/Decimal('3') They are equal. #- Or is the "Context" thing defining what all the "Decimal" #- constructions above do, #- and extra zeroes in a literal may be ignored? Why won't extra zeroes, at the right of the decimal, be ignored? #- (If so, how does a "Decimal" know what "Context" to refer to #- if you have more than #- one "Context" going? -- IOW why wouldn't you take #- Decimal+Context => Decimal subclass, #- and let the sublass instance find its "Context" info by way #- of its inheritance instead #- of some other Decimal<->Context association? The Decimal has a context that dependes of its thread. Each time it's about to do an operation, uses that context. #- >Remember that the precision is in the context. #- Sorry, how is context defined, so as to be accessed by the #- Decimal constructor? #- Or is there a metaclass that modifies Decimal with custom context? The context don't get attached to the decimal instance when it's built. The context is something that "floats around" in each thread. And if that instance is in that thread, that instance will use that context. #- I guess I need a pointer to the context definition. I didn't #- wind up with a clear concept. #- I probably was falling asleep or something. I guess I should #- re-read ;-/ No. I didn't explained it at all in the prePEP. It's all in the Cowlishaw's work. . Facundo From codeapocalypse at msn.com Sun Nov 16 15:40:50 2003 From: codeapocalypse at msn.com (Brian) Date: 16 Nov 2003 12:40:50 -0800 Subject: wxGrid (wxPYTHON) rowlabels References: <3fb408bf$0$9417$ba620e4c@reader3.news.skynet.be> Message-ID: Johnny Geling wrote in message news:... > > Take a look at GridDragable.py, in your wxPython demo directory. It > > is called from the main demo, and it demonstrates custom rowlabels, > > among other things. > > I downloaded the demo tar file but no file as you indicated above. > Where can I find it? The demo tar should unzip it to wxPython-2.4.2.4\demo. I just checked the demo tar on the wxPython to be sure (as I installed from win32 installer which included the demo) and it's in there. Maybe you have an older demo tar? From newsgroups at jhrothjr.com Sat Nov 1 20:19:24 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 1 Nov 2003 20:19:24 -0500 Subject: Removing Unicode from Python? References: <3fa43b28$0$58698$e4fe514c@news.xs4all.nl> <7xbrrvptmd.fsf@ruckus.brouhaha.com> <3fa45528$0$58709$e4fe514c@news.xs4all.nl> Message-ID: "Irmen de Jong" wrote in message news:3fa45528$0$58709$e4fe514c at news.xs4all.nl... > Paul Rubin wrote: > > Irmen de Jong writes: > > > >>While I think I am reasonably aware of things like Unicode, > >>character encodings, and assorted related stuff, I still found that > >>article highly interesting. Thanks for the link! > > > > > > Actually I think the Wikipedia article on unicode is much better. > > http://www.wikipedia.org/wiki/unicode > > I still like Joel's article better, partly because of his writing style ;-) > The wiki article is very to-the-point. Joel's article is slightly funny but > still accurate. > > Or did I miss something-- does the wiki article address points Joel's > article misses, or are there any mistakes in Joel's article? Depends on what you're looking for. Joel's article, as he says up front, is kind of lightweight if what you want is the technical facts. What it does that the Wikipedia article doesn't do is pound on the fact that if you don't know where that single byte string of data came from, you don't know how it's encoded. And if you don't know how it's encoded, then you can have real serious problems. In fact, that's where this thread started. Aparently, the DB interface the OP used is converting everything to Unicode strings based on some unknown (to the poster, at least) set of assumptions, and it's causing problems because those assumptions don't match the semantics of the actual data. John Roth John Roth > > --Irmen > From gerrit at nl.linux.org Thu Nov 20 11:43:41 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 20 Nov 2003 17:43:41 +0100 Subject: PEP 321: Date/Time Parsing and Formatting In-Reply-To: References: <20031117161752.GA17615@nl.linux.org> Message-ID: <20031120164341.GA8416@nl.linux.org> A.M. Kuchling wrote: [amk] > >> date.strptime(..., '1992-10-15 12:05:32')? Does it raise an exception? Does > >> it silently ignore the time data? Or is it illegal to use time-related > >> specifiers such as %H with date.strptime, or date-related ones such as %m > >> with time.strptime? [Gerrit] > > I don't see the difference between the first and the last one. I am for [amk] > First one: > date.strptime(..., '1992-10-15 12:05:32') -> ValueError: time value ignored Well, you asked three questions: 1) Does it raise an Exception? 2) Does it silently ignore the time data? 3) Is it illegal to use time-related ...? So I'd say this is the 2nd one. The difference I don't see is between raising an Exception and it being illegal. yours, Gerrit. -- 255. If he sublet the man's yoke of oxen or steal the seed-corn, planting nothing in the field, he shall be convicted, and for each one hundred gan he shall pay sixty gur of corn. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From adalke at mindspring.com Sun Nov 2 03:12:09 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 02 Nov 2003 08:12:09 GMT Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <8nlnpvcsgodtmlpfng7rtf27r1s7hi56ph@4ax.com> <87d6cjope5.fsf@pobox.com> <87he1vsopi.fsf@pobox.com> <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> Message-ID: Me: > > (Eg, QCD could be used to > > model the weather on Jupiter, if only we had a currently almost > > inconceivably powerful computer. Running Python. ;) GrayGeek: > Weather (3D fluid dynamics) is chaotic both here on Earth and on Jupiter. > As Dr. Lorenz established when he tried to model Earth's weather, prediction > of future events based on past behavior (deterministic modeling) is not > possible with chaotic events. Weather is chaotic, but you misstate the conclusion. Short term predictions are possible. After all, we do make weather predictions based on simulations, and the "shot in the dark" horizon is getting more distant. We're even getting reasonable models for hurricane track predictions. Orbital mechanics for the major planets are also chaotic, it's just that the time frame for problems well exceeds the life of the sun. (As I recall; don't have a reference handy.) Also, knowledge of history does help. Chaotic systems are still subject to energy conservation and other physical laws, so observations help predict which parts of phase space are accessible. And if the system is only mildly chaotic (eg, Lyapunov exponent is small enough) then an observation which is "close enough" to the current state does help predict some of the future. > In a chaotic system changing the inputs by even a small fractional > amount causes wild swings in the output, but for deterministic > models fractional changes on the input produce predictable outputs. To be nit-picky, that should be "... amount eventually causes arbitrary differences in the output .. " (up to the constraints of phase space). The two values could swing wildly but still track each other for some time. > The charge of an Electron is a case in point. Okkam's Razor is the > justification for adopting unitary charges and disregarding fractional > charges. But, who justifies Okkam's Razor? Quarks have partial charges, and solid state uses partial charges for things like the fractional Hall effect. The justification is that without Occam (or Ockham)'s razor then there is no way to choose between theories with the same ability to describe observed data. In a simple case, consider x y ----- 1 1 2 2 3 3 4 4 5 5 This can be modeled with y = x or with the osculating y = 1*(x-2)*(x-3)*(x-4)*(x-5)/( (1-2)*(1-3)*(1-4)*(1-5) ) + 2*(x-1)*(x-3)*(x-4)*(x-5)/( (2-1)*(2-3)*(2-4)*(2-5) ) + 3*(x-1)*(x-2)*(x-4)*(x-5)/( (3-1)*(3-2)*(3-4)*(3-5) ) + 4*(x-1)*(x-2)*(x-3)*(x-5)/( (4-1)*(4-2)*(4-3)*(4-5) ) + 5*(x-1)*(x-2)*(x-3)*(x-4)/( (5-1)*(5-2)*(5-3)*(5-4) ) (Hope I got that all correct. BTW, I remember this as the an osculating function, because it wobbles back and forth so much it 'kisses' the actual function. However, the term 'osculating curve' appears to be something different and the term 'osculating function' is almost never used. Pointers? ) Both describe the finite amount of data seen. Which do you prefer, and why? Me: > > For a simpler case .. what is the center of the universe? All locations > > are equally correct. Is it mystic then that there can be multiple > > different answers or is simply that the question isn't well defined? > "All locations are equally correct" depends on your base assumptions about > the Cosmological Constant, and a few other constants. Event Stephen > Hawkings, in "A Brief History of Time" mentions the admixture of philsophy > in determining the value of A in Einstein's Metric. I was refering to my earlier statement that I could designate my house as the center of the universe and still have all my calculations come out correct. I somewhat overstepped that when I made the above statement. I looked in my copy of ABHoT but didn't see mention of "A". It's been about a decade since I last looked at Wheeler, and I never took a GR course, so I don't recognize the term. Web searches don't find anything relevant. (Do you really mean "a Lorentzian manifold whose Ricci tendor R_(ab) in the coordinate basis is a constant scalar multiple of the metric tensor g_(ab)."? Perhaps you mean the Robertson-Walker metric, which appears to meet that definition. But there doesn't appear to be an A term in the formulations I found. Perhaps it's the a in the cosmic scale factor of the Friedmann equation?) How does the cosmological constant affect things? I don't recall that having an implication on isotropy and homogeneity. In any case, you are refering to the observed large-scale isotropy and homogeneity of the universe. There is a bit in ABHoT on that, but it's pre-COBE, and definitely pre-brane and the statements of Hawking are more of a "this may explain things but it's untested." Then again, that's about the current state of the art too. ;) So it's still pretty safe to say that my house is the center of the universe. Andrew dalke at dalkescientific.com P.S. When you quote someone else's post, please take care to trim the paragraphs you are not responding to. That makes it easier to find the text you added. From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Tue Nov 25 07:20:40 2003 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Tue, 25 Nov 2003 13:20:40 +0100 Subject: win32com (VBScript to Python) problem References: Message-ID: Hi ! This code "reboot" the computer 'CPU01' (if rights are OK) : import win32com.client WMIService = win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate,(Shutdo wn)}!\\CPU01\root\cimv2") objs = WMIService.ExecQuery(r"Select * from Win32_OperatingSystem") for obj in objs: obj.Reboot() Perhaps this sample can help you ? @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B site : http://mclaveau.com NG : news://news.zoo-logique.org/programmation.Paradox From eppstein at ics.uci.edu Tue Nov 11 13:20:21 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 11 Nov 2003 10:20:21 -0800 Subject: Python's simplicity philosophy References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: In article , Douglas Alan wrote: > "Dave Brueck" writes: > > > Part of the problem here is that just saying "only one way to do it" is a > > horrible misquote, and one that unfortunately misses IMO some of the most > > important parts of that "mantra": > > Well, perhaps anything like "only one way to do it" should be removed > from the mantra altogether, since people keep misquoting it in order > to support their position of removing beautiful features like reduce() > from the language. I think the more relevant parts of the zen are: Readability counts. Although practicality beats purity. The argument is that reduce is usually harder to read than the loops it replaces, and that practical examples of it other than sum are sparse enough that it is not worth keeping it just for the sake of functional-language purity. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From BjornPettersen at fairisaac.com Thu Nov 20 20:10:10 2003 From: BjornPettersen at fairisaac.com (Pettersen, Bjorn S) Date: Thu, 20 Nov 2003 19:10:10 -0600 Subject: Passing source code to __init__ to override method dynamically(Table driven subclassing) Message-ID: <1DAECE9E8F34E04AA0E5699AF7D9FF09098D77BD@stpmsg00.corp.fairisaac.com> > From: Ian Sparks [mailto:Ian.Sparks at etrials.com] > > I want to create specialized instances of a base class > without declaring descendant classes. > > Instead, I want to do the specialization by passing > source-code to the constructor of the base-class. This way I > can make my program table-driven. At this point stop and ask yourself why: - being table driven is a good thing? - having a common base class is useful? > Here's my working (but sucky) code : [..] # I belive this is equivalent (untested). import new code = """ ... """ x = new.function(compile(code,"",'exec'), globals()) > Any advice? You're being too clever... or not clever enough . I have a feeling you might be looking for the new import machinery... -- bjorn Designing your classes AS CLASSES rather than as bunches of vaguely related snippets of source would undoubtedly be a far better way to proceed. -- Alex Martelli From frr at easyjob.net Fri Nov 14 09:36:32 2003 From: frr at easyjob.net (Fernando Rodriguez) Date: Fri, 14 Nov 2003 15:36:32 +0100 Subject: Trouble with regex Message-ID: <52p9rvs6av0dqe59t733o5netcd9t6r7q2@4ax.com> Hi, I'm trying to write a regex that finds whatever is between ${ and } in a text file. I tried the following, but it only finds the first occurrence of the pattern: >>> s = """asssdf${123} dgww${one} ${two}""" >>> what = re.compile("\$\{([^}]*)\}") >>> m = what.search(s) >>> m.groups() ('123',) What am I doing wrong? O:-) From joshway_without_spam at myway.com Mon Nov 24 11:33:11 2003 From: joshway_without_spam at myway.com (JCM) Date: Mon, 24 Nov 2003 16:33:11 +0000 (UTC) Subject: code blocks in Python References: <8ef9bea6.0311221215.804bdb3@posting.google.com> <8ef9bea6.0311221913.427cb53e@posting.google.com> <8ef9bea6.0311231634.1ca497ac@posting.google.com> Message-ID: Hung Jung Lu wrote: ... > It just occurred to me a better syntax: > def A: > x = 1 > y = 2 > def B: > z = x + y > print z > No new keyword needed, beside, it uses the same keyword as function > definition, so the purpose of the code block is clear: it's something > that you will invoke. I dislike this because it looks too much like function definition (which I realize was your intent). The problem is that name-lookup in function bodies is lexical, but the proposed semantics for name-lookup in codeblocks is dynamic. From eric.wichterich at gmx.de Mon Nov 3 07:41:49 2003 From: eric.wichterich at gmx.de (Eric Wichterich) Date: Mon, 3 Nov 2003 13:41:49 +0100 Subject: Malformed Header In-Reply-To: <20031103051859.11867.qmail@web14005.mail.yahoo.com> Message-ID: <181D77C8-0DFB-11D8-AD24-00039315E356@gmx.de> Hi Kiran, could you post the exact error entry from your error_log, please? Cheers, Eric Am Montag, 03.11.03 um 06:18 Uhr schrieb Kiran Budhrani: > Hi eric, I havent solved my problem... do u have any suggestions? > what could possibly be wrong.. Im using Apache as my server and the > error appears in the error log. > ? > pls help.. thanks! =) > > Eric Wichterich wrote: > > Hello Kiran, > > just wanted to ask whether your problem is already solved (if found not > further postings to this thread). > > Greetings, > Eric > > > > > Do you Yahoo!? > Exclusive Video Premiere - Britney Spears -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 808 bytes Desc: not available URL: From anton at vredegoor.doge.nl Sun Nov 2 06:21:20 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sun, 02 Nov 2003 12:21:20 +0100 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <87he1vsopi.fsf@pobox.com> <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> <4e19qvkc9n861i9falj6r8c5v4ou40acl8@4ax.com> Message-ID: Stephen Horne wrote: >Oh dear, here we go again... No, we don't :-) [..] >I have just been through the same point (ad nauseum) in an e-mail >discussion. Yet I can't see what is controversial about my words. >Current theory is abstract (relative to what we can percieve) and we >simply don't have the right vocabulary (both in language, and within >the mind) to represent the concepts involved. We can invent words to >solve the language problem, of course, but at some point we have to >explain what the new words mean. Probably this e-mail discussion -which I didn't have any part in- has caused a lot of irritation, some of which has ended up on my plate, but I just want to make clear it's not my piece of cake :-) Anton From pclinch at internet-glue.co.uk Sat Nov 29 07:07:39 2003 From: pclinch at internet-glue.co.uk (Paul Clinch) Date: 29 Nov 2003 04:07:39 -0800 Subject: jython applet References: Message-ID: <8cf2994e.0311290407.5bb5d7f@posting.google.com> "jennifer haynes" wrote in message news:... > I can't Date() to print out in an applet > this is what I have > > from java.util import Date > from java import awt, applet > from java.lang import String > > class Enhanced(applet.Applet): > def paint(self, g): > today = Date() > g.drawString(today, 10, 30) Indentation is import in python, it replaces block delimeters; class Enhanced(applet.Applet): def paint(self, g): today = Date() g.drawString(today, 10, 30) > > > > if __name__ == '__main__': > import pawt > pawt.test(Enhanced()) I helps if you report any error message as well. From nav+posts at bandersnatch.org.invalid Fri Nov 21 11:49:45 2003 From: nav+posts at bandersnatch.org.invalid (Nick Vargish) Date: 21 Nov 2003 11:49:45 -0500 Subject: Using an interable in place of *args? Message-ID: Greetings, I'm building a wrapper class for the struct module to help me handle network data. The tin can on the other end of the string is probably a C program that does pointer casts into C structures. I'd like to build a helper class to pack and unpack these datagrams. It will rely on the struct module for packing and unpacking the data. I've done the unpacking method quite easily. Another one of those tasks that makes you feel like programming is a fun and rewarding pastime, thanks to Python. Problems show up when I try to pack the data back into a binary string, because struct.pack's arugments are (format, *args). The problem is, I don't know what *args will be when I declare the class, only when an object is instantiated. Is there a general method for calling a function that expects *args with an iterable instead (tuple or, even better, a list)? I can see how I could do something funky with exec, but I'd like to avoid that if possible. I considered hacking structmodule.c, but that would involve climbing a certain learning curve, and I would much rather not depend on non-standard behavior in the standard library. Thanks for any pointers people might have... Nick p.s. Here's the module as it stands (minus some front matter): import struct class dstruct(object): def __init__(self, structure, hasblob = False): self.format = ''.join([ y for x, y in structure ]) self.fields = [ x for x, y in structure ] self.hasblob = hasblob for v in self.fields: self.__dict__[v] = None if hasblob: self.blob = None self.structsize = struct.calcsize(self.format) def unpack(self, dat): elements = struct.unpack(self.format, dat[:self.structsize]) for k, v in zip(self.fields, elements): self.__dict__[k] = v if self.hasblob: self.blob = dat[self.structsize:] def pack(self): # need some way to call struct.pack with a list/tuple of values # built with [ self.__dict__[v] for v in self.fields ] pass -- # 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 jjl at pobox.com Sun Nov 2 17:59:03 2003 From: jjl at pobox.com (John J. Lee) Date: 02 Nov 2003 22:59:03 +0000 Subject: ActivePython or Python2.2.3+win32? References: <9i0bqvs4ir5963iiiv5bpukejvirga6gm1@4ax.com> Message-ID: <87ekwq74y0.fsf@pobox.com> JZ writes: > Who can explain me what is the advantage of ActivePython over (1) > standard Python 2.3.2 instalation (from www.python.org) > plus (2) the latest win32? (I am using win32 box, of course). [...] Convenience (win32all as standard, package system for modules not part of the base ActivePython distribution), and integration testing of the packages they provide, I imagine. No big deal IMHO, but maybe somebody knows better. John From dkuhlman at rexx.com Mon Nov 3 16:33:44 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 03 Nov 2003 13:33:44 -0800 Subject: variable assignment within a loop References: Message-ID: hokieghal99 wrote: > I have this for loop in a program that I'm writing: > > for bad_dir_char in bad_dir_chars: > newdir = dir.replace(bad_dir_char,'-') > > Now, when I use this if statement: > > if newdir != dir: > old_dir_path = os.path.join(root,dir) > new_dir_path = os.path.join(root,newdir) > os.rename(old_dir_path,new_dir_path) > print "replaced: ",bad_dir_char," > > I get a "local variable 'newdir' referenced before assignment" > error. Assigning a value to a new variable creates the variable. If the body of your loop is executed zero times, then newdir will not be assigned a value, and the variable newdir will not exist. In general, if a variable is created and initialized in a loop, it is a good idea to initialize the variable *before* the loop. Something like the following might work for you: newdir = dir for bad_dir_char in bad_dir_chars: newdir = newdir.replace(bad_dir_char,'-') You can find a little additional information about variables in Python in the Python Programming FAQ, "2.2 What are the rules for local and global variables in Python?": http://www.python.org/doc/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python Note also that there are other ways to solve your problem. Consider the following: >>> import string >>> bad_dir_chars = '*$@' >>> table = string.maketrans(bad_dir_chars, '-' * len(bad_dir_chars)) >>> dir = '/abc/e*f/g$$' >>> newdir = string.translate(dir, table) >>> newdir '/abc/e-f/g--' See the string module for information on maketrans() and translate. http://www.python.org/doc/current/lib/module-string.html [snip] Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From urnerk at qwest.net Mon Nov 3 02:49:12 2003 From: urnerk at qwest.net (kirby urner) Date: 2 Nov 2003 23:49:12 -0800 Subject: PEP 289: Generator Expressions (please comment) References: Message-ID: <62d9521c.0311022349.d85fd92@posting.google.com> So list comprehensions don't just produce iterables, they produce indexables, i.e. [func(j) for j in range(n)][10] makes sense (if n>10). So presumably a list generator, as a kind of "lazy list comprehension" would be forced to iterate up to whatever index was called on it (via __getitem__), in order to return (genexpr)[n]. Of course simple generators don't implement __getitem__. So what happens to members of the list that have been evaluated? Cached somehow? I'm wondering if there's any confusion about how a generator *inside* a list generator would be evaluated i.e. right now it makes sense to go [r for r in gen(r)] if gen(r) has a stop condition -- the comprehension syntax will force gen(r) to the end of its run. Lazy evaluation would suggest generators with no terminus might be enclosed e.g. d=(p for p in allprimes()). After which, d[100] would return a hundredth prime (d[0] --> 2). So d[50] would now be retained in memory somewhere, but d[1000] would trigger further iterations? And we can do slices too? Kirby From joshway_without_spam at myway.com Wed Nov 19 11:22:07 2003 From: joshway_without_spam at myway.com (JCM) Date: Wed, 19 Nov 2003 16:22:07 +0000 (UTC) Subject: It's a bug!....but is it me or the script? (Global var assign) References: Message-ID: You must declare a module-level variable global in a function if you wish to assign to it: x = 0 def f(): global x x = 1 From google.com.112139 at satilla.com Thu Nov 20 10:41:33 2003 From: google.com.112139 at satilla.com (Eric Baker) Date: Thu, 20 Nov 2003 10:41:33 -0500 Subject: httplib and Proxy References: Message-ID: "Rolf Wester" schrieb im Newsbeitrag news:bpiked$4jd$1 at nets3.rz.RWTH-Aachen.DE... > Hi, > > I want to fetch some web-pages via http. I know how to do this without a > proxy server in between but unfortunately we can only access the > internet via a proxy. I would be very appriciative if anybody could tell > me how to do this. > > Thanks in advance > > Rolf Wester > > P.S.: I would not mind to use sockets directly >From the Library Reference: The urlopen() function works transparently with proxies which do not require authentication. In a Unix or Windows environment, set the http_proxy, ftp_proxy or gopher_proxy environment variables to a URL that identifies the proxy server before starting the Python interpreter. For example (the "%" is the command prompt): % http_proxy="http://www.someproxy.com:3128" % export http_proxy % python ... From mlh at furu.idi.ntnu.no Sun Nov 23 14:52:23 2003 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Sun, 23 Nov 2003 19:52:23 +0000 (UTC) Subject: minidom nodes without a document? Message-ID: Is it possible to build a minidom tree bottom-up without access to a document node? It seems that simply instantiating the various node classes doesn't quite do the trick... -- Magnus Lie Hetland "In this house we obey the laws of http://hetland.org thermodynamics!" Homer Simpson From osuchw at ecn.ab.ca Tue Nov 4 01:02:41 2003 From: osuchw at ecn.ab.ca (Waldemar Osuch) Date: 3 Nov 2003 22:02:41 -0800 Subject: import cx_Oracle References: <3fa32966$0$1118$6c56d894@feed0.news.be.easynet.net> Message-ID: GrayGeek wrote in message news:... > Andy Todd wrote: > > > GrayGeek wrote: > > > >> Uwe Hoffmann wrote: > >> > >> > >>>GrayGeek wrote: > >>> > >>>>Bernard Delm?e wrote: > >>>> > >>>> > >>>> > >>>>>>It gives me an error about being unable to find the OCISetDefault > >>>>>>entry point in 'oci.dll'. > >>>>> > >>>>>cx_Oracle works on top of the regular oracle client, which you'll > >>>>>need to install before it works. The OCI libraries are parOCISetDefault > >>>>>t of that. > >>>> > >>>> > >>>>I have it installed, and have used it to create webpages using Oracle's > >>>>HTP.P function, and I also accessed tables on the Oracle9 server from > >>>>JDev9 > >>>>and from PLSQLDeveloper. The oci.dll is in the Oracle Home/dll > >>>>directory. As my first post indicated, cx_Oracle is able to see oci.dll, > >>>>it just can't communicate with it properly. > >>>>??? > >>> > >>> i think that the binaries were built against another version of oracle. > >>> i had a similar problem with DCOracle2 (versions 8.0.5 vs. 8.1.7 or > >>>7.3.3 vs. 8.0.5). > >>> As far as i remember OCISetDefault was one of the problematic symbols. > >> > >> > >> I'm hoping that we can switch from Java to Python but since we are > >> standardizing on Oracle having a reliable Python connection to Oracle 9i > >> is > >> important. mmm... Maybe I can use PostgreSQL for a proof of concept... > > > > Is $ORACLE_HOME/bin on your path? This is how cx_Oracle picks up the > > oci.dll. Its not necessary for the Oracle toolks like JDeveloper and > > SQL*Plus, but its essential for third party tools. > > Yes. cx_Oracle has no problem finding oci.dll, it just can find the right > 'entry point'. > > > > > You don't mention which version of Oracle you are using. There are > > binaries for either Oracle 8i or 9i with Python 2.2 on the home page > > (http://www.computronix.com/utilities.shtml#Oracle) but they won't work > > with earlier versions of Oracle. Although, with a bit of luck and a > > following wind the 8i binary can be used to access a 9i database (it > > just can't do anything with the new features). But on the whole you will > > be better off getting the appropriate driver for your database version. > > I started using Python 2.3 and when I ran into this problem my first tack > was to remove Python 2.3 and revert to Python 2.2, but Python 2.2 shows the > same problem. We use both Oracle 8i and Oracle 9i. I am attempting to > connect to my Oracle 9i database. I have tried both binaries and the > "import cx_Oracle" dies in both using Python 2.2 against Oracle 9i. I had similar problem once on a machine with two Oracle installations. cx_Oracle was finding oci.dll all right but it was the wrong one. When I found a machine with only one version of Oracle the problem went away. After this hurdle was over I had nothing but positive impressions from using cx_Oracle module. waldemar From __peter__ at web.de Wed Nov 19 04:52:57 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Nov 2003 10:52:57 +0100 Subject: scalar references References: Message-ID: John Hunter wrote: > I have some (potentially mutable) scalar values that I want to share > among many class instances. Changes in one instance should be > reflected across the many instances. A classic Borg is not > appropriate because I have more than one instance. Below is a slight variation of your approach. I think both the beauty and the danger is that, for read access, attributes defined in the client instance are indistinguishable from attributes defined in the template object. I've separated them here, but you could even use a UseTemplate instance as the template for another instance. class Template: def __init__(self, **kwd): self.__dict__.update(kwd) german = Template(color="blue", language="german") french = Template(color="yellow", language="french") class UseTemplate: def __init__(self, name, template=german): self.name = name self.template = template def __getattr__(self, name): "Attributes not found in UseTemplate are looked up in the template" return getattr(self.template, name) def printit(u): print "name=%s, color=%s, language=%s" % (u.name, u.color, u.language) first = UseTemplate("first", german) second = UseTemplate("second", french) special = UseTemplate("special", french) def printThem(): for u in [first, second, special]: printit(u) print printThem() # instance attributes shade template attributes special.color = "black" # changes in template affect all instances using it french.color = "red" printThem() del special.color # the template attr will reappear printThem() Peter From rainerd at eldwood.com Sat Nov 15 15:47:03 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Sat, 15 Nov 2003 20:47:03 GMT Subject: Is RAII possible in Python? References: <4_utb.21936$IK2.1678737@news20.bellglobal.com> Message-ID: Pierre Rouleau wrote: > Is RAII available in Python? In practice, yes. Objects are destroyed when their reference count goes to zero. In theory, no. The language specification does not guarantee this behavior. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From kiranb_102 at yahoo.com Sun Nov 2 01:10:22 2003 From: kiranb_102 at yahoo.com (Kiran B.) Date: 1 Nov 2003 22:10:22 -0800 Subject: Malformed header error... pls help! Message-ID: <5a0ddb88.0311012210.222a737@posting.google.com> hello, Im getting this error everytime i load this page. [error] [client 127.0.0.1] malformed header from script. Bad header=*** You don't have the (right): c:/program files/apache group/apache/cgi-bin/fig28_18.py I have connected all databases already. If I remove the import MySQL statement, theres no problem. But i need to use the database. . what could possibly be wrong??? pls help.. I have the MySQLdb installed in my Python directory already.. #!c:\Python23\python.exe import cgi import MySQLdb def printContent(): print "Content-type: text/plain\n\n" print print """ Registration results def printReply(): from convert import genPrime, genPrimeE p1 = genPrime() q1 = genPrime() e1 = genPrimeE() N1 = p1 * q1 M1 = (p1-1)*(q1-1) print 'e1 %d, m1 %d' %(e1,M1) while(e1 % M1 == 0): e1 = genPrimeE() connection = MySQLdb.connect( db = "try" ) cursor = connection.cursor() cursor.execute("insert into trials (p,q,n,m) values ('p1','q1','n1','m1');") authorList = cursor.fetchall() cursor.close() # close cursor connection.close() printContent() form = cgi.FieldStorage() personInfo = { 'firstName' : form[ "firstname" ].value, 'lastName' : form[ "lastname" ].value, 'email' : form[ "email" ].value, 'phone' : form[ "phone" ].value, 'book' : form[ "book" ].value, 'os' : form[ "os" ].value, 'message' : form["message"].value } printReply() From nicolas.lehuen at thecrmcompany.com Thu Nov 20 11:15:28 2003 From: nicolas.lehuen at thecrmcompany.com (Nicolas LEHUEN) Date: Thu, 20 Nov 2003 17:15:28 +0100 Subject: Suggestion for a new regular expression extension Message-ID: <3fbce8a0$0$25040$afc38c87@news.easynet.fr> Hi, I'm currently writing various regular expressions designed to help me parse some real-world French postal addresses. The task is not easy due to the vast amount of abbreviations, misspelling and variations in adresses. Just to give you a taste of what the regular expression looks like (unoptimized and perfectible, but for now it performs well enough) : re_adresse = re.compile(r''' (?P\d+(?:[ /\-]\d+)?)? \s* (?:(?P A | B(?:IS)? | C | E | F | T(?:ER|RE)? | Q(?:UATER)? )\b)? \s* (?P(?: (?:G(?:DE?|RDE?|RANDE?)\s+)?R(?:UE)? ....... (snip) .... | B(?:D|LD|VD|OUL(?:EVARD)?) ....... (snip) .... )\b)? (?:\s*(?P.+))? $ ''',re.X) Note for example the many abbreviations (correct or not) ouf "boulevard" : BD, BLD, BVD, BOUL, BOULEVARD. For normalisation purposes, I need to transform all those forms into the only correct abbreviation, BD. What would be really, really neat, would be a regular expression extension notation that would make the RE engine to return an arbitrary string when a substring is matched. The standard parenthesis operator return the matched text, whereas this extension would return any arbitrary text when getting a match. In my particular case, it would be very handy, allowing me to tell the RE engine to return me "BD" when matching B(?:D|LD|VD|OUL(?:EVARD)?). For now, without the extension, I need a two-pass process. First I try to "tokenize" the adress using the big regular expression cited above, then for each token I try to normalize it using a duplicate of the regular expression. This forces me to have two separate regular expression sets and requires maybe twice the processing power, whereas with an appropriate RE extension, all this could be done in a single pass. This extension would also be quite interesting to build transliterators, especially if the returned value could include references to other captured string. Let's say the extension would be written (?PRregular expression), with P meaning

ython extension (to keep consistency within sre_parse.py) and R meaning ewrite. Here is a sample run : >>> r = re.compile(r'^(\d+)\s+(?RB(?:D|LD|VD|OUL(?:EVARD)?))\s+(.*)$') >>> r.match('15 BD HAUSSMANN').groups() ('15','BD','HAUSSMANN') >>> r.match('15 BLD HAUSSMANN').groups() ('15','BD','HAUSSMANN') >>> r.match('15 BOULEVARD HAUSSMANN').groups() ('15','BD','HAUSSMANN') Perhaps the rewriting expression could include reference to other matched parentheses (but ) : >>> r = re.compile(r'(?R<\1\1>\d+)\s+\d+') >>> r.match('15 40').groups() ('1515','40') >>> r = re.compile(r'(?R<\1\2>\d+)\s+(\d+)') >>> r.match('1 4').groups() ('14','4') Maybe forward references would be too difficult to handle. The difficulty with this would be how to handle an expression like (?R<\2>.+)(\1) (throw an exception ?). The simplest thing to do would be to only allow back references, or only references to the current match of the parenthesis, with a notation like \m : >>> r = re.compile(r'.*(?R<$\m.00">\d+).*') >>> r.match('1540').group(0) '1540' >>> r.match('1540').group(1) '$1540.00' But anyway the reference to other groups in the rewriting expression would be only a plus. The core suggestion is just the rewrite extension. I also considered using sre.Scanner to do the stuff, but does anyone know what is the status of this class ? I made a few test and it seems to work, but it is still marked as 'experimental'. Why ? Last reference I saw to this class is there : http://aspn.activestate.com/ASPN/Mail/Message/python-dev/1614505... So, is this class good enough for common usage ? Anyway, this wouldn't suffice here because I would need a Scanner for the full adresse using different sub-Scanners for each address part... Best regards, Nicolas From mis6 at pitt.edu Thu Nov 6 01:59:56 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 5 Nov 2003 22:59:56 -0800 Subject: PEP 322: Reverse Iteration (REVISED, please comment) References: <5d83790c.0310281022.6264aa16@posting.google.com> <3f9ec63f$1@brateggebdc5.br-automation.co.at> Message-ID: <2259b0e2.0311052259.897e3ce@posting.google.com> Alex Martelli wrote in message news:... > math.sum would be arguably equivalent to sum as a built-in -- a > tad less immediately accessible, but perhaps superior in that it > immediately suggests it's about numbers only, so we'd avoid the > icky performance trap you now get with sum(manylists, []) {which > makes sum only 2/3 wonderful at best -- fine with numbers ONLY}. A recent post of yours made me realize that "sum" is NOT for numbers only: >>> class C(object): def __add__(self,other): return self >>> c1,c2,c3=C(),C(),C() >>> sum([c1,c2],c3) <__main__.C object at 0x00F4DED0> So, only summing strings is disallowed, all the rest is allowed, but there can be performance traps, for instance in summing lists. So, if 'sum' is only good at summing numbers, why this is not enforced? We are forbidden to sum strings, but then for the same reason we should be forbidden to sum lists: there is some inconsistency here ... care to explain the rationale for 'sum' again ? Michele From johnny.geling_rem*ove_this*_ at chello.be Mon Nov 17 02:56:40 2003 From: johnny.geling_rem*ove_this*_ at chello.be (Johnny Geling) Date: Mon, 17 Nov 2003 08:56:40 +0100 Subject: wxGrid (wxPYTHON) rowlabels In-Reply-To: References: <3fb408bf$0$9417$ba620e4c@reader3.news.skynet.be> Message-ID: Brian wrote: > Johnny Geling wrote in message news:... > >>>Take a look at GridDragable.py, in your wxPython demo directory. It >>>is called from the main demo, and it demonstrates custom rowlabels, >>>among other things. >> >>I downloaded the demo tar file but no file as you indicated above. >>Where can I find it? > > > The demo tar should unzip it to wxPython-2.4.2.4\demo. > > I just checked the demo tar on the wxPython to be sure (as I installed > from win32 installer which included the demo) and it's in there. > > Maybe you have an older demo tar? I think so. I grabbed it from the windows version and found it there. There are also other intresting features in that demo. Thanks Johnny From john at rygannon.com Mon Nov 3 13:19:53 2003 From: john at rygannon.com (John Dean) Date: Mon, 3 Nov 2003 18:19:53 GMT Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <3fa69c25$0$12666$fa0fcedb@lovejoy.zen.co.uk> > We had to let John go this last week, we tried to do it in an amicable > fashion, but John had and has been enganged in this type of activity > for a bit now. Unfortunately, this is not the truth and Shawn knows it. 1. I wasn't let go, I quit 2. Shawn and I had a resellers agreement 3. Shawn was fully aware that I had set up a Forum to provide support. This is/was something I had been trying to get him to do for many month, without success > Everything in this email is a complete fabrication. The facts speak for thenselves > John cannot legally sell the Rekall software, nor does he own it. This is not completely true. I have no agreement, either written or verbal with regards to the status of Rekall. TKC only have rights to the Rekall name. The copyright of the software itself is owned by Mike Richardson Rekall will be release under the GPL under its original name KBase > > I'm sorry for any confusion this might have caused anyone, but we're > still here and will be here for a long time to come It is just a matter of time before TKC goes under and that time is very, very short -- Best Regards John From dave_member at newsguy.com Tue Nov 11 22:59:48 2003 From: dave_member at newsguy.com (dave) Date: 11 Nov 2003 19:59:48 -0800 Subject: python-2.3.2 source code checksum error Message-ID: downaloded from ftp.python.org and failed to unzip the files: x Python-2.3.1/Mac/OSXResources/app/Resources/English.lproj/Documentation/ide/index.html, 9909 bytes, 20 tape blocks x Python-2.3.1/Mac/OSXResources/app/Resources/English.lproj/Documentation/ide/IDE.gif, 10249 bytes, 21 tape blocks tar: directory checksum error tried other versions (python) and they all failed in the same way ... i also downlaoded other gnu software from ftp.gnu.org and they were fine with no problem at all ... does anyone have such problem too? tia From mhammond at skippinet.com.au Sat Nov 1 19:50:37 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 2 Nov 2003 11:50:37 +1100 Subject: ANN: ActivePython 2.3.2 & ActivePython 2.2.3 In-Reply-To: <20031101143220.A4976@ActiveState.com> Message-ID: <041d01c3a0db$557615b0$0500a8c0@eden> > ...so I was just being cautious. If people consider those > builds stable > enough I wouldn't have a problem upgrading ActivePython's win32all. Well, I consider them stable when I release them :) The simple fact of the matter is that we don't have any kind of "release cycle" here, and I try and reflect that in the sequential numbering. The general process is that when I release a new win32all, I consider the previous one "stable", unless I have heard of real problems. And worse, each new win32all does have new features. Sometimes they are obscure, but sometimes they are more visible. Sometimes, these new obscure features will not be stable, while everything else is (and sometimes that is just fine - people want the experimental features early even if they may not be stable) IMO, the very best thing AS could do would be to arrange that a win32all package could update the version in ActivePython. There are a number of ways this could happen - I guess the one that needs the least of my time would be for you to have your own "ActivePython Update", built from my specific win32all tags in between ActivePython updates. A better way that would require some of my time is to have win32all.exe itself find and upgrade ActivePython. FYI, my short-ish term plans with win32all are to: * Enhance Thomas's distutils build script, and make that the "official" way to build and install sources (that holds the best hope for managing multiple Python versions at once from one source tree) * Drop all registry stuff, using a few .pth files * Re-do the setup script using inno. * Change win32all numbering slightly: win32all-200-2.3 - win32all build 200, for Python 2.3 win32all-200-2.2 - win32all build 200, for Python 2.2 win32all-200-2.3_d - _d and pch files for the above * Release from sourceforge. This will probably happen after the next 2 or so win32all releases. The second item in that list would be a good time to work out how we could upgrade ActivePython from win32all. I'll be putting out a new win32all by the middle of next week, but the reality is that things continue to enhance and change all the time. Mark. From bignose-hates-spam at and-benfinney-does-too.id.au Wed Nov 5 23:20:02 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 6 Nov 2003 15:10:02 +1050 Subject: Please Help Explain References: Message-ID: On Thu, 06 Nov 2003 04:01:21 GMT, Jakle wrote: > I was at a job interview one day and the owner of the start up company > asked me if I'd rather make $1000 dollars a day, or start off with a > penny a day and double the amount every day for 30 days. A classic surprise in mathematics. A doubling series gets large unexpectedly quickly, until you've seen it happen a few times. It's the subject of an ancient parable (of Arabic origin, I believe). A pauper manages to beat the king at chess, and the king condescendingly offers the pauper a hearty meal as reward. The pauper asks for a more modest reward: he asks the king to place a single rice grain on the first square of the board, two on the next, four on the next, eight on the next, and so on for all sixty-four squares of the chessboard. The king, believing he can be rid of the pauper for the price of a bowl or two of rice, agrees. By the end of the exercise, the pauper is owed enough rice to empty all the royal granaries. (2 to the power 64 is 18,446,744,073,709,551,616.) The same principle occurs in bacterial infection. A single bacterium infects the host, and then after a short time divides in two. This is repeated indefinitely; for a while, the host notices nothing, until quite suddenly the infection blossoms. The rate of doubling hasn't altered appreciably; but the increase after the initial slow period is dramatic. > I was too lazy to sit down with paper and pen to figure out how much > the second choice came out to. They weren't testing your ability to perform the arithmetic (2 to the power 30 is 1,073,741,824); they were testing your familiarity with the principle. > I came up with this formula: n = n*2. Yep, that's the formula (actually y = x * 2, so that it's clear there's an old value and a new one). > def calc(n, days): > i = 1 > while i <= days: > n = n*2 > i = i+1 > return n/float(100) > > I completely stumbled across it and it works. Copngratulations (and further points for wanting to understand why it works). > I just don't understand how the value of n is assigned to the second n > in "n=n*2" once it loops back again. The assignment conceptually occurs in two steps: - evaluate ("make a single value from") the right-hand side - asign the value to the left-hand side So the evaluation creates a new value that is (n*2). Then, this new value is assigned to n, and whatever value n held previously is forgotten. None of this is visible to you; it's all handled by the Python engine. All you see is the result (that n has the new calculated value). > I would understand if it was a recursive function and passed as an > argument, but I don't think I completely understand how the "while" > statement handles variable values. Hopefully this helps resolve the dilemma of a self-referential assignment. > I am learning from "How to Think Like a Computer Scientist: Learning > With Python" A good text. Also work through these: "Python tutorial" (as soon as you can) "Dive Into Python" (when you're ready for some more) -- \ "It was half way to Rivendell when the drugs began to take | `\ hold" -- Hunter S. Tolkien, _Fear and Loathing in Barad-D?r_ | _o__) | Ben Finney From fBechmann at web.de Sun Nov 9 09:17:38 2003 From: fBechmann at web.de (Frank Bechmann) Date: 9 Nov 2003 06:17:38 -0800 Subject: how to get a list of available drives (partitions) in windows References: Message-ID: thx for the quick help! seemed to be a problem that's not easy to be googled. and sorry in advance for the double-post which will show up soon. From aleax at aleax.it Wed Nov 12 11:03:42 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 12 Nov 2003 16:03:42 GMT Subject: case-sensitivity (was Re: True, False, None) References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> Message-ID: Michele Simionato wrote: ... >> Why is staticmethod "a class" to you while int presumably isn't? > > Actually, I would prefer "Int" over ""int" ;) A consistent preference -- which will never be satisfied, of course. So, when I used to have a factory function (as 'int' was), and change it into a type (or class, same thing), I should rename it and break all existing programs that would otherwise keep working just fine? Or would you prefer to bloat the built-in namespace (or module namespace where such refactoring is going on) by having both 'int' _and 'Int'? I consider such a desire to distinguish callables that are for the most part quite polymorphic, such as types/classes on one hand and factory functions on the other, quite misplaced. Python is all about signature-based polymorphism: why should we sacrifice the wonders of this on the altar of "Capitalization"?! > saying "classes are capitalized". Of course, I am not proposing to > change anything. It is a very minor annoyance I can very well live > with. To me, case sensitivity is somewhat more than a minor annoyance, though I still live with it because the case-insensitive languages I know of (such as Lisp) have many more things I don't really like. > I never understood why you advocate case insensitivity. I would expect > case insensitivity to be a source of bugs: for instance, identifiers > with similar names could be confused (es. myfunction vs. myFunction): > one would expect them to be different (at least people coming from > case insensitive languages) whereas they would be the same. People coming from (an exclusive diet of) case _sensitive_ (not, as you say, INsensitive!) languages would surely expect these identifiers to be separate, but there are enough people coming from case INsensitive languages (Pascal, Fortran, Basic, Lisp, ...) to basically even this factor out. One factor that makes me prefer insensitivity is that people who meet Python as their _first_ programming language quite rightly see case-sensitivity as just one more hassle being thrown at them, since in real life people aren't really case-sensitive. E.g., intel's trademark is all-lowercase, but on the website they keep referring to themselves as uppercase-I Intel and nobody's confused; hostnames and protocols in URL's are case-insensitive, too, so people don't particularly have a connection of computers with case-sensitivity; so are filenames in Windows, the most widespread OS, and MacOS, widely considered the most user-friendly one (in the default filesystem, although since it has Unix underneath you can use a case-insensitive FS on it if you deliberately go for it); etc, etc, ad nauseam. But people's expectations when they first meet Python are only a part of it. More relevant is, how usable are the two possibilities? Case sensitivity means you must basically memorize several more bits to go with each name -- for no good reason whatsoever. You must remember that module FCNTL has an all-uppercase name, htmllib all-lower, cStringIO weirdly mixed, mimetypes lower, MimeWriter mixed, etc, etc -- totally wasted mnemonic effort. Then you get into the single modules for more of the same -- unless you can know what is conceptualized as "a class" vs "a type" vs "a function" memorization's your only hope, and if you DO know it's still learning by rote, incessantly (ah yes, class dispatcher in module asyncore, that's LOWER-case, ah yes, the 'error' exception class, that's lowercase in sunaudiodev, it's lowercase in socket, and in anydbm, and thread -- it's uppercase Error in sunau, and also in shutil, and multifile, and binhex ... and functions are supposed to start lowercase? Yeah right, look at imaplib and weep. or stat. or token... And you think your troubles are over once you've got the casing of the FIRST letter right? HA! E.g., would the letter 'f' in the word 'file' be uppercased or not when it occurs within a composite word? Take your pick... shelve.DbfilenameShelf, zipfile.BadZipfile, zipfile.ZipFile, mimify.HeaderFile, ... Basically, you end up looking all of these things up -- again and again and again -- for no good reason. Case-sensitivity inevitably causes that, because people sometimes think of e.g. "zipfile" as ONE word, sometimes as two, so they uppercase the 'f' or not "wantonly". Some will inevitably say that's just the fault of the human beings who choose each of these many names -- case sensitivity as an abstract ideal is pristine and perfect. To which, my witty repartee is "Yeah, right". When you present me a language whose entire libraries have been written by superhumanly perfect beings my attitude to case sensitivity may change. Until you do, I'll surmise that _most_ such languages and libraries ARE going to be written by humans, and there really is no added value in me having to memorize or constantly look up the capitalization of all of these names -- misspellings are bad enough (and fortunately are generally acknowledged as mistakes, and fixed, when found, which isn't the case for capitalization issues). Moreover, many of the distinctions you're supposed to be drawing with this precious capitalization, allegedly worth making me and a zillion learners suffer under silly gratuitous mnemonic load, are distinctions I'd much rather *NOT* see, such as ones between types and classes (traditionally), or types/classes and factory functions. Some factory functions get capitalized, like threading.RLock, cause it's "sorta like a class", some don't, because, hey, it's a function. More useless distinction and more memorization. But at least constants, I hear some claim? THOSE are invariably ALWAYS spelled in all-uppercase...? "Sure", say I, "just like math.pi"... > Also, now I can write > > ONE=1 > > and > > def one(): return 1 > > and it is clear that the first name (ONE) refers to a constant > whereas the second name (one) refers to something which is not a constant. Except that it is, unless your design intention (unlikely though possible) is that the user will rebind name 'one' in your module to indicate some other function object. Unless such is your meaning, names 'one' and 'ONE' are "constants" in exactly the same sense: you do not intend those names to be re-bound to different objects. One of the objects is callable, the other is not, but that's quite another issue. One is technically immutable -- the other one isn't (you can set arbitrary attributes on it) but it IS hashable (the attributes don't enter into the hash(one) computation) which is more often than not the key issue we care about when discussing mutability. So, what IS "a constant" in Python? If you wanted to bind a name (asking implicitly that it never be re-bound) to a "indisputably mutable" (not hashable) object, how would you capitalize that? Python itself does not seem to care particularly. E.g.: >>> def f(): pass ... >>> f.func_name = 'feep' Traceback (most recent call last): File "", line 1, in ? TypeError: readonly attribute >>> f.func_defaults = () I can rebind f.func_defaults, NOT f.func_name -- but they have exactly the same capitalization. So, no guidance here... > In a case insensitive language I am sure I would risk to override > constants with functions. Why is that any more likely than 'overriding' (e.g.) types (in the old convention which makes them lowercase) or "variables" (names _meant_ to be re-bound, but not necessarily to functions)? And if you ever use one-letter names, is G a class/type, or is it a constant? I consider the desire to draw all of these distinctions by lexical conventions quite close to the concepts of "hungarian notation", and exactly as misguided as those. > When I learned C (coming from Basic and Pascal) > I thought case sensitivity was a good idea, why you don't think so? When I learned C (coming from a lot of languages, mostly case insensitive) I thought case sensitivity was a ghastly idea, and I still do. Much later I met the concept of "case _preservation_" -- an identifier is to be spelled with the same case throughout, and using a different casing for it is either impossible or causes an error -- and THAT one is a concept I might well accept if tools did support it well (but I suspect it's more suitable for languages where there are declarations, or other ways to single out ONE spelling/capitalization of each identifier as the "canonical, mandated" one -- I'm not sure how I'd apply that to Python, for example). As long as I could input, e.g., simplexmlrpcserver and have the editor (or whatever tool) change it to SimpleXMLRPCServer (or whatever other SpelLing they've chOseN) I wouldn't mind as much. > (you are free to point me to old posts if this, as I suspect, has > been debated to death already ;) Oh, this isn't the first round, but it isn't the second one, either. It's essentially a discussion on how languages should be designed, rather than anything that could ever concretely change in Python: the very existence of "indistinguishable except for spelling" names such as fileinput and FileInput, random and Random, etc, etc, makes it certain that this characteristic can never be changed. Perhaps it's exactly because the discussion is totally moot, that it keeps getting hot each time it's vented (wanna bet...?-). Alex From ulope at gmx.de Mon Nov 3 18:36:25 2003 From: ulope at gmx.de (Ulrich Petri) Date: Tue, 4 Nov 2003 00:36:25 +0100 Subject: running functions in parallel on multiple processors References: Message-ID: "Jon Franz" schrieb im Newsbeitrag news:mailman.372.1067870688.702.python-list at python.org... > Michael, > I may have something laying around that would be useful for you - > its a module I wrote that makes forked multi-process programing > very easy, since each process accesses a shared data-store > automatically. I haven't released it due to a lack of time to write > documentation, but it sounds like it may be the sort of thing you could use. > It's called remoteD, and it works like this: > > Anyway, I'll end up writing better documentation and doing an official > release > on sourceforge later this week - but for now you can download it at: > http://www.neurokode.com/remoteD.tar > I hope this helps, feel free to bug me with questions. > Whoa this is great stuff! I was looking for sth. like this for a long time... Thanks. From jcb at iteris.com Tue Nov 4 15:09:14 2003 From: jcb at iteris.com (MetalOne) Date: 4 Nov 2003 12:09:14 -0800 Subject: Any suggestions to speed this up Message-ID: <92c59a2c.0311041209.2e89e054@posting.google.com> def buildBitmap(rawData, w, h, maxColorVal): """ppm format, http://netpbm.sourceforge.net/doc/ppm.html Constructs a wxBitmap. The input is a raw grayscale image, 8 bits per pixel.""" imageHdr = "P6\r%d %d\r%d\r" % (w, h, maxColorVal) #expand grayscale to rgb imageBuf = imageHdr + string.join([v*3 for v in rawData], "") return wxBitmapFromImage( wxImageFromStream( cStringIO.StringIO(imageBuf) )) Virtually all the time is consumed expanding the 1 byte of grayscale data into 3 bytes to get RGB. For example, V=128 is converted to R=128,G=128,B=128. On my computer I can display 3 frames per second of 360x240 data. If I modify the imageBuf line to imageBuf = imageHdr + rawData*3, then I can display 40fps. Of course, the image doesn't look right, but that is the kind of speed that I desire. I have tried a few things, 1) Building the string using cStringIO. 2) map instead of list comprehension. 3) I tried to get fancy with zip(rawData, rawData, rawData) followed by string joins. None of these had any speed improvement and 3) was much slower. I am hoping not to have to write an extension module in "C". From dont_use at nowhere.com Sat Nov 29 20:01:06 2003 From: dont_use at nowhere.com (Glenn Reed) Date: Sun, 30 Nov 2003 14:01:06 +1300 Subject: PythonWin IDE doesn't save all project files?? Message-ID: Hi, Someone might be able to help me with this. If I am using PythonWin (as part of the ActiveState Python distribution) (lastest release 2.2) and have two files in the editor window. ---- module1.py -------- class module1: def __init__(self): self.x=23 self.y=14 self.z=33 self.x1=self.x ---- tmod.py ---- # Test Module import module1 thisClass = module1.module1() print thisClass.x ------------------------ and then I run this script tmod.py I get the correct answer 23 However if I then go back and change the value of the variable in module1.py and change 'self.x=23' to 'self.x=45' and run the tmod.py script again I still get the answer 23. I click the "save all files" icon which is a picture of 3 floppy disks and run the tmod.py again and I still get 23. If I exit PythonWin and start it again and load the same scripts I get the correct answer 45. I have tried closing and reopening the module1.py source file but nothing helps until I restart PythonWin. Does anyone know what is happening here? Thanks in advance. Glenn. From jwsacksteder at ramprecision.com Tue Nov 4 15:39:39 2003 From: jwsacksteder at ramprecision.com (jwsacksteder at ramprecision.com) Date: Tue, 4 Nov 2003 15:39:39 -0500 Subject: enable/disable widgets with checkbox(TKinter) Message-ID: <71650A6F73F1D411BE8000805F65E3CB3B3722@SRV-03> I want to have a check box that can optionally disable a text input field in the same dialog. I am asking the user to input the start and end of a range and there needs to be a check box to select all items. When the checkbox changes state, I want to ghost-out the input fields. A rough approximation of the situation follows. class mystuff(Frame): def __init__(self,parent=None): Frame.__init__(self,parent) self.CheckMode = IntVar() self.mode_label = Label(self, text='All Line Items?', borderwidth='5') self.mode_box = Checkbutton(self, width='1',variable=self.CheckMode,command=self.FlipState) self.input_label = Label(self, text='Input Name', borderwidth='5') self.input_box = Entry(self, width='3') self.pack() def FlipState(self): #This does not work! self.input_box.disable() print "variable is", self.LineItemMode.get() From max at alcyone.com Mon Nov 3 23:20:13 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 03 Nov 2003 20:20:13 -0800 Subject: for line in ftpr: and fptr.tell() References: Message-ID: <3FA728FD.501EE060@alcyone.com> Jamey Cribbs wrote: > Because you won't get the correct file position from tell(). I think > it > had something to do with the file iterator caching several kb of the > file when it first started the for loop. > > Is there a fix/work-around for this? Yes. Use: while True: line in F.readline() if not line: break pos = F.tell() ... Seriously, the problem here is that iterating over a while has the same effect as F.xreadlines() For efficiency, the reads are buffered, so interacting with the file object while you're using one of these methods results in weird behavior. If you want to interact with the file object while you're also reading in lines, you should not use either of those mechanisms. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Something to remember you by. \__/ Leonard Shelby From max at alcyone.com Mon Nov 17 17:11:59 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 17 Nov 2003 14:11:59 -0800 Subject: Origin of the term "first-class object" References: <8ef9bea6.0311171335.356a7af6@posting.google.com> Message-ID: <3FB947AF.F4F942BE@alcyone.com> Hung Jung Lu wrote: > Does anybody know where this term comes from? > > "First-class object" means "something passable as an argument in a > function call", but I fail to see the connection with "object class" > or with "first-class airplane ticket". It doesn't have any connection with the former (since the term long predates object orientation, so far as I know). It does have a connection to the latter, in that something going first class has all the privileges and properties owed to it as a complete and total thing. So a "first-class object" is a complete entity unto itself, and can be passed to functions and returned from them, as you suggest. Think of "first-class object" as "important thing" and maybe it'll make slightly more sense. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ The only way to get rid of a temptation is to yield to it. -- Oscar Wilde From amy-g-art at cox.net Sat Nov 22 13:16:06 2003 From: amy-g-art at cox.net (Amy G) Date: Sat, 22 Nov 2003 10:16:06 -0800 Subject: Newbie here... getting a count of repeated instances in a list. References: Message-ID: Thanks for that, I will try come Monday. Hopefully it will work. AMY "Amy G" wrote in message news:keyvb.5217$9O5.2011 at fed1read06... > I started trying to learn python today. The program I am trying to write > will open a text file containing email addresses and store them in a list. > Then it will go through them saving only the domain portion of the email. > After that it will count the number of times the domain occurs, and if above > a certain threshhold, it will add that domain to a list or text file, or > whatever. For now I just have it printing to the screen. > > This is my code, and it works and does what I want. But I want to do > something with hash object to make this go a whole lot faster. Any > suggestions are appreciated a great deal. > > Thanks, > Amy > > ps. Sorry about the long post. Just really need some help here. > > > CODE > ************************ > file = open(sys.argv[1], 'r') # Opens up file containing emails > mail_list = file.readlines() # and sets the contents into a > list > > def get_domains(email_list): # This function takes list of emails > and returns the domains only > domain_list = email_list > line_count = 0 > while line_count < len(email_list): > domain_list[line_count] = > email_list[line_count].split('@', 1)[1] > domain_list[line_count] = > email_list[line_count].strip() > return domain_list > > def count_domains(domain_list): # Takes argument of a list of domains and > returns a list of domains that > counted_domains = 0 # occur more than number > of times > line_count = 0 > domain_count = 0 > threshhold = 10 > while line_count < len(domain_list): > domain_count = > domain_list.count(domain_list[line_count]) > if domain_count > threshhold: > r = 0 > counted_domains.append(d) > while r < (domain_count -1): > # Remove all other instances of an email once counted > domain_list.remove(d) > r = r + 1 > line_count = line_count + 1 > return counted_domains > > > domains = get_domains(mail_list) > counted = count_domains(domains) > print counted > > ******************************************** > > From joconnor at cybermesa.com Wed Nov 12 11:35:20 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Wed, 12 Nov 2003 16:35:20 GMT Subject: True, False, None References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> Message-ID: <3fb2606a.49907930@news.cybermesa.com> On Wed, 12 Nov 2003 09:12:42 GMT, Alex Martelli wrote: >To me, personally, all of this debates only underscores yet again the >one serious "ergonomic" defect in Python's syntax -- case sensitivity. Prior to Python I was using Smalltalk, which is case sensitive. Like 'case statements' it's something that even after using Python quite some time I never really even thought about whether the language had it or not. From dw-google.com at botanicus.net Thu Nov 6 06:19:22 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 6 Nov 2003 03:19:22 -0800 Subject: dump table and data with mysqldb References: <99dce321.0311050726.3e369dcf@posting.google.com> Message-ID: <99dce321.0311060319.afc66fc@posting.google.com> "Hoang" wrote in message news:... > "SELECT * FROM database INTO OUTFILE file" > to redirect to across the network rather than the local file-system. > mysqldump also puts it into the local FS. There might be no recourse other > than having to recreate the INSERT statements in your own code. I think someone can't be bothered reading the documentation. :) Delete your dump_structure_sql and replace with this code. To the best of my knowledge this replicates the part of MySQLdump that you require. dump_data_sql could be broken out into another function or two, but for speed I left it as it is below. Hope this helps, David. PS: it outputs in MySQL 'extended' INSERT format, which is apparently slightly faster than multiple INSERTs, but may not work with other databases. def dump_sql(db, dump_data = False): print "#" print "# Dumping schema for database", get_db_name(db) print "#" print print for table, create_def in get_structure_sql(db).iteritems(): print "#" print "# Dumping schema for table", table print "#" print print create_def print print if dump_data: dump_data_sql(db, table) def get_column_names(cursor, table): cursor.execute("DESCRIBE %s" % (table)) return [ row[0] for row in cursor ] def dump_data_sql(db, table): cursor = db.cursor() colnames = get_column_names(cursor, table) colnames_sql = ', '.join(colnames) count = cursor.execute("SELECT %s FROM %s" % (colnames_sql, table)) if count == 0: return print "#" print "# Dumping data for table", table print "#" print print "INSERT INTO %s(%s) VALUES" % (table, colnames_sql) count -= 1 for index, row in enumerate(cursor): row_sql = " (%s)" % (', '.join(db.escape(row))) if index < count: print row_sql + "," else: print row_sql + ";" print print From aleax at aleax.it Fri Nov 14 04:44:30 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Nov 2003 09:44:30 GMT Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> Message-ID: <2u1tb.25127$hV.934365@news2.tin.it> Brandon J. Van Every wrote: ... > It is still not a good sign. If Python is so easy, and it were also > popular, then presumably people would write problem specific books "in > Python." Do your website in Python, your database in Python, your game in > Python, your AI in Python, your laundry in Python... Yes, there's quite a few of those -- "Game Programming with Python" (by Sean Riley) came out last month, "Game Programming With Python, Lua, and Ruby" (by Tom Gutschmidt) should be out any day now, "Text Processing in Python" (by David Mertz) has been out for months, "Python Web Programming" (by Steve Holden) and "Web Programming in Python) (by George Thiruvathukal, Thomas Christopher, John Shafaee) even longer, and similarly for other popular "specific areas" such as XML processing. Still, book-publishing is an "interesting" activity -- and stocking bookstore shelves even more so. A purely anecdotal datum I just learned about, for example: smack in the heart of downtown Milan there are two excellent, large bookstores which are always hotly competing. Somebody was looking for "Python in a Nutshell" at one of them and complained on an Italian Python list that they had no copies at all on the shelves; somebody else replied, quite perplexed, that the _other_ of the two bookstores had _five_ copies on _its_ shelves... ...and unless you get friendly enough with the store's personnel to chat about such issues, it's gonna be hard to learn whether one store is cursing and swearing for wasting such shelfspace for a book which just is not moving, or the other is desperate for more copies of a book it has run out of...:-) Personally, I think my (admittedly risible:-) "googling survey" is a more accurate gauge of a language's popularity than eyeballing the variety or abundance of titles about it at one or a few bookstores;-) Alex From bokr at oz.net Thu Nov 20 22:07:46 2003 From: bokr at oz.net (Bengt Richter) Date: 21 Nov 2003 03:07:46 GMT Subject: time.mktime memory access violation bug References: Message-ID: On Thu, 20 Nov 2003 23:54:24 +0100, Peter Otten <__peter__ at web.de> wrote: >Bengt Richter wrote: > >> What does the following sequence do on your machine? Your tests did not >> apparently exercise the daylight savings time path involved in my crash. > >My (tacit, sorry) assumption was that setting daylight savings to 1 would >subtract 3600s from the Unix epoch, making it a negative value and thus >provoke the crash. But that was wrong: > >>>> def d(t): >... tpl = time.localtime(t) >... return time.mktime(tpl[:-3] + (0, 0, 0)) - time.mktime(tpl[:-3] + >(0, 0, 1)) >... >>>> d(0) >0.0 > >With an arbitrary summer time: > >>>> d(962924461) >3600.0 >>>> > >> E.g., >> >> >>> import time >> >>> time.localtime(0) >> (1969, 12, 31, 16, 0, 0, 2, 365, 0) >> >>> time.mktime(time.localtime(0)) >> 0.0 >> >>> time.mktime(time.localtime(0)[:6]+(0,0,1)) >> >> (my NT4 crashes here) >> > >For completeness: > >>>> time.localtime(0) >(1970, 1, 1, 1, 0, 0, 3, 1, 0) >>>> time.mktime(time.localtime(0)) >0.0 >>>> time.mktime(time.localtime(0)[:6] + (0, 0, 1)) >0.0 >>>> > >From the docs I would expect that such a "smart" behaviour would require a >DST flag of -1. Agreed. > >Looking at the two zero times (UTC + x vs UTC - x hours) I wonder if an NT >machine on this side of the zero meridian would encounter the same >problems. I suspect so. I think it is in the mktime.c of the MS library: > I suspect that "can't get NULL" is wrong in this snippet from D:\VC98\CRT\SRC\MKTIME.C when passed the zero epoch, because the associated localtime doesn't handle negative epoch time. ==== /* * Convert this second count back into a time block structure. * If localtime returns NULL, return an error. */ if ( (tbtemp = localtime(&tmptm1)) == NULL ) goto err_mktime; /* * Now must compensate for DST. The ANSI rules are to use the * passed-in tm_isdst flag if it is non-negative. Otherwise, * compute if DST applies. Recall that tbtemp has the time without * DST compensation, but has set tm_isdst correctly. */ if ( (tb->tm_isdst > 0) || ((tb->tm_isdst < 0) && (tbtemp->tm_isdst > 0)) ) { tmptm1 += _dstbias; tbtemp = localtime(&tmptm1); /* reconvert, can't get NULL */ } ==== I think it dies a little later on *tb = *tbtemp; ... stepping through disassembly of optimized code with no source except the separate file to infer what is going on ;-/ This is from MSVC++6.0 BTW, which UIAM windows python 2.3.2 still was compiled with(?) What is Python policy when a vendor lib module causes a bug? Regards, Bengt Richter From ameLista at telia.com Fri Nov 28 12:14:44 2003 From: ameLista at telia.com (Anders Eriksson) Date: Fri, 28 Nov 2003 17:14:44 GMT Subject: Strange behavior in PythonWin IDE References: <1fa1hqqgi2xas.dlg@morateknikutveckling.se> Message-ID: <1don4gzcf9gcq$.dlg@amez.homeip.net> On Fri, 28 Nov 2003 15:59:51 +0100, Gilles Lenfant wrote: > This bug (and others related to charsets) has been submitted some months > ago... OK, I didn't know that PythonWin was on SourceForge, but I will try there instead. Thank You ! // Anders -- At-home-but-still-working From bgudorf at neurokode.com Mon Nov 3 11:06:12 2003 From: bgudorf at neurokode.com (Bryan J Gudorf) Date: Mon, 3 Nov 2003 11:06:12 -0500 Subject: Python Database Objects (PDO) 1.1.0 Released Message-ID: Python Database Objects 1.1.0 has been released. This fairly stable test release includes support for various databases through the mxODBC module. This release also adds more functionality through commands such as move and moveto, which allow for more dynamic movement through a recordset. As we move forward in the 1.1 series we will be adding support for more databases. Community support and feedback is appreciated so that we can make PDO as useful as possible. As released previously: Python Database Objects (PDO) provides an easy to use Object Oriented API for database developers. PDO utilizes DB-API modules for database access, but allows for a Common Object Oriented API across RDBMS. Thus, PDO can be thought of as a 'wrapper' around the DB-API and database specific modules. PDO offers a unique interface which includes such features as column access by name, forward and backward movement through a result set and much, much more. Downloads for Python Database Objects are available on SourceForge.Net or for more information please visit pdo.neurokode.com. Bryan J Gudorf ~NeuroKode Labs From jjl at pobox.com Wed Nov 26 14:53:37 2003 From: jjl at pobox.com (John J. Lee) Date: 26 Nov 2003 19:53:37 +0000 Subject: Extracting email attachment when is_multipart() is False References: <87r7zw9ur6.fsf@pobox.com> Message-ID: <87fzgavrcu.fsf@pobox.com> Derrick 'dman' Hudson writes: > On Wed, 26 Nov 2003 08:06:15 +0100, Davor Cengija wrote: [...] > >> You seem to be missing the RFC 822 headers (From, To, Subject, etc.). > > > > Yes, that's true. The question is if it's easier to write a parser for that > > kind of messages or to force the message producing application to output the > > headers as well. We'll see... > > You have a third option, which I would try if you can't get the > message producer to do it correctly: slap some RFC822 headers on the > beginning, and then ignore them in the parsed message object. After [...] Or read the docs & code for the email module, to figure out how to persuade it to take the messages without the headers. John From ville.spammehardvainio at spamtut.fi Sun Nov 23 10:38:12 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 23 Nov 2003 17:38:12 +0200 Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> <7xwu9svyny.fsf@ruckus.brouhaha.com> <7xvfpcowjt.fsf@ruckus.brouhaha.com> <653b7547.0311222346.b4d9e98@posting.google.com> Message-ID: John Hunter writes: > >>>>> "Ville" == Ville Vainio writes: > > Ville> In the light of this, does releasing a library under GPL > Ville> (as opposed to LGPL) make any sense at all? > > Yes (re GPL), if you want to place the additional burden on users to > release their derived works under GPL. Ie, if you beliwve all But if the software is distributed w/o libraries, and the user has to d/l the libs themselves, then the code is not covered by GPL. So a library under GPL would effectively be a library under LGPL, with the difference that the end user has to do some extra legwork to start using the program. This simple loophole makes the GLP look like it was never intended for libraries (except static libs). -- Ville Vainio http://www.students.tut.fi/~vainio24 From theller at python.net Wed Nov 19 15:14:47 2003 From: theller at python.net (Thomas Heller) Date: Wed, 19 Nov 2003 21:14:47 +0100 Subject: win32com bugfix References: Message-ID: "Koen Van Herck" writes: > I've posted two bugfixes to the python-win32 mailing list, but there seems > to be not much activity on that list. Is there another place (here?) that I > should post them? You could try and mail your fixes directly to Mark Hammond, or you submit them as patches to http://sf.net/projects/pywin32 Thomas From adalke at mindspring.com Mon Nov 10 18:51:13 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 10 Nov 2003 23:51:13 GMT Subject: Am I the only one who would love these extentions? - Python 3.0 proposals (long) References: Message-ID: Georgy Pruss: > 1) Underscores in numbers. It will help to read long numbers. > E.g. > 12_345_678 > 3.14159_26535_89793_23846 Perl has this. How often do long numbers occur in your code? When is the workaround of int("12_345_678".replace("_", "")) float("3.14159_26535_89793_23846".replace("_","")) inappropriate? Note also that this allows the more readable (to some) float("3.14159 26535 89793 23846".replace(" ","")) > 2) Binary constants. Not in great demand, just nice to have, > half an hour to implement. > E.g. > 0b01110011 > 0b1110_0101_1100_0111 Why is it nice enough to make it be a syntax addition, as compared to >>> int("01110011", 2) 115 >>> int("1110_0101_1100_0111".replace("_", ""), 2) 58823 >>> ? > 3) Hex strings. Very useful when you want to initialize long > binary data, like inline pictures. > E.g. > x'48656C6C6F 21 0D0A' > ux'0021 000D 000A' > They can be combined with other strings: 'Hello!' x'0d0a' > Now you can use hexadecimal values, but with two times > longer sequences like '\x..\x..\x..\x..', or do the translation > during run-time using '....'.decode('hex'). I very rarely include encode binary data in my data files. Images should usually be external resources since it's hard to point an image viewer/editor at a chunk of Python code. A counter example is some of the PyQt examples, which have pbm (I think) encoded images, which are easy to see in ASCII. In that case, there's a deliberate choice to use a highly uncompressed format (one byte per pixel). The run-time conversion you don't is only done once. In addition, another solution is to have the Python spec require that a few encodings (like 'hex') cannot be changed, and allow the implementation to preprocess those cases. So why is it useful enough to warrant a new special-case syntax? > 4) Keywords 'none', 'false', 'true'. They should be keywords, > and they should be lowercase, like all the rest keywords. > True, False and None can stay for some time as predefined > identifiers, exactly like they are now. Why *should* they be lower case? There was a big dicussion when True/False came out, which resulted in that "casing". You argue consistancy to other keywords. What other keywords refer to objects? >>> keyword.kwlist ['and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'yield'] >>> None that I can see. > 5) Enum type. There are approximations to this, as in http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67107 > # defines constants AXIS.X=0, AXIS.Y=1, AXIS.Z=2 > enum AXIS: X, Y, Z For that case, I would prefer the following class AXIS: X, Y, Z = range(3) If there are more terms then here's an alternative. I've not seen it before so I think it's a novel one class Keywords: AND, ASSERT, BREAK, CLASS, CONTINUE, DEF, \ DEL, ELIF, YIELD, ... = itertools.count() That is, the ellipsis at the end of a sequence assignment means to ignore RHS terms at that point and beyond. > # defines color.red, color.green, color.blue > enum color > red = '#FF0000', green = '#00FF00', blue = '#0000FF' This can be done already as class color: red = '#FF0000' green = '#00FF00' blue = '#0000FF' > # defines consts A=0, B=1, C=2, D=10, E=11, F=12 > enum > A, B, C > D = 10, E > F While I know C allows this, I've found it more confusing than useful. What about class consts: A, B, C, ... = itertools.count() D, E, F, ... = itertools.count(10) > 6) The colon is optional after for,if,try,enum etc. if it is > followed by a new line. Although it's mandatory if there are > statements on the same line. So it's like ';' -- you MUST > use it when it's needed. You CAN still use it if you like it, > like now you can put a semicolon after each statement > as well. > > def abs(x) > if x < 0 > return -x > else > return x The reason for the ":" is to make the block more visible. This came out during human factors testing in ABC (as I recall). It also simplifies tool development since software can assume that if the previous line ends in a : then there should be an indent. BTW, what advantage is there in having an optional syntax for this? > 7) Built-in regex'es. It would be nice to have built-in regular > expressions. Probably, some RE functionality can be shared > with the built-in string class, like presently we can write > 'x'.encode('y'). For example $str can produce a regex object > and then s==re can return true if s matches re. This would be > very good for the switch construction (see below). > E.g. > id = $ "[A-Za-z_][A-Za-z0-9_]*" > if token == id: return token Regexps play much less a role than in languages like Perl and Ruby. Why for Python should this be a syntax-level feature. Eg, your example can already be done as id = re.compile("[A-Za-z_][A-Za-z0-9_]*") if id.match(token): return token Note that you likely want the id pattern to end in a $. A downside of the == is that it isn't obvious that == maps to 'match' as compared to 'search'. Suppose in 5 years we decide that Larry Wall is right and we should be using Perl6 regexp language. (Just like we did years ago with the transition from the regex module to the re module.) What's the viable migration path? Does your new regexp builtin allow addition $"[A-Za-z_]" + $"[A-Za-z0-9_]*" or string joining, like $"[A-Za-z_]" $"[A-Za-z0-9_]*" or addition with strings, as in $"[A-Za-z_]" + "[A-Za-z0-9_]*" What about string interpolation? $"[%s]" % "ABCDEF" > 8) Slices. They can have two external forms and they are > used in three contexts: a) in [index], b) in the 'case' clause, > c) in the 'for-as' statement. The have these forms: > a:b means a <= x < b (a:b:c -- with step c) > a..b means a <= x <= b (a..b:c -- with step c) > E.g. > 1:100 == 1,2,3,...,99 > 1..100 == 1,2,3,...,100 See http://python.org/peps/pep-0204.html . Proposed and rejected. > 9) For-as loop. See also http://python.org/peps/pep-0284.html which is for integer loops. Since your 8) is rejected your 9) syntax won't be valid. > 10) Until loop -- repeat the loop body at least one time > until the condition is true. > > until > > > It's the same as: > > > while not > Actually, it's the same as while True: if postcond: break Why is this new loop construct of yours useful enough to warrant a new keyword? > 11) Unconditional loop. Yes, I'm from the camp that > finds 'while 1' ugly. Besides, sometimes we don't need > a loop variable, just a repetition. > > loop [] > > > E.g. > loop 10 > print_the_form() > > loop > line = file.readline() > if not line > break > process_line( line ) Do you find 'while True' to be ugly? How much code will you break which uses the word "loop" as a variable? I know you expect it for Python 3 which can be backwards incompatible, but is this really worthwhile? How many times do you loop where you don't need the loop variable? Is this enough to warrant a special case construct? I don't think so. Note that the case you gave is no longer appropriate. The modern form is for line in file: process_line(line) > 12) Selection statement. The sequence (it can also > occur in the for-as statement, see above) is composed > of one or more expressions or slices. > > switch > case > > case > > else > > > The sequence can contain RE-patterns. > > case $pattern,$pattern2 # if expr matches patterns > ... See http://python.org/peps/pep-0275.html which has not yet been decided > 13) One line if-else. > > if : ; else: Why? What's the advantage to cramming things on a line compared to using two lines? if a: print "Andrew" else: print "Dalke" Even this is almost always too compact for readability. > 14) Conditional expression. Yes, I'd love it. > > cond ? yes : no rejected. See http://python.org/peps/pep-0308.html > 15) Better formatting for repr() > > repr(1.1) == '1.1' > > If the parser recognizes 1.1 as a certain number, I can't see > any reason why it should print it as 1.1000000000000001 for > the next parser run. Then use 'str', or "%2.1f" % 1.1 What you want (a parser level change) makes a = 1.1 repr(a) different from repr(1.1) That's not good. Note that 1.1 cannot be represented exactly in IEEE 754 math. Following IEEE 754 is a good thing. What is your alternative math proposal? > 16) Depreciated/obsolete items: > > -- No `...` as short form of repr(); I agree. I believe this is one of the things to be removed for Python 3. > -- No '\' for continuation lines -- you can always use parenthesis; I agree. I believe this is one of the things to be removed for Python 3. > -- No else for while,for,try etc -- they sound very unnatural; I've found 'else' very useful for a few cases which once required ugly flags. > -- Ellipsis -- it looks like an alien in the language. As you can see, I proposed a new way to use ellipsis. In real life I almost never use the .... > I do believe that these changes follow the spirit of the language > and help Python to become an even better language. Given how many new looping constructs you want, I disagree with your understanding of the spirit of the language. Andrew dalke at dalkescientific.com From jfranz at neurokode.com Tue Nov 25 13:07:18 2003 From: jfranz at neurokode.com (Jon Franz) Date: Tue, 25 Nov 2003 13:07:18 -0500 Subject: Database connect / PDO References: <3FC248D1.3090603@ghaering.de> <030d01c3b2d9$4220a970$7401a8c0@voidmk9> <3FC3323A.3050209@egenix.com> Message-ID: <046d01c3b37e$f74fd000$7401a8c0@voidmk9> > mxODBC provides all .description values except display_size and > internal_size (and this is allowed by the DB API standard). These > two values are rarely of importance and if you absolutely need them > they can also be queried using the catalog methods the mxODBC exposes. Sorry, but I disagree - these two values can be very important. > You should note however, that some ODBC database drivers try > to be smart and "optimize" the return values that you see > in .description (the MyODBC driver is a prominent example). > While this is allowed by the ODBC standard, it is certainly > not good practice. > > As a result, the only true source of the schema information > are the catalog methods, e.g. .columns() available in mxODBC. > These also provide much more information than is available in > .description. I can understand where you are coming from in that the drivers themselves may make it impossible to provide full/accurate column data from a query. I'd wager you can't even automate calls to .column() because mxODBC doesn't necessarily know what table a column came from when results are fetched. I can only speak for myself, but it is quite frustrating to not get the information I need when I perform a query. Please realize that my message was not intended as a defacement or argument against mxODBC - I was simply warning the user of the pitfalls they may experience when using it with PDO. > mxODBC 2.0.x is 100% DB API 2.0 compliant. Then you should change your documentation :) "The mxODBC package provides a nearly 100% Python Database API 2.0 compliant interface " >From http://www.egenix.com/files/python/mxODBC.html > The only omissions are .nextset() and .callproc() which will be > available in mxODBC 2.1.0. Both are optional in the DB API 2.0 > specification. If this is why the documentation says nearly, then your interpretation of what 100% would mean is different from mine. 100% compliant would, in my mind, be supporting all required interfaces. I wouldn't think optional interfaces are needed for compliance, and supporting them, although good, wouldn't come into the percentage... unless you wanted to say you were 105% compliant :) .Just my two cents. ~Jon Franz NeuroKode Labs, LLC From mwh at python.net Mon Nov 24 09:56:41 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 24 Nov 2003 14:56:41 GMT Subject: Bug or Feature? References: <2259b0e2.0311240603.549943b3@posting.google.com> Message-ID: Stephan Diehl writes: > Although, the question was more along the line, if (in the light of the > principle of least surprise) this behaviour makes sense. > My private opinion would be, that the usefullness of builtin types as real > types would be much better, if they were safe under inheritance. The problem is that it's impossible for the int type to know about the requirements of your subclass' constructor. Explicit is better than implicit, and all that. For the example you posted, I don't see much of an advantage to inheriting from int. Cheers, mwh -- If a train station is a place where a train stops, what's a workstation? -- unknown (to me, at least) From bwglitch at hotpop.com Fri Nov 14 22:39:14 2003 From: bwglitch at hotpop.com (BW Glitch) Date: Fri, 14 Nov 2003 22:39:14 -0500 Subject: Python's simplicity philosophy In-Reply-To: References: <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: Douglas Alan wrote: > BW Glitch writes: > > >>>The mantra "there should be only one obvious way to do it" apparently >>>implies that one should remove powerful, general features like >>>reduce() from the language, and clutter it up instead with lots of >>>specific, tailored features like overloaded sum() and max(). > > >>That's not what _I_ understand. There's room for powerful features, >>but when these features gives trouble to the people who just want >>something done, then another approach should be taken. > > > If there's a problem with people not understaning how to sum numbers > with reduce(), then the problem is with the documentation, not with > reduce() and the documentation should be fixed. It is quite easy to > make this fix. Here it is: You are assuming way too much. Documentation is meant to clarify what a function does, not a tutorial on what a function is. That's why your CS101 professor should have taught you that the name of the function should state what the function does. sum() states clearly that it is meant to sum something (a connection is made with numbers, because that's what most people associate numbers). reduce(), OTOH, states nothing, it reduces. But what? Why should I care for a function that isn't clear? > FAQ > --- > Q: How do I sum a sequence of numbers? > > A: from operator import add > reduce(add, seq) > > Problem solved. > A: Guru. Q: How a user that reads the manual is called? ;) >>And I'm not talking about stupid people. I'm talking about the >>microbiolgist/chemist/physics/etc who is programming because of >>need. > > > If a microbiologist cannot understand the above, they have no business > being a microbiologist. Why should he? Because he could care less about a function called reduce()? Because he just want to do his job, regardless on how a CS expert does it? Because he didn't learned LISP as his first language? >I learned reduce() in high school, and it > didn't take me any longer than the 60 seconds I claim it will take > anyone with a modicum of intelligence. Please, get your fact straights. Do you know that people learn in different ways? Just because you learned something one way doesn't mean everyone else should learn it (and understand it) the same way you do. >>>If so, clearly this mantra is harmful, and will ultimately result >>>in Python becoming a bloated language filled up with "one obvious >>>way" to solve every particular idiom. This would be very bad, and >>>make it less like Python and more like Perl. > > >>You feel ok? Perl's mantra is "More Than One Way To Do It"... > > > If both the mantras cause a language to have general features > replaced with a larger number of specialized features that accomplish > less, then both mantras are bad. > Mantras are cute names for design decisions (I know, mantras doesn't mean that, but in these context). When designing something, certain compromises must be made. Guido van Rossum (GvR or BDFL) made some decisions early on and have stayed with Python ever since. Good or bad, we have to stick with the decisions. Why? Because each decision represents a solution from many to a single problem. If we start making exceptions to the decision, the decision should be rethought. But more importantly, if it works, don't fix it. Unless you go by the engineering mantra... >>>I can already see what's going to happen with sum(): Ultimately, >>>people will realize that they may want to perform more general >>>types of sums, using alternate addition operations. (For intance, >>>there may be a number of different ways that you might add together >>>vectors -- e.g, city block geometry vs. normal geometry. Or you >>>may want to add together numbers using modular arithmetic, without >>>worrying about overflowing into bignums.) So, a new feature will >>>be added to sum() to allow an alternate summing function to be >>>passed into sum(). Then reduce() will have effectively been put >>>back into the language, only its name will have been changed, and >>>its interface will have been changed so that everyone who has taken >>>CS-101 and knows off the top of their head what reduce() is and >>>does, won't easily be able to find it. > > >>I don't get you. There's a reason why special functions can be >>overloaded (__init__, __cmp__, etc.; I don't use others very >>often). That would allow for this kind of special >>treatments. Besides GvR would not accept your scenario. > > > There are often multiple different ways to add together the same data > types, and you wouldn't want to have to define a new class for each > way of adding. For instance, you wouldn't want to have to define a > new integer class to support modular arithmetic -- you just want to > use a different addition operation. Define a class then. What you are describing is a specific case which most people don't face in everyday problems. If you have a set of tools, try to use the best combination for the given tool. If all you have is a hammer, everything start looking like a nail. ;) If you have to program in Java, everything start looking like a class. >>Also, whytf do you mention so much CS101? > > > Because anyone who has studied CS, which should include a significant > percentage of programmers, will know instantly where to look for the > summing function if it is called reduce(), but they won't necessarily > know to look for sum(), since languages don't generally have a > function called sum(). And everyone else will not know to look for > either, so they might as well learn a more powerful concept in the > extra 30 seconds it will take them. False. Programmers come from many sources. Restraining yourself to CS people is bad enough. As Alex Martelli mentioned in another post of this thread, power should be demonstrable. It's quite amusing that no one has showed an example of the power of reduce() (by itself, not its side effects). [snip] >>IMHO, you think that the only people that should make software >>is a CS major. > > > Did I say that? You didn't. But I infere that from what you've said in this thread. >>>>>To me, there is never *one* obviously "right way" to do anything > > >>>>Never? I doubt this very much. When you want to add two numbers in a >>>>programming language, what's your first impulse? Most likely it is >>>>to write "a + b". > > >>>Or b + a. Perhaps we should prevent that, since that makes two >>>obviously right ways to do it! > > >>Even without any algebra, any kid can tell you that 1 + 2 is the same >>as 2 + 1. Replace 1 and 2 by a and b and you get the same result. > > > Yes, but they are still two *different* ways to to get to that result. > Starting with a and adding b to it, is not the same thing as starting > with b and adding a to it. It is only the commutative law of > arithmetic, as any good second grade student can tell you, that > guarantees that the result will be the same. On the other hand, not > all mathematical groups are albelian, and consequently, a + b != b + a > for all mathematical groups. > This might be the case IF we were talking about Matlab/Octave, which are languages design towards mathematics. This would be the case of concatenating strings ('Hello ' + 'World! ' <> 'World! ' + 'Hello '), but you should expect that to happen. >>>C'mon -- all reduce() is is a generalized sum or product. What's >>>there to think about? It's as intuitive as can be. And taught in >>>every CS curiculum. What more does one want out of a function? >>>|>oug > > >>It wasn't obvious for me until later. reduce() is more likely to be >>used for optimization. IIRC, some said that optimization is the root >>of all evil. > > > I don't know what you are getting at about "optimization". Reduce() > exists for notational convenience--i.e., for certain tasks it is easer > to read, write, and understand code written using reduce() than it > would be for the corresponding loop--and understanding it is no more > difficult than understanding that a summing function might let you > specify the addition operation that you'd like to use, since that's > all that reduce() is! Optimization was from somenone else in the thread whom I might misunderstood. It's still not obvious. You need to understand 1) whattf does reduce() do and how, 2) what does the function passed does and 3) what the array is about. >>Just because it's _obvious_ to you, it doesn't mean it's obvious to >>people who self taught programming. > > > It was obvious to me when I was self-taught and I taught myself APL in > high-school. It also seemed obvious enough to all the physicists who > used APL at the lab where I was allowed to hang out to teach myself > APL. Well, I learned TI-BASIC, C, C++ and then went on to learn Scheme, Prolog and Python. Most of these during the last 6 years. Have I missed something because I didn't know how to use reduce()? No. And more importantly, what is a real life scenario where I should go with reduce() instead of a loop? From what you've said, the only reason to use reduce() is to show mere mortals that I know how to use reduce(). Besides that, Martelli have pointed that it provides no advantage what so ever. And readability suffers because of the high abuse of this function. -- Andres Rosado -----BEGIN TF FAN CODE BLOCK----- G+++ G1 G2+ BW++++ MW++ BM+ Rid+ Arm-- FR+ FW- #3 D+ ADA N++ W OQP MUSH- BC- CN++ OM P75 -----END TF FAN CODE BLOCK----- A plague upon all their houses! -- Scourge (BW) From fulko at lina.dto.tudelft.nl Thu Nov 13 11:00:39 2003 From: fulko at lina.dto.tudelft.nl (Fulko van Westrenen) Date: Thu, 13 Nov 2003 16:00:39 +0000 (UTC) Subject: GLUT/Tk problem References: Message-ID: I forgot some details: All on Debian GNU/Linux: Woody (i386) Python 2.1 python-opengl 1.5.7 python2.1-tk 2.1.3 -- Fulko van Westrenen fwes at lina.dto.tudelft.nl From mfranklin1 at gatwick.westerngeco.slb.com Thu Nov 20 04:57:08 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 20 Nov 2003 09:57:08 +0000 Subject: TKinter Destroy Question In-Reply-To: References: Message-ID: <1069322228.1101.15.camel@m-franklin> On Thu, 2003-11-20 at 04:59, Rob wrote: > My first GUI so be gentle... > > When I start my program I call a class that runs the initial window. While > in this class if a certain button is pressed it calls a function outside the > class. This function then initially calls another function to > "root.destroy()". Basically I want the current window gone so the function I > just called can open it's own window. The problem I'm stuck with is that > once this function is done and I need to close the new window to go to the > next window i again call the function which performs the "root.destroy()". > When I try to call it a second time it tells me: > > TclError: can't invoke "destroy" command: application has been destroyed > When you destroy a window it's gone! so can't be destroyed again..... Without an example of what you are doing it's difficult to help but. You could call withdraw() method on root this will unmap it from the screen (but not destroy it) However why are you calling destroy on root twice? Perhaps you mean to call destroy on the old window when you create a new one (like a Wizard) e.g (untested...) root=Tk() def createNext(): nextWindow = Toplevel() nextWindow.title("Next Window") b = Button(root, text="Create Next Window", command=createNext) b.pack() root.withdraw() root.title("The Main Root Window") b = Button(root, text="Create Next Window", command=createNext) b.pack() root.mainloop() The problem here is you are not getting rid of the previous window when the Next button is pressed just root! Perhaps a better example would be:- class MyApplication(Tk): def __init__(self): Tk.__init__(self) self.title("Main Application Window") self.prevWindow = self self.windowCount = 1 b = Button(self, text="Next", command=self.nextWindow) b.pack() def nextWindow(self): window = Toplevel() self.windowCount = self.windowCount + 1 window.title("Next Window %d" %self.windowCount) b = Button(window, text="Next", command=self.nextWindow) b.pack() self.prevWindow.withdraw() self.prevWindow = window app = MyApplication() app.mainloop() However this will never finish! to close the whole application the app.quit() method must be called..... or if it's inside the class definition self.quit() Basically explain what you want with some example code and we can help Regards Martin -- Martin Franklin From amk at amk.ca Mon Nov 17 13:06:34 2003 From: amk at amk.ca (A.M. Kuchling) Date: Mon, 17 Nov 2003 12:06:34 -0600 Subject: Unit Testing Examples References: Message-ID: On 17 Nov 2003 09:10:32 -0800, Tom Verbeure wrote: > I'm not sure, though, at what level I have to write unit tests. It's > easy to write a tests that validates the consistency of a single node > of a graph, but the real complexity is, of course, in the interaction > of multiple nodes. Not too long ago I wrote a set of unit tests for a graph data type; unfortunately the code belongs to my employer and isn't open source, so you can't see a copy. What I did was: * Test basic things: create an empty graph and check that it has zero nodes and edges. Add a vertex and edge; remove the vertex and edge. In my case there are various accessors for .number_of_nodes() and .number_of_vertices(), so I checked that they went up by one. * Create a little graph, ~5 nodes, and test the BFS and DFS methods to see that they output nodes in a sensible order. Sancho, the testing framework I use, provides code coverage measurement, so I used that to find which lines of code weren't exercised by the test suite and added tests to cover more lines. It's usually difficult to exercise 100% of the code, because error cases can be difficult to provoke, especially if they represent an internal invariant being broken or an external resource such as a file or server not being available, and some trivial accessors aren't worth testing, so I'm usually happy with 70%-80% coverage as long as the complicated methods are completely or mostly covered. In my case I'm not bothering to run a very large graph as a test case, because the little graph exercises all of the relevant branches; I'm therefore betting that the code is OK for larger graphs, too. If a large graph demonstrates a bug someday, I would try to boil it down to a small test case and add this case to the test suite. If performance is important, you might consider adding a performance test: run an algorithm on a large graph and check that the running time is suitably fast. This might save you from making some change that doesn't affect correctness but results in a sizable performance regression. --amk From charlie at iwec.com Tue Nov 18 17:21:05 2003 From: charlie at iwec.com (Charlie Taylor) Date: Tue, 18 Nov 2003 14:21:05 -0800 Subject: Question: CGI script returning binary data from a POST form submit Message-ID: I'm having trouble passing binary data back from a python CGI script when a POST is used to send FORM data to a Windows Server. In this case, I've used all of the "import msvcrt" approaches and while it seems to work fine for images, passing back an excel spreadsheet ('Content-Type: application/vnd.ms-excel') is just not working unless I submit the FORM with a GET. Any hints would be greatly appreciated. From bokr at oz.net Sat Nov 29 21:50:51 2003 From: bokr at oz.net (Bengt Richter) Date: 30 Nov 2003 02:50:51 GMT Subject: Need some advice References: <2idisv45km5c64v2iqn7mj7pim3l1f4hpk@4ax.com> Message-ID: On Sun, 30 Nov 2003 00:19:53 GMT, Jeff Wagner wrote: >I am in the process of learning Python (obsessively so). I've been through a few tutorials and read >a Python book that was lent to me. I am now trying to put what I've learned to use by rewriting that >Numerology program I wrote years ago in VB. My bet is that the VB program will have some ugly things in it, and translating it in too fine detail will amount to programming Python in VB, which is perverse. I'd suggest you back off and draw a language-neutral flowchart of your old program, and mess with that until it's a simple and clear spec of what you want your program to do. At that point you should be able to implement it in python without carrying over VB-isms. OTOH, you may not be ready to take full advantage of Python, because there are a lot of things your don't know about it yet (don't feel bad -- we're all ignorant, just on different parts -- to paraphrase Will Rogers ;-) > >There are times I am totally stuck (for instance, I just had an idea to put the numerical values of >the alphabet and months of the year in a dictionary located in a function. Then, I can import the >dictionary I need from that function ... well, I'm getting import errors). Sounds like your concepts of modules and functions and importing still need adjustment ;-) > >So the question is this ... when I get stuck like this and seem to be banging into walls with >everything I try, is it better to continue trying different things or stop, take a break and go back If you need a hammer to do the immediate job right, is it better to keep whacking away with pliers and crescent wrenches and whatnot, or go back to the booklet that came with your almost-everything-in-the-box toolkit and look at the pictures showing uses for all the goodies? >to reading a tutorial or a Python book? Or is it better that after I've tried everything I can think >of, I just post the question here, get the answer and move forward? If you can't think of what to try, chances are you are best off getting up to speed on basics, so you know know what's available to you. Otherwise you are wondering how to build a Lego windmill with the first dozen pieces that come out of the box ;-) Good luck & have fun ;-) Regards, Bengt Richter From tjreedy at udel.edu Fri Nov 14 16:56:15 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Nov 2003 16:56:15 -0500 Subject: Too much builtins (was Re: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <653b7547.0311121826.65b6b2d4@posting.google.com> Message-ID: "Alex Martelli" wrote in message news:IT6tb.27445$hV.1005380 at news2.tin.it... > I'd rather put map/filter/reduce in a 'legacy' module -- warts and > all, e.g. map's horrible habit of None-padding shorter sequences, > EEK -- and have a designed-from-scratch functional module without > the warts. What a liberating thought. I sometimes forget that the only thing I am really stuck with when programming in Python is the core syntax (in the Ref Manual) and that I am free to wrap or replace anything else (in the Lib Manual). For a project I hope to start soon, I have been worried about how to work around or explain away the deficiencies of Python's of reduce(). Instead, I should just write the version I want for my purposes (especially since speed does not matter). So your voluminous writing on this has benefited at least one person. > Probably, yes. What functions, as opposed to types, do you > think should absolutely be in the builtins rather than in a separate > module, and (unless it's obvious) why? I have thought some about this also. Type objects could be put/left in types, but as constructors, they are too useful and basic not to have immediately available (unless builtins was reduced to nearly nothing). > Of course __import__ had better stay or we won't > be able to get anything imported, for example:-). Does it have to be in builtins for import statements to work? Direct use of __import__ seems relatively rare. > The attribute-related functions hasattr, getattr, > setattr, and delattr, seem very fundamental > (but I'd want the same status for the item-functions > currently over in operator), > as well as > (at least some of them -- delattr isn't -- but I do think that trying to > discriminate too finely would make things too hard to learn) > very frequently used in code. I had to re-lineate this to parse apart the three thoughts. A static frequency-of-use analysis for some large code collection would be interesting. I might write something eventually. > iter I group this with type constructor objects, even though not one itself > len unless made a method, keep in > pow [for the crucial 3-arguments case] very specialized and rarely used? move to math as pow3 > range (or some preferable variant that returns an iterator) how about iter(3), etc, currently an arg type error? think of 3 as the sentinal value. is not typing '0,' worth the wartiness of optional first arg? > and zip seem pretty fundamental agree except for pow Terry J. Reedy From dont_use at nowhere.com Sat Nov 29 19:49:38 2003 From: dont_use at nowhere.com (Glenn Reed) Date: Sun, 30 Nov 2003 13:49:38 +1300 Subject: ActiveState Python won't call module function. References: Message-ID: Yep, thanks, that worked Dennis Lee Bieber wrote in message news:docn91-it4.ln1 at beastie.ix.netcom.com... > thisClass = module1.module2() From max at cNvOiSsiPoAnMtech.com Mon Nov 10 11:01:57 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Mon, 10 Nov 2003 16:01:57 GMT Subject: Visual studio macros? Message-ID: Has anyone implemented some sorta an interface to use python to do visual studio macros? thanks- m From M.Boeren at guidance.nl Thu Nov 20 11:08:12 2003 From: M.Boeren at guidance.nl (Marc Boeren) Date: Thu, 20 Nov 2003 17:08:12 +0100 Subject: regular expression to extract text Message-ID: <7BE0F4A5D7AED2119B7500A0C94C58AC3D6E6A@DELLSERVER> Oops, just noted that the data was included below, and not in the given lines. Still, the split still works on both lines: > QEXZUO C26 H31 N1 O3 > 6.164 15.892 22.551 90.00 90.00 90.00 bit1 = line1.split(" ")[0] bit2 = [v for v in line1.split(" ")[1:] if v] bit3 = [v for v in line2.split(" ") if v] >>> bit1 'QEXZUO' >>> bit2 ['C26', 'H31', 'N1', 'O3'] >>> bit3 ['6.164', '15.892', '22.551', '90.00', '90.00', '90.00'] You can probably figure out the rest, like testing for a line0.startswith('----') as a separator and such? Cheerio, Marc. From dieter at handshake.de Thu Nov 20 14:41:38 2003 From: dieter at handshake.de (Dieter Maurer) Date: 20 Nov 2003 20:41:38 +0100 Subject: Multiple inheritance in Java/C# References: <8ef9bea6.0311182031.38034c10@posting.google.com> Message-ID: Thomas writes on Wed, 19 Nov 2003 15:55:28 +0100: > On Tue, 18 Nov 2003 20:31:35 -0800, Hung Jung Lu wrote: > ... lacking multiple inheritance ... > At least, the compiler tells you exactly what to do; in my > experience, this leads to very stable applications, even if the > application gets very large. (If you work with MI, it might happen > as well that you have to change many classes when you make changes > to the base classes.) I am a fan of inheritance. Only multiple inheritance provides mix in classes that let you construct your class out of components: you need persistence, add a "Persistence" mixin class; you need properties, add a "PropertyManager" class; you need indexing, add an "Indexible" class.... I build complex systems (multi-media database, E-Commerce platform, content management system) making extensive use of multiple inheritance (C++ and Python). I think, I do it extremely fast and efficient -- both for the initial implementation as well as for maintenance. Much more efficient than in a language without multiple inheritance (I have Java experience, as well). It is *very* rare in practice that a base class change affects derived classes, although it is easy to construct examples for this case. > I hope that C# uses it's chance of being a (IMHO) well designed > language, which can concentrate now on performance and stability > issues (and not on implementing new features). Python used to be > that way, but in the last time, it is developing too fast (IMHO). It would only be too fast, when it would introduce a high rate of errors. Nobody hinders you to stay behind... Dieter From stevena at neosynapse.net Mon Nov 10 04:51:23 2003 From: stevena at neosynapse.net (Steven D.Arnold) Date: Mon, 10 Nov 2003 04:51:23 -0500 Subject: submitting a jpeg to a web site? Message-ID: <71536A72-1363-11D8-84BD-000A95BA4396@neosynapse.net> Hi, I am curious how one might submit a JPEG to a web site using Python. I've tried urllib.urlopen, passing a dictionary that contained a key pointing to a string that contains the bytes of the JPEG, but that didn't apparently work. I did use the urllib.urlencode function on the dict before calling urlopen. It seems on the face of it that urlopen is not the ordained way to do what I want here. The

tag of the page I'm submitting to looks like this: The enctype seems to suggest I need some kind of MIME-like capability to do this right. Does anyone know what I should be doing to make this work? Thanks in advance, steve From fs111 at linuxmail.org Thu Nov 13 15:07:35 2003 From: fs111 at linuxmail.org (=?ISO-8859-15?Q?Andr=E9?= Kelpe) Date: Thu, 13 Nov 2003 21:07:35 +0100 Subject: XLM and XSLT References: <3FB3B061.B72526CA@mortauxspams.bz> Message-ID: Olivier Hoarau wrote: > Hello, Hi! > I would like to create a file from a xml file with a xslt transformation > in a python program. > Is there someone who can give me some examples to do that ? something > like this > > import libxslt > import libxml2 > > xsl=parseStylesheetFile(xsl file) > xml=parseFile(xml file) > result = applyStylesheet(xls,xml) > saveResultToFilename(result,outfile) Looks like lib(xml/xslt)-python interfacefrom http://xmlsoft.org/. Maybe this is the right choice for you. For a little overview take a look at this page: http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/python-xslt > Olivier HTH Andr? From stephan.diehl at gmx.net Mon Nov 24 09:44:59 2003 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Mon, 24 Nov 2003 15:44:59 +0100 Subject: Bug or Feature? References: <2259b0e2.0311240603.549943b3@posting.google.com> Message-ID: Michele Simionato wrote: > Stephan Diehl wrote in message > news:... >> I was playing around with defining new types and have seen the >> following behaviour: >> >> Python 2.3.1 >> ============ >> >> >>> class Int(int):pass >> ... >> >>> a = Int(7) >> >>> b = Int(8) >> >>> c = a + b >> >>> type(c) >> >> >> Basicly: Int is not closed under it's defined operations. :-( >> > > You want my "innermethods" module. Originally I wrote it as a recipe > for the cookbook, but then I forgot to post it ;) > Yes, thanks, this is most helpfull. Although, the question was more along the line, if (in the light of the principle of least surprise) this behaviour makes sense. My private opinion would be, that the usefullness of builtin types as real types would be much better, if they were safe under inheritance. From aleax at aleax.it Tue Nov 11 06:10:38 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 11 Nov 2003 11:10:38 GMT Subject: Python's simplicity philosophy (was Re: reduce()--what is it good for?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: Robin Becker wrote: ... > This whole thread is reminiscent of vi vs emacs or an os war or similar. > It's a pity that people with a preferred style should be so dogmatic > that they want to remove language features to prevent others using them. Python's essence is simplicity and uniformity. Having extra features in the language and built-ins runs directly counter to that. > The whole 'only one way to do it' concept is almost certainly wrong. Bingo! You disagree with the keystone of Python's philosophy. Every other disagreement, quite consequently, follows from this one. The world is *chock full* of languages designed with the philosophy of "the more, the merrier". Why can't you let us have just _*ONE*_ higher-level language designed with full appreciation for "the spirit of C" (as per the C standard's Rationale) in its key principles: """ (c) Keep the language small and simple. (d) Provide only one way to do an operation. """ Maybe "the spirit of C" is as wrong as you claim it is. Personally, I _cherish_ it, and in Python I found a language that cherishes it just as much, while working at a much higher semantic level and thus affording me vastly higher productivity. I will not stand idly by, and let you or anybody else attack its foundations and thus try to destroy its key strengths, without a fight. > There should be maximal freedom to express algorithms. As others have Want "maximal freedom to express algorithms"? You can choose among a BAZILLION languages designed according to your philosophy -- even sticking just to higher-level languages with dynamic typing and generally infix/algoloid syntax, Perl is the obvious example, and if you just can't stand its core syntax, in full respect of this "maximal freedom" principle, you can of course change it, too -- see http://www.csse.monash.edu.au/~damian/papers/HTML/Perligata.html and revel in that _truly_ maximal freedom. Or, for a language that's somewhat in-between, but still philosophically accepts the "maximal freedom" tenet for which you crave, try Ruby -- if I _did_ want such freedom, then Ruby is what I'd most likely use. But can't you let us have *ONE* language that's designed according to the concept you consider "almost certainly wrong"?! Why do YOU use this language, even while you condemn its foundation and try to undermine them, rather than using any one of the myriad that already DO follow your philosophy?! Trying to make Python into (e.g.) a Ruby with slightly different cosmetics and "fine points" is truly absurd: if you want Ruby, you know where to find it. Let Python stay Python, and leave those of us who find ourselves best served by its design principles in peace! Alex From tjreedy at udel.edu Tue Nov 4 17:16:07 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 4 Nov 2003 17:16:07 -0500 Subject: Any suggestions to speed this up References: <92c59a2c.0311041209.2e89e054@posting.google.com> Message-ID: <3tGdnQIbXsa0uDWiRVn-iQ@comcast.com> "MetalOne" wrote in message news:92c59a2c.0311041209.2e89e054 at posting.google.com... > Virtually all the time is consumed expanding the 1 byte of grayscale > data into 3 bytes to get RGB. For example, V=128 is converted to > R=128,G=128,B=128. I would look at PIL to see it it had a builtin function to do this and then Numerical Python. TJR From arnout.standaert at n-o-s-p-a-m.cit.kuleuven.ac.be Fri Nov 21 04:04:37 2003 From: arnout.standaert at n-o-s-p-a-m.cit.kuleuven.ac.be (Wald) Date: Fri, 21 Nov 2003 09:04:37 +0000 (UTC) Subject: best Wx editor References: Message-ID: Derrick 'dman' Hudson wrote: > For coding, UNIX is the best :-). (vim as editor, cvs for > source control, python for execution, ls/cp/mv/grep/ for > file management, you get the picture) Not that I'm an anti-Unix/Linux person, but the tools you mention are equally available for other platforms, including Windows. VIM: http://www.vim.org/download.php#pc CVS: http://www.cvsnt.org/ http://www.tortoisecvs.org/ http://www.wincvs.org/ Python: http://www.python.org/ http://www.activestate.com/Products/ActivePython/ ls/cp/mv/grep/... http://www.cygwin.org/ Well, anyway, just wanted to point that out. Other than that, Unix/Linux is a bloody great platform. I'm in the process of learning to use it (Debian) and I love its transparency. If it wasn't for specific software, I would have a single-boot Linux system. Regards, Wald From jjl at pobox.com Tue Nov 4 20:53:47 2003 From: jjl at pobox.com (John J. Lee) Date: 05 Nov 2003 01:53:47 +0000 Subject: Selling Python Software References: <8765i1d2jb.fsf@pobox.com> Message-ID: <878ymvzil0.fsf@pobox.com> bokr at oz.net (Bengt Richter) writes: > On Tue, 04 Nov 2003 09:03:51 GMT, "Andrew Dalke" wrote: > > >Bengt Richter: > >> OTOH, we are getting to the point where rather big functionality can be put > >> on a chip or tamper-proof-by-anyone-but-a-TLA-group module. I.e., visualize > >> the effect of CPUs' having secret-to-everyone private keys, along with > >> public keys, > > > >Actually, we aren't. There have been various ways to pull data of > >of a smart card (I recall readings some on RISKS, but the hits I > >found are about 5+ years old). In circuit emulators get cheaper and > >faster, just like the chips themselves. And when in doubt, you can > >buy or even build your own STM pretty cheap -- in hobbiest range > >even (a few thousand dollars). > > Even if you knew exactly where on a chip to look, and it wasn't (Which knowledge is bound to become available -- I don't think any leak is required.) > engineered to have the key self-destruct when exposed, what would Exposed to what? > you do with the key? You'd have the binary image of an executable > meant to execute in the secret-room processing core. How would you No, you already have that -- it's on your hard drive (the current scheme is only about the processor & associated gubbins, if I read Ross Anderson's page right). > make it available to anyone else? [...] Copy it. I think the idea is something like this (got from Ross Anderson's TC FAQ). The processor makes sure that a single process can only see it's own memory space. The processor also has a private key, and knows how to take an md5 sum (or whatever), sign it with the key, and send that off to the software author's server along with your identity. The server checks that it was signed with your processor's private key, and that you've paid for the software, and a sends a signed message back that tells your machine "OK". Obviously (hmm... I should hesitate to use that word about anything related to security!), if you have your machine's private key, you can play "man-in-the-middle". Presumably the next phase is to make hard drives, etc. 'trusted'. I couldn't find much useful stuff on this on the web. Anybody have any good links to overviews of this? John From pekko.piirola at helsinki.fi Wed Nov 26 04:29:31 2003 From: pekko.piirola at helsinki.fi (Pekko Piirola) Date: 26 Nov 2003 09:29:31 GMT Subject: Animations with matplotlib? Message-ID: I'm trying to make an animation with matplotlib. The problem: whenever I try to rescale or move the plot with the buttons of plotting window, the animation stops. My system is Debian Woody and python-2.3 with matplotlib-0.32. I'm a total newbie with matplotlib (I installed it yesterday), so what am I doing wrong? An example code below: ------------------------------------------ #!/usr/bin/env python2.3 import matplotlib.matlab import gtk import Numeric fig = matplotlib.matlab.figure(1) ind = Numeric.arange(60) x_tmp=[] for i in range(100): x_tmp.append(Numeric.sin((ind+i)*Numeric.pi/15.0)) X=Numeric.array(x_tmp) lines = matplotlib.matlab.plot(X[:,0],'o') def updatefig(*args): updatefig.count += 1 if updatefig.count>59: updatefig.count=0 lines[0].set_data(ind,X[:,updatefig.count]) fig.draw() return gtk.TRUE updatefig.count=-1 gtk.timeout_add(200,updatefig) matplotlib.matlab.show() ------------------------------------------------- -- Best regards, Pekko From radam2 at tampabay.rr.com Tue Nov 18 02:34:41 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Tue, 18 Nov 2003 07:34:41 GMT Subject: True inconsistency in Python References: <3FB8847F.6CB1BECA@alcyone.com> <3FB92086.9CBD0761@alcyone.com> <8qhirvgi2sf5l3vkfocq65mcb94c6pbb9s@4ax.com> Message-ID: <7rhjrvgefdpfkm15divsor9e3iktl0falh@4ax.com> On Mon, 17 Nov 2003 23:40:52 -0500, "Terry Reedy" wrote: > >"Ron Adam" wrote in message >news:8qhirvgi2sf5l3vkfocq65mcb94c6pbb9s at 4ax.com... >> No, this one point is not the only reason, I made the example a >> little farfetched to demonstrate a concept I think is a valid reason >> to have 'True' and 'False' as Constants. > >The developers agree and would make them so now if it were not for >backward compatibility needs. They probably will make them so in the >future. Currently, reassigning None can get you a Warning. That would be good. >> Their actual internal >> values shouldn't be relevant or depended on. > >When the bool type was added, a few people argued for a pure bool type >with no relation to anything else. However, in Python, 'practicality >beats purity'. Having True/False == 1/0 now and forever has practical >uses. Good also. >> In python you can change the value of True, or set True to point to >> something different. > >Yes, you are currently allowed to stab yourself in the back (but even >this will probably change in the future). Don't do it. > I agree, it's good that it may change. >> For example you can do this. >> >>> True = False >> Now all bets are off.... > >Ditto. > >> To be sure that True is True and False is >> False, we need to put in explicit definitions into our programs. > >In 2.2.2+, you only need to not change them and to not work with a >psycopath. Many people are starting to learn programming with python as their first computer language. I wouldn't refer to them as a psychopath. They may one day write programs that save peoples lives. They have to start someplace. Many people using python will not be professional programmers but enthusiast and hobbiests, or web page programmers, or ..... in other words, a very large and diverse group. >... >> The above is much less implausible. Do you agree? > >Yes, it is more plausible that you shoot yourself in the feet than >that Guido and the whole Python development community go bonkers. I >strongly suspect that PyChecker can check for assignments to True and >False (along with about a hundred other things). Get it and use it. > >Terry J. Reedy > I'm not sure what your point is here, but using PyChecker sounds like a good suggestion. _Ronald Adam From http Wed Nov 26 20:16:04 2003 From: http (Paul Rubin) Date: 26 Nov 2003 17:16:04 -0800 Subject: mbox despamming script Message-ID: <7x1xruehm3.fsf_-_@ruckus.brouhaha.com> I was surprised there was no obvious way with spamassassin (maybe I shoulda looked at spambayes) to split an existing mbox file into its spam and non-spam messages. So I wrote one. It's pretty slow, taking around 1.5 seconds per message on a 2 ghz Athlon, making me wonder how serious ISP's getting thousands of incoming messages per hour can run anything like spamassassin on all of them. But for my purposes it's ok. Comments and improvements are welcome. ================================================================ #!/usr/bin/python # Spam filter for mbox files. Reads mailfile and makes two new # files, mailfile.spam and mailfile.ham, containing the spam and non-spam # messages from mailfile as determined by piping through spamc. # Copyright 2003 Paul Rubin # Copying permission: GNU General Public License ver. 2, import mailbox,os,sys from time import time def mktemp(): import sha,os,time d = sha.new("spam:%s,%s"%(os.getpid(),time.time())).hexdigest() return "spam%s.temp"% d[:10] tempfilename = mktemp() def main(): print sys.argv if len(sys.argv) > 1: filename = sys.argv[1] else: print "Usage: spam.py mboxfile" print "marking up", filename mailfile = open(filename, 'r') ham = open(filename + ".ham", 'w') spam = open(filename + ".spam", 'w') mbox = mailbox.UnixMailbox(mailfile) i = 0 while 1: i += 1 m1 = mailfile.tell() msg = mbox.next() if not msg: break body = msg.fp.read() envelope = env_header(mailfile, m1) print "%5d"%i, m1, mailfile.tell(), msg.startofbody, len(body), is_spam, txt = spam_filter (envelope, msg, body) print ['HAM','SPAM'][is_spam] if is_spam: spam.write(txt) else: ham.write(txt) def spam_filter(envelope, msg, body): txt = envelope + ''.join(msg.headers) + '\n' + body out = os.popen("spamc > %s"% tempfilename, "w") out.write(txt) out.close() t = mailbox.UnixMailbox(open(tempfilename)) spam_level = len(t.next().get('X-Spam-Level', '')) txt = open(tempfilename).read() return (spam_level >= 5, txt) def env_header(fp, pos): t = fp.tell() fp.seek(pos) e = fp.readline() fp.seek(t) return e try: t=time() main() dt = time()-t print "elapsed: %d min %d sec"% divmod(int(dt), 60) finally: os.unlink(tempfilename) From duane at franz.com Sun Nov 2 10:33:11 2003 From: duane at franz.com (Duane Rettig) Date: 02 Nov 2003 07:33:11 -0800 Subject: Paging Mr. Rettig [ws Re: Explanation of macros; Haskell macros] References: <87brs2tjut.fsf@memetrics.com> <4wuaj84x5.fsf@franz.com> <3FA5027D.5FDFB4AB@setf.de> Message-ID: <4r80q3hvs.fsf@franz.com> james anderson writes: > Marcin 'Qrczak' Kowalczyk wrote: > > > > On Sun, 02 Nov 2003 02:01:58 -0800, Duane Rettig wrote: > > > > > With this much openness, it doesn't seem unreasonable > > > to expect a debugger to be able to use such information to make macros > > > and the forms they expand into completely debuggable and steppable at > > > any desired level. > > > > Does any debugger do this? > > ? you mean like this? wrt evaluating > > (defun testf (x) > (dotimes (i x) > (print i))) > > (step (testf 2)) I've reproduced the whole code below so that readers can see it when they contemplate this comment and a question (I have no time now, but I'll explain tonight if nobody gets it, although it should be easy): James did not say what lisp he was using, but presumably it is a Common Lisp. The following example was obviously not compiled. Can you explain why? > ==> > > (testf 2) > (block testf (dotimes (i x) (print i))) > (dotimes (i x) (print i)) > x = 2 > (block nil (if (ccl::int>0-p #:g25) (tagbody #:g24 (print i) (locally # > #) (unless # #))) nil) > (if (ccl::int>0-p #:g25) (tagbody #:g24 (print i) (locally (declare #) > (setq i #)) (unless (eql i #:g25) (go #:g24)))) > (ccl::int>0-p #:g25) > #:g25 = 2 > t > (tagbody #:g24 (print i) (locally (declare (ccl::settable i)) (setq > i (1+ i))) (unless (eql i #:g25) (go #:g24))) > (print i) > i = 0 > 0 > (locally (declare (ccl::settable i)) (setq i (1+ i))) > (setq i (1+ i)) > (1+ i) > i = 0 > 1 > 1 > 1 > (unless (eql i #:g25) (go #:g24)) > (not (eql i #:g25)) > (eql i #:g25) > i = 1 > #:g25 = 2 > nil > t > (progn (go #:g24)) > (go #:g24) > (print i) > i = 1 > 1 > (locally (declare (ccl::settable i)) (setq i (1+ i))) > (setq i (1+ i)) > (1+ i) > i = 1 > 2 > 2 > 2 > (unless (eql i #:g25) (go #:g24)) > (not (eql i #:g25)) > (eql i #:g25) > i = 2 > #:g25 = 2 > t > nil > nil > nil > nil > nil > nil > nil > nil > > > v/s > > (testf 2) > (block testf (dotimes (i x) (print i))) > (dotimes (i x) (print i)) > nil > nil > nil > > > depending on whether one stepped into or over the macro form? -- Duane Rettig duane at franz.com Franz Inc. http://www.franz.com/ 555 12th St., Suite 1450 http://www.555citycenter.com/ Oakland, Ca. 94607 Phone: (510) 452-2000; Fax: (510) 452-0182 From jsbenson at bensonsystems.com Tue Nov 25 20:38:12 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Tue, 25 Nov 2003 17:38:12 -0800 Subject: a position on Treestructure in SQL and request for comments on same Message-ID: <017901c3b3bd$f4b80f80$4a09500a@jsbwxp3> I checked out the http://c2.com/cgi/wiki?TreeInSql link and found the following: Motivation There are many applications where data is structured as trees. This data needs to be stored in a database. This data needs to be searched efficiently. A join operation (set intersection) needs to be efficient. Forces a.. Loading an entire tree into memory before searching is not scalable. b.. Relational tables are two dimensional, so trees must be expressed using relational linkage. c.. Fast searching at the database relies on early subsetting against some index. (end quote) This whole "store tree nodes as individual records in an RDBMS" sounds doomed to irrelevance in the near future because: 1) Loading an entire file into memory wasn't scalable, but it's sure looking that way now, and specific file <--> string idioms in Python and the availability of scads of cheap RAM encourage it more with each passing year. Analogously, maintaining an entire pointery data structure in memory and dispensing with access through RDBMS key blocks in favor of simple pointer traversal is cheaper and cheaper as time goes by. Large (64-bit offset) files and 64-bit OSes are waiting in the wings, too. 2) Virtual memory will also help you in your efforts to cram ever larger data structures into memory. If you want to persist them easily, they could be implemented in memory-mapped files with lazy read semantics (i.e. file portions are only retrieved from disk on demand). 3) Perhaps a felicitous partition of functionality would be appropriate, such as in-memory tree data structures with leaf node data storage delegated to an RDBMS or hash table on disk. I feel a little like a devil's advocate here, because in the past I have also advocated shoehorning tree-structured stuff into an ISAM file, similar to the tree-to-RDBMS idea posted here earlier, and, like a good code monkey, I was excited about doing it. But it seems now that the technological drivers are rendering this approach outmoded. Although there are limitations of having stuff in-memory (like, how do you provide scalable access to it from other processors and checkpoint it to disk), it's interesting to note that your average RDBMS has already adopted the approach outlined in 3): key blocks tend to get cached in memory anyway, since they're on the critical path to the data block leaf nodes, which can also get cached too. Whoops! Sounds like your RDBMS is already a mugwump sort of tree, with it's mug in-memory and it's wump on disk. So it sound's like there is really a continuum of mug/wump distribution, and that the wump would wither away were it not necessary for persisting data structures. Comments, please: am I missing anything important here? From hungjunglu at yahoo.com Mon Nov 24 18:27:09 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 24 Nov 2003 15:27:09 -0800 Subject: code blocks in Python References: <8ef9bea6.0311221215.804bdb3@posting.google.com> <8ef9bea6.0311221913.427cb53e@posting.google.com> <8ef9bea6.0311231634.1ca497ac@posting.google.com> <8ef9bea6.0311232220.4e308a4c@posting.google.com> <8ef9bea6.0311241105.e53c47d@posting.google.com> Message-ID: <8ef9bea6.0311241527.61a27b6c@posting.google.com> Skip Montanaro wrote in message news:... > > You should be able to express the desired semantics of your extension to the > language without requiring us to execute code. I have yet to see an > explanation of why you want > > def c: > x += 1 > > added to the language. I can guess that it binds c to a "code block". How > do I use it? The above is illegal syntax in Python today. Am I supposed to > guess how to use it? That has nothing to do with compile(). Am I supposed > to run it with the exec statement or do you envision me just inserting > > c > > into my code? Skip: being you a Python old timer, I think you are just grumbling for no good reason. :) Before anything else, people are already jumping into implementation details, optimization, syntax, etc. I am barely starting to look at whether there have been previous existing efforts, and if so, why were they discarded, etc. > > What exactly have you given me that I couldn't have done with > > x = 1 > x += 1 > I come back again to repeat it one more time: the compile() function already exists and works in Python. Before you do your posting, please think about the compile() function first. (Do I need to say it one more time? I don't mind.) So, let me try to pretend I am Skip Montanaro, and follow through with the process. (a) OK, I have been told that compile() function exists in Python. (b) I am complaining that I can do x = 1 x += 1 without resorting to codeblocks. So there is no need for codeblocks. Codeblocks are useless, good for nothing. (c) OK, one more time, I have been told that compile() function exists and works in Python. Everytime I talk about codeblocks, I need to think about the compile() function first. (d) Aha! So by analogy, there is no need for the compile() function in Python. I get it now! (e) Wait a second... searching through the Python newsgroup archive I find hundreds if not thousands of messages related to the usage of the compile() function. So the compile() function can't be useless. Either thousands of Python users are wrong, or I have not been careful in my thinking process. (f) Hmm... let me look at those messages and try to understand how people are using the compile() function. (g) Aha! The compile() function is not useless. I know how to use it, now. (h) Aha! Codeblocks are not useless. (i) Aha! So codeblocks are analogous to the compile() function, the only difference is that codeblocks are compiled at compile time. The compile function compiles the code string at runtime. (j) Wait, I think Hung Jung has said everything before in his messages. Bingo! Now you get it. Hung Jung From gerrit at nl.linux.org Fri Nov 28 05:03:34 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Fri, 28 Nov 2003 11:03:34 +0100 Subject: python-dev Summary for 2003-10-16 through 2003-11-15 In-Reply-To: <3FC65193.7000300@ocf.berkeley.edu> References: <3FC65193.7000300@ocf.berkeley.edu> Message-ID: <20031128100334.GC2426@nl.linux.org> Brett C. wrote: > This is the twenty-eighth and twenty-ninth summaries written by Brett > Cannon (does anyone even read this?). I do! Keep up the good work! yours, Gerrit. -- 127. If any one "point the finger" (slander) at a sister of a god or the wife of any one, and can not prove it, this man shall be taken before the judges and his brow shall be marked. (by cutting the skin, or perhaps hair.) -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From peter at engcorp.com Sun Nov 2 17:39:03 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 02 Nov 2003 17:39:03 -0500 Subject: Puzzling form/cgi problem References: Message-ID: <3FA58787.F9220A5C@engcorp.com> Dfenestr8 wrote: > > I have a problem with a subroutine in a cgi script that's supposed to > return the byte location at the end of a file, which the script then > stores as a hidden input on a web form. > > Unfortunately, even though it works fine in the python shell, in the > cgi-script it always returns "0". That's no use to me at all. Not sure about a fix for the seek() problem, by can't you just use os.stat() to get the size of the file? -Peter From mis6 at pitt.edu Fri Nov 14 12:06:37 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 14 Nov 2003 09:06:37 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <2259b0e2.0311140033.4e3ca8ea@posting.google.com> Message-ID: <2259b0e2.0311140906.87b7839@posting.google.com> "Brandon J. Van Every" wrote in message news:... > > True... but in most cases we're making an Existential choice about our > willingness to control. We are not in fact helpless. Such is the case with > Python. If you want to actually do something about marketing Python "like > the big boys do," I encourage you to join the marketing-python forum. > http://pythonology.org/mailman/listinfo/marketing-python Unfortunately, I am not a kinda of marketing person ... Anyway, I must congratulate you for the Python logo: it is ways better than any other Python logo I have seen (so far) and it looks really professional. The font is so and so, but the stylized snake is perfect, and very original. > > We can only wait and see (as in that old chinese said ...) > > Chinese philosophies, at least as received by Westerners looking for > alternatives to their high stress culture, often have the flaw of being too > Yin. The Tao is balance, not passivity. Yes, but the idea I had in mind was something like "relax, we are not in war against Java or C# or anything else, let us wait for a bit before complaining about Python dead". OTOH, if people think that Python is an endangered species and want to start a promotional campaign to save it, I am certainly not opposed. Anyway, one must be realistic and do not expect that Python will replace Java any soon, just because the way the world is. So, I do promote Python, but the pacific way ;) Michele P.S. in Italian "pacific" means "peaceful" but also, referred to a person, somebody with a slow pace, and/or somebody who doesn't worry too much (like me ;) not sure if the English word has the same connotation, but anyway I meant that there is no hurry, as I don't see any sign of Python disappearing soon, I see just the opposite actually ;) From reply.in.the.newsgroup at my.address.is.invalid Thu Nov 27 18:47:10 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 28 Nov 2003 00:47:10 +0100 Subject: Word2000 to wxPython conversion.... References: <823dsvsklcdtharcqkj5a3aoci4f181t1k@4ax.com> Message-ID: Nikolai Kirsebom: >I've made a small utility which converts the content of a Microsoft >Word2000 document to wxPython code. Wow! I have lots of Word documents I'd like to mail to you :-) -- Ren? Pijlman From nc-agirbane at netcologne.de Wed Nov 12 05:00:02 2003 From: nc-agirbane at netcologne.de (Necati Agirbas) Date: Wed, 12 Nov 2003 11:00:02 +0100 Subject: guten tag Message-ID: Betreff: SCHULBESCHEINGUNG F?r Frau DERYA AGIRBAS, wohnhaft novalissstr.42 in 51147 K?ln geb.26.05.1981 (k?ln) Lehrgangsbezeichnung: T193! Guten Tag auch den Damen und Herren, Versuche sied Heute Morgen Sie in der Schule telefonisch zuerreichen, aber Ihre telefon anlage wird ja installiert! Mein name ist hanife agirbas, schreibe Sie aus folgendem grund an meine schwester DERYA AGIRBAS hat ihre schule bis zu den Sommer ferien dieses Jahres 2003 besucht, und wir ben?tigen eine Schul -Bescheinigung f?r das Jahr 2002. Wenn Sie es f?r heute fertig stellen k?nnten w?hren wir ihnen sehr dankbar. bitte um Ihre r?ckantwort, mfg hanife agirbas From mis6 at pitt.edu Sat Nov 15 02:13:57 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 14 Nov 2003 23:13:57 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> <2u1tb.25127$hV.934365@news2.tin.it> Message-ID: <2259b0e2.0311142313.62a73078@posting.google.com> "Brandon J. Van Every" wrote in message news:... > Maxim Khesin wrote: > > Or perhaps Pythonistas are smarter than other people :) and buy their > > books online. > > That wouldn't make me smarter. I live 5 blocks away from Barnes & Noble > downtown. Lotsa other people are similarly well situatated according to > where they work. I lived < 50 meters from Barnes & Noble, still I bought my Python books from Amazon.com. For instance "Python in a Nutshell" was available on-line before than in the libraries, with 30% discount and free shipping. It arrived in a couple of days. Michele From ian at emit.demon.co.ukx Mon Nov 3 07:23:39 2003 From: ian at emit.demon.co.ukx (Ian McConnell) Date: Mon, 03 Nov 2003 12:23:39 +0000 Subject: Running a python farm References: <877k2qrc0a.fsf@emit.demon.co.uk> Message-ID: <87wuahod2s.fsf@emit.demon.co.uk> Ian McConnell writes: > What's the pythonic way of sending out a set of requests in parallel? > > My program throws an image at the server and then waits for the result. I'm > currently using this bit of socket code to send an image to server on > another machine. Once again, thanks to all those who replied. In the end I went with the select and poll method as I only have a small number of machines to run my code on and this method fitted in easiest with my existing program. Actually, it also turns out that my code isn't quite as parallelised as I thought it was and having results coming back in a different order confused some of the later bookkeeping, so I've also done a version (pclient2) that maintains the image order. Even with this limitation, I do get a good speed up. I'm sure this code can be made more efficient and is probably fairly easy to deadlock, but it works for me. import sys import socket import cPickle import select import string class Machine: def __init__(self, hostname): colon = string.rfind(hostname, ':') if colon >= 0: self.host = hostname[0:colon] self.port = int(hostname[colon+1:]) else: self.host = hostname self.port = 10000 # default port # Should check for host being alive and possible endian issues def connect(self): return (self.host, self.port) def __repr__(self): return "%s:%d" % (self.host, self.port) class Client: def __init__(self, host, array, opts): print 'NEW CLIENT', host, array.shape sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host sock.connect(host.connect()) sent = sock.sendall(cPickle.dumps((array, opts), 0)) sock.shutdown(1) self.rfile = sock.makefile('rb') def result(self): r,w,e = select.select([self.rfile], [], [], 1) if not r: return None else: return cPickle.loads(self.rfile.read()) def __repr__(self): return "%s" % self.host def name(self): return self.host def pclient(hostnames, all_images, opts): """ hostnames is a list of machine names (as host:port) that are willing to process data all_image is a list of images opts is a dictionary of processing options. """ client_list = [] result = [] # assign images to hosts hosts = [] while len(hostnames) > 0: host = Machine(hostnames.pop()) if host is not None: hosts.append(host) for host in hosts: client_list.append(Client(host, all_images.pop(), opts)) # process while client_list: print len(client_list), 'clients busy' next_client_list = [] for o in client_list: res = o.result() if res is not None: result.append(res) if all_images: # if we have images assign to completed host next_client_list.append(Client(o.host, all_images.pop(), opts)) else: next_client_list.append(o) client_list = next_client_list return result # # # # Extra code to ensure results return in same order as submitted. # # # class fifo: """Simple implementation of a First-In-First-Out structure.""" def __init__(self): self.in_stack = [] def push(self, obj): self.in_stack.append(obj) # print 'fifo push', self.in_stack def pop(self): return self.in_stack.pop(0) def __repr__(self): return str(self.in_stack) def __len__(self): return len(self.in_stack) def head(self): return self.in_stack[0] class Workers: def __init__(self, hosts, opts): self.idle = hosts self.busy = fifo() self.opts = opts def free(self): return len(self.idle) def newjob(self, array): if array == [] or array == None: # Delete idle list self.idle = [] return host = self.idle.pop() self.busy.push(Client(host, array, self.opts)) def poll(self): if len(self.busy) == 0: return None host = self.busy.head() return host.result() def done(self): if len(self.busy) == 0: return None res = None while res == None: res = self.poll() host = self.busy.pop() self.idle.append(host.name()) print ' idle:', self.idle, ' busy:', self.busy return res def pclient2(hostnames, all_images, opts): """ hostnames is a list of machine names (as host:port) that are willing to process data all_image is a list of images opts is a dictionary of processing options. Returns results in same order as input. """ result = [] hosts = [] while len(hostnames) > 0: host = Machine(hostnames.pop()) if host is not None: hosts.append(host) workers = Workers(hosts, opts) while workers.free() > 0: workers.newjob(all_images.pop()) print 'PCLIENT2 idle:', workers.idle, ' busy:', workers.busy while 1: res = workers.done() if res == None: break result.append(res) # Queue up another job if there are images left to process if all_images: workers.newjob(all_images.pop()) return result -- "Thinks: I can't think of a thinks. End of thinks routine": Blue Bottle ** Aunty Spam says: Remove the trailing x from the To: field to reply ** From qrczak at knm.org.pl Sun Nov 2 06:00:35 2003 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Sun, 02 Nov 2003 12:00:35 +0100 Subject: Paging Mr. Rettig [ws Re: Explanation of macros; Haskell macros] References: <87brs2tjut.fsf@memetrics.com> <4wuaj84x5.fsf@franz.com> Message-ID: On Sun, 02 Nov 2003 02:01:58 -0800, Duane Rettig wrote: > With this much openness, it doesn't seem unreasonable > to expect a debugger to be able to use such information to make macros > and the forms they expand into completely debuggable and steppable at > any desired level. Does any debugger do this? -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From guettli at thomas-guettler.de Mon Nov 17 09:58:25 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 17 Nov 2003 15:58:25 +0100 Subject: html renderer References: <2259b0e2.0311160610.1bc0a636@posting.google.com> Message-ID: Am Sun, 16 Nov 2003 06:10:04 -0800 schrieb Michele Simionato: > I am looking for a textual html renderer (such as lynx) to be > called from a Python program. The only needed functionality is > the following: passing to it a string it should show the html file at > the first match of the string (it does not seem obvious to do it with > lynx, please correct me if I am wrong). Essentially, I want to be able to > to browse rapidly over a bunch of html files. Fancy graphics is not > important, easy of use is very important. Portable solutions are > better, but a Linux only solution would be good enough. Hi, may be this helps: # untested fd=os.popen("lynx -dump foo.html") content=fd.read() fd.close() idx=content.find("yourtext") print content[idx-20:idx+20] thomas From rudy.schockaert at pandoraSTOPSPAM.be Thu Nov 6 11:20:39 2003 From: rudy.schockaert at pandoraSTOPSPAM.be (Rudy Schockaert) Date: Thu, 06 Nov 2003 16:20:39 GMT Subject: Strange problems with encoding In-Reply-To: <7h3r80lfrqy.fsf@pc150.maths.bris.ac.uk> References: <7h3wuadfvt3.fsf@pc150.maths.bris.ac.uk> <7h3r80lfrqy.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson wrote: > > Well, I'm from the setdefaultencoding-is-evil camp, but it sounds like > you're in a pretty icky situation. > I wasn't even aware there are two camps. What would be the reasons not to use setdefaultencoding? As I configured it now it uses the systems locale to set the encoding. I'm using the same machine to retrieve data, manipulate it and store in a database (on the same machine). I would like to understand what could be wrong in this case. >> >>Actually, I don't care as long as the encode and decode on the same >>machine give me back the original value. > > > Huh? > What I mean is that I encode the data when I store it in the DB and decode it when I retrieve the data from the DB. I do this because SQLObject doesn't support the binary data. As long as the result that comes back out is exactly the same as it was when it went in, I don't care. > >>>>The reason I want to base64-encode these unicode strings is because I >>>>get those as input and want to store them in a MySQL database using >>>>SQLObject. >>> >>>! Why can't you just encode them as utf-8 strings? (Or, thinking >>>about it, why doesn't SQLObject support unicode?) >>> >> >>The actual input strings don't really contain unicode text values, but >>rather binary values i get as result from calling win32.NetUserEnum. > > > Oh, so they're not really unicode strings at all? Blech. That's > really really nasty. Binary data should really be represented as > (narrow) strings in Python. I'm just doing it the easy way, I guess. I get the data from the win32 call as Unicode data, even when it contains binary data. Perhaps that I will transform this data in a later phase to more usefull format, but that'll depend on the need. Perhaps the utf-16-le codec would be the > most appropriate... > This is really not my thing. I noticed that on my system the encoding is now set to cp1252. What would be the difference if I switched to utf-16-le? Thanks for your explanation. Rudy From aleax at aleax.it Tue Nov 4 13:23:02 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 04 Nov 2003 18:23:02 GMT Subject: programming languages (etc) "web popularity" fun References: <1b0569eff1ff540df7b1bf4ad2d5da1f@news.teranews.com> <874qxl9iuw.fsf@pobox.com> Message-ID: Skip Montanaro wrote: > Please add Macsyma to your list. There must be one or two Lisp Machines > still out there... ;-) At your service -- here's the tail of the evergrowing list...: 26: matlab 109000 27: smalltalk 98100 28: ruby 95900 29: mathematica 70800 30: maple 70600 31: powerbuilder 49500 32: erlang 29800 33: object pascal 23600 34: caml OR ocaml OR "o'caml 20700 35: macsyma 3110 36: interlisp 1630 Alex From janeaustine50 at hotmail.com Mon Nov 17 21:08:01 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 17 Nov 2003 18:08:01 -0800 Subject: Memory exception with Tkinter root.quit Message-ID: >Jane Austine wrote: >>>>from Tkinter import * >>>>>r=Tk() >>>>>b=Button(r,text='Quit',command=r.quit) >>>>>b.pack() >>>>>r.mainloop() >> >> >> And when I press the "Quit" button the mainloop exits. After that, if >> I finish the python shell, a memory exception occurs. >> >> This is Windows XP machine with Python 2.3. > > Not much of a help, but I've tried it here: no problems... (python > 2.3.2, win xp). Can it be a Python 2.3.0 issue that has been fixed in > 2.3.1 or 2.3.2 ? > > --Irmen I tried it with 2.3.2, but it doesn't work either. The crash message is: python.exe -- application program error the command from "0x77f7e22a" referenced the memory at "0x00000028". The memory couldn't be "read". From aahz at pythoncraft.com Mon Nov 24 12:33:40 2003 From: aahz at pythoncraft.com (Aahz) Date: 24 Nov 2003 12:33:40 -0500 Subject: Origin of the term "first-class object" References: <8ef9bea6.0311171335.356a7af6@posting.google.com> Message-ID: In article , Rainer Deyke wrote: >Aahz wrote: >>Rainer: >>> >>> l[x * 2 + f(y)] = f(l[x * 2 + f(y)]) >>> >>> This statement contains an obvious redundancy that will make code >>> maintenance difficult. Python allows me to factor out some of the >>> redundancy: >>> >>> index = x * 2 + f(y) >>> l[index] = f(l[index]) >>> >>> However, Python gives me no way to factor out the remaining >>> redundancy. >> >> Sure it does: change the immutable to a mutable. > >Not good enough. Why not? Note that you're playing what is IMO an unfair game where you keep changing the goalposts. >I'd rather write "l[x] = f(l[x])" with all of its redundancy than wrap >every conceivable immutable object in a mutable wrapper. Besides, I >don't *want* 'f' to change an object (which may also be referenced >elsewhere); I want it to change a binding. Well, you're going to have to pay for what you want in some fashion; Python's going to keep its default semantics, so you're going to need *some* kind of wrapper. >And, really, "l[x] = f(l[x])" isn't that big of a deal. It's a bit of >redundancy that I'd rather not have, but it's not bad enough that I >feel the need to do anything about it. It's not a redundancy unless you're using a particular skewed way of looking at things. If you're going to skew, you might as well keep skewing until you're using a Pythonic mechanism. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From Google_Post at slink-software.com Wed Nov 12 10:25:54 2003 From: Google_Post at slink-software.com (K_Lee) Date: 12 Nov 2003 07:25:54 -0800 Subject: Regular expression code implementation review between Tcl vs Python References: <394af34.0311110758.3b1781ea@posting.google.com> <3fb10cc1.7910169@News.CIS.DFN.DE> <394af34.0311112107.20b9a34f@posting.google.com> Message-ID: <394af34.0311120725.4ab9bb39@posting.google.com> David Gravereaux wrote in message news:... > Google_Post at slink-software.com (K_Lee) wrote: > > >I guess the TCL original goal was also to support > >Win16, DOS, etc. > > No it wasn't. Given whatever core an extension is loaded into, the > extension grabs the function table from the core it is loaded into. > > Say for example I build all of Tcl statically into my application (kinda > dumb, but let's just say). If I try to load an extension into it, where is > it supposed to get the Tcl functions it needs? Do you see the issue Stubs > solves? > Ok, David, I understand better now. (Putting on my monday morning quarterback hat.) If the original design specifies that * If you load extension with .so/dll, you are required load tcl from .so/dll. then we can get rid the stub interface, right? That doesn't sound like an unreasonable requirement for people who use any tcl + extension. I still think Tcl'folks did a great jobs, just like to know the trade off vs. features better. K Lee From nessus at mit.edu Fri Nov 14 04:59:25 2003 From: nessus at mit.edu (Douglas Alan) Date: Fri, 14 Nov 2003 04:59:25 -0500 Subject: Python's simplicity philosophy References: <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: BW Glitch writes: >> The mantra "there should be only one obvious way to do it" apparently >> implies that one should remove powerful, general features like >> reduce() from the language, and clutter it up instead with lots of >> specific, tailored features like overloaded sum() and max(). > That's not what _I_ understand. There's room for powerful features, > but when these features gives trouble to the people who just want > something done, then another approach should be taken. If there's a problem with people not understaning how to sum numbers with reduce(), then the problem is with the documentation, not with reduce() and the documentation should be fixed. It is quite easy to make this fix. Here it is: FAQ --- Q: How do I sum a sequence of numbers? A: from operator import add reduce(add, seq) Problem solved. > And I'm not talking about stupid people. I'm talking about the > microbiolgist/chemist/physics/etc who is programming because of > need. If a microbiologist cannot understand the above, they have no business being a microbiologist. I learned reduce() in high school, and it didn't take me any longer than the 60 seconds I claim it will take anyone with a modicum of intelligence. >> If so, clearly this mantra is harmful, and will ultimately result >> in Python becoming a bloated language filled up with "one obvious >> way" to solve every particular idiom. This would be very bad, and >> make it less like Python and more like Perl. > You feel ok? Perl's mantra is "More Than One Way To Do It"... If both the mantras cause a language to have general features replaced with a larger number of specialized features that accomplish less, then both mantras are bad. >> I can already see what's going to happen with sum(): Ultimately, >> people will realize that they may want to perform more general >> types of sums, using alternate addition operations. (For intance, >> there may be a number of different ways that you might add together >> vectors -- e.g, city block geometry vs. normal geometry. Or you >> may want to add together numbers using modular arithmetic, without >> worrying about overflowing into bignums.) So, a new feature will >> be added to sum() to allow an alternate summing function to be >> passed into sum(). Then reduce() will have effectively been put >> back into the language, only its name will have been changed, and >> its interface will have been changed so that everyone who has taken >> CS-101 and knows off the top of their head what reduce() is and >> does, won't easily be able to find it. > I don't get you. There's a reason why special functions can be > overloaded (__init__, __cmp__, etc.; I don't use others very > often). That would allow for this kind of special > treatments. Besides GvR would not accept your scenario. There are often multiple different ways to add together the same data types, and you wouldn't want to have to define a new class for each way of adding. For instance, you wouldn't want to have to define a new integer class to support modular arithmetic -- you just want to use a different addition operation. > Also, whytf do you mention so much CS101? Because anyone who has studied CS, which should include a significant percentage of programmers, will know instantly where to look for the summing function if it is called reduce(), but they won't necessarily know to look for sum(), since languages don't generally have a function called sum(). And everyone else will not know to look for either, so they might as well learn a more powerful concept in the extra 30 seconds it will take them. > Maybe you took the course with LISP, assembly and Scheme, but AFAIK, > not everyone has/had access to this course. Many people learned to > program way before taking CS101. As did, I, and I had no problem with reduce() when I learned it long before I took CS-101. > IMHO, you think that the only people that should make software > is a CS major. Did I say that? >>>> To me, there is never *one* obviously "right way" to do anything >>> Never? I doubt this very much. When you want to add two numbers in a >>> programming language, what's your first impulse? Most likely it is >>> to write "a + b". >> Or b + a. Perhaps we should prevent that, since that makes two >> obviously right ways to do it! > Even without any algebra, any kid can tell you that 1 + 2 is the same > as 2 + 1. Replace 1 and 2 by a and b and you get the same result. Yes, but they are still two *different* ways to to get to that result. Starting with a and adding b to it, is not the same thing as starting with b and adding a to it. It is only the commutative law of arithmetic, as any good second grade student can tell you, that guarantees that the result will be the same. On the other hand, not all mathematical groups are albelian, and consequently, a + b != b + a for all mathematical groups. >> C'mon -- all reduce() is is a generalized sum or product. What's >> there to think about? It's as intuitive as can be. And taught in >> every CS curiculum. What more does one want out of a function? >> |>oug > It wasn't obvious for me until later. reduce() is more likely to be > used for optimization. IIRC, some said that optimization is the root > of all evil. I don't know what you are getting at about "optimization". Reduce() exists for notational convenience--i.e., for certain tasks it is easer to read, write, and understand code written using reduce() than it would be for the corresponding loop--and understanding it is no more difficult than understanding that a summing function might let you specify the addition operation that you'd like to use, since that's all that reduce() is! > Just because it's _obvious_ to you, it doesn't mean it's obvious to > people who self taught programming. It was obvious to me when I was self-taught and I taught myself APL in high-school. It also seemed obvious enough to all the physicists who used APL at the lab where I was allowed to hang out to teach myself APL. |>oug From dcengija_IQ_Filter at inet.hr Tue Nov 25 06:46:07 2003 From: dcengija_IQ_Filter at inet.hr (Davor Cengija) Date: Tue, 25 Nov 2003 12:46:07 +0100 Subject: Extracting email attachment when is_multipart() is False Message-ID: I need to write a script which should extract the attachment from a text file, which is saved as MIME mail message. Unfortunatelly, Message.is_multipart() returns False so msg.get_payload() returns the complete message. What I need is the attachment only. Is it possible to do that with standard email package without the actual string level parsing? This is how my file/message looks like: ====== start here ======== This is a multi-part message in MIME format. ------=_NextPart_000_0026_01C3B347.DBEA9660 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit CONTENT signature, etc ------=_NextPart_000_0026_01C3B347.DBEA9660 Content-Type: application/octet-stream; name="filename.csv" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="filename.csv" 10012;20031118;292.67;4 101;23;19.98;2;39.96 102;24;21.89;4;87.56 ------=_NextPart_000_0026_01C3B347.DBEA9660-- ====== end here ======== So, I obviously need this part only: 10012;20031118;292.67;4 101;23;19.98;2;39.96 102;24;21.89;4;87.56 Python 2.3.2 on windows. Thanks and regards, Davor From joconnor at nets.com Sun Nov 23 00:46:58 2003 From: joconnor at nets.com (Jay O'Connor) Date: Sat, 22 Nov 2003 22:46:58 -0700 Subject: Empty list as default parameter In-Reply-To: References: <7xislb238p.fsf@ruckus.brouhaha.com> Message-ID: Bengt Richter wrote: >On 22 Nov 2003 19:05:58 -0800, Paul Rubin wrote: > > > >>bokr at oz.net (Bengt Richter) writes: >> >> >>>Yes. The bindings of default values for call args are evaluated at >>>define-time, in the context of the definition, not at execution >>>time, when the function is called. >>> >>> >>That's always seemed like a source of bugs to me, and ugly workarounds >>for the bugs. Is there any corresponding disadvantage to eval'ing the >>defaults at runtime as is done in other languages? >> >> >What languages are you thinking of? A concrete example for comparison would >clarify things. > One example that had not occurred to me until reading this thread has to do with how Smalltalk methods are built. Since Smalltalk doesn't allow for default parameters, one very common idiom is for a developer to create a sort of 'cascade' effect of multiple methods. The full method will require all the paremeters,but one or more of the more common ways of using the method will be provided which just turn around and call the main method with some default parameter provided for the paramaters not beiing specified. An example: Canvas>>drawShape: aShape color: aColor pen: aPen "do all the drawing in this method." ... Now, if the developer decides that often the color or pen are going to be pretty standard he may provide some 'convenience methods' that other developers can call that in turn just call the main method with defaults. Canvas>>drawShape: aShape "Use default color of balck and a solid pen" ^self drawShape: aShape color: #black pen: #solid Canvas>>drawShape: aShape color: aColor ^self drawShape: aShape color: aColor pen: #solid Canvas>>drawShape: aShape pen: aPen ^self drawShape: aShape: color: #black pen: aPen. This can be a built akward to write sometimes, but makes life pretty nice for the other developers. This is not alwasy the case but just based on what the developer thinks are going to be likely patterns of use. What came to mind, of course, is that this allows the defaults to be dynamic. Canvas>>drawShape: aShape ^self drawShape: aShape color: self currentColor pen: self currentPen You are still providing defaults, but the defaults are based on the current state of the system at execution, not at compile time. This is actually a fairly common idiom in Smalltalk, but Smalltalk's mechanism for method signatures is fairly unique and happens to support this approach well. From http Wed Nov 19 14:46:30 2003 From: http (Paul Rubin) Date: 19 Nov 2003 11:46:30 -0800 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <3FBB805D.40A8DA75@engcorp.com> <3FBBA68A.6D819C5C@engcorp.com> Message-ID: <7x8ymcp2eh.fsf@ruckus.brouhaha.com> "Dave Brueck" writes: > > My guess is that it's so insecure that most people wouldn't really want > > to use it if they knew how insecure it was, or they would actually decide > > that something like XORing the data is actually adequate and stick with > > that. > > Maybe so, maybe not. Here's one counter data point: me. :) May I ask what application you want to use rotor for? > If someone is trying to protect their data but haven't done enough > of their homework to know that rotor versus e.g. AES is incredibly > weak, odds are they aren't going to have a secure system *at all* > anyway, no matter how strong encryption library they use - they'll > probably leave the key totally exposed or some such mistake. If a > person using it _doesn't_ know how insecure it is, then even if you > give them AES to make the front door impenetrable, most likely all > the windows will still be wide open. Having spent a lot of time as the in-house crypto maintainer on a security-intensive commercial development project, I can confirm that there's much truth to what you're saying. That's why a built-in library encryption function intended for non-specialists has to free the application programmer as much as possible from the likelihood of using a cipher the wrong way. Of course there's infinite ways the application itself can screw something up, but the library implementer can't much help that. > How's this: it would be really great to have a key-based data > obfuscator (read: weak encryptor) ship as a standard part of > Python. But that's precisely what rotor is, and IMO it does a bad job. > I'll concede that if rotor keeps somebody out, a simple data munge > like XOR probably would too (although you're getting a little closer > to the point where hex editor-using crackers can play whereas rotor > requires a programmer cracker). The difference is that a standard > module like rotor hits the sweet spot in terms of diminishing > returns of effort vs security, so if you're going to settle for that > level of security and have it ship as a standard module, why _not_ > just use rotor? If you're going to ship something as a standard module, it should try to provide real security. It was a mistake to have ever shipped rotor. From hgiese at ratiosoft.com Tue Nov 11 11:39:32 2003 From: hgiese at ratiosoft.com (Helmut Giese) Date: Tue, 11 Nov 2003 16:39:32 GMT Subject: Regular expression code implementation review between Tcl vs Python References: <394af34.0311110758.3b1781ea@posting.google.com> Message-ID: <3fb10cc1.7910169@News.CIS.DFN.DE> On 11 Nov 2003 07:58:14 -0800, Google_Post at slink-software.com (K_Lee) wrote: >I documented the regex internal implementation code for both Tcl and Python. > >As much as I like Tcl, I like Python's code much more. >Tcl's Stub interface to the external commands is confusing to >outsider. I still don't get why the stub interface is needed. Simple. Let's create an example. If you don't use it, than you have to link your extension against the current version of Tcl, say, tcl84.lib. Easy, no problem. But tomorrow Tcl 8.5 comes out and you have the problem, that tcl85.dll is running (used by tclsh or wish) and your extension needs tcl84.dll, since (during its linking) you created an un-breakable connection between the two. Solutions: - Stick with the older version of Tcl. - Re-compile the extension now linking against Tcl85.lib (and repeat for Tcl 8.6, 8.7, etc.) - Don't link against Tcl8.x lib but use the 'stub interface'. This avoids creating this fixed connection between your extension and a particular version of Tcl, and you can use the extension with any future version of Tcl and be happy ever after (unless the stub interface itself changes, but this will be in a completely different time frame- if it should ever happen at all). >One aspect I don't understanding about python is that the Python >language itself is object oriented and all the internal is implement >as C object. Why not C++ object? Just my 0.02: I suppose that C++ compilers still differ a lot more on different platforms (concerning their conformance to the standard) than C compilers do. So, if portability is high on your check list, C still is the language of choice - but in the future C++ will catch up (IMHO). Best regards Helmut Giese From mesteve_b at hotmail.com Sun Nov 30 07:34:59 2003 From: mesteve_b at hotmail.com (python newbie) Date: Sun, 30 Nov 2003 12:34:59 GMT Subject: referencing an object attribute sort of indirectly from within list References: Message-ID: Sorry about that, I retyped it because I was actually using dom to import an xml file, and the nodes were used to populate the object attributes, not the literal strings I was using. I didn't want to put the xml code in this post. I also set my email to text only, so no more html. "Bengt Richter" wrote in message news:bqbnp2$i27$0 at 216.39.172.122... > On Sun, 30 Nov 2003 01:32:05 GMT, "python newbie" wrote: > > >This is a multi-part message in MIME format. > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-- So far, so annoying > [...] > > > >Is there anything that would get in the way of me being able to = > >reference an object attribute, from within a list. > > > >I have: > Where do you have it? This is not an actual verbatim example of something you tried. > > > # one class here > > > > class BackupSet: > ^--- this is different from your constructor call below at [1] > > fileGroupList =3D [] > > =20 > ># another class here > > > > class FileGroup: > > sourceDir =3D '' > > destinDir =3D '' > > def __init__(self): > > self.sourceDir =3D 'c:\folder' > > self.destinDir =3D 'd:\folder' =20 > > > > > >fileGroup =3D FileGroup() > > > >backupSet =3D BackUpSet() > ^----- [1] So I know you didn't do this. > > > >backupSet.fileGroupList.append(fileGroup) > > > ># when i try to reference an attribute here, I just get 'none' > Maybe you have some old code that reads > self.sourceDir = 'none' > in class FileGroup. Who can tell? > > > > >print bkset.fileGroupList[0].sourceDir or > ^^^^^-- what the heck is that? > > >print "%s" % bkset.fileGroupList[0].sourceDir > > =20 > > > >thanks > >Steve > >------=_NextPart_000_0025_01C3B69E.E2B92BA0 > >Content-Type: text/html; > > Two things: > 1. Don't post HTML > 2. Do post verbatim copy/pasted examples from the window where you > actually tried what you are talking about. It's not that much more typing. > > I'm hungry. I don't know why I'm putting off food even a minute to do this ;-/ > > Regards, > Bengt Richter From nomail at hursley.ibm.com Thu Nov 20 21:48:21 2003 From: nomail at hursley.ibm.com (Derek Fountain) Date: Fri, 21 Nov 2003 10:48:21 +0800 Subject: Details on exceptions References: <3fbd7509$0$1749$5a62ac22@freenews.iinet.net.au> Message-ID: <3fbd7c7c$0$1746$5a62ac22@freenews.iinet.net.au> > Library Reference, Built-in Exceptions will tell you > everything you want to know. Ah ha! Yes, it did, thanks. The business of learning Python seems to revolve around learning where, in all the documentation, the thing you're looking for is written. Here's an example: in that page it says: "When exceptions of this type are created with a 2-tuple...". Er, what does that mean? I found an example which does this: except IOError, (errno, strerror): which is presumably the syntax referred to. Where, in the docs or the O'Reilly book, can I find a description of this syntax? Can I instantiate any class in that manner, or is it somehow specific to the exception handling in some way? From andy at wild-flower.co.uk Tue Nov 11 16:29:53 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Tue, 11 Nov 2003 21:29:53 +0000 Subject: confirm 3d8e4ecdf861b0c71d045ac0eb95a4f49e3fe70d In-Reply-To: References: Message-ID: <200311112129.53484.andy@wild-flower.co.uk> On Tuesday 11 Nov 2003 1:10 pm, python-list-request at python.org wrote: > Your membership in the mailing list Python-list has been disabled due > to excessive bounces The last bounce received from you was dated > 11-Nov-2003. You will not get any more messages from this list until > you re-enable your membership. You will receive 3 more reminders like > this before your membership in the list is deleted. > > To re-enable your membership, you can simply respond to this message > (leaving the Subject: line intact), or visit the confirmation page at > > > http://mail.python.org/mailman/confirm/python-list/3d8e4ecdf861b0c71d045ac0 >eb95a4f49e3fe70d > > > You can also visit your membership page at > > > http://mail.python.org/mailman/options/python-list/andy%40wild-flower.co.uk > > > On your membership page, you can change various delivery options such > as your email address and whether you get digests or not. As a > reminder, your membership password is > > silver > > If you have any questions or problems, you can contact the list owner > at > > python-list-owner at python.org Has anyone else been getting these? When I checked my membership page, it said *one* bounce, out of a threshold of 15... is it just a glitch or maybe something of more import? -andyj From peter at engcorp.com Mon Nov 3 15:52:02 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Nov 2003 15:52:02 -0500 Subject: Selling Python Software References: <8765i1d2jb.fsf@pobox.com> <3FA6BCF4.9BC51DF@alcyone.com> Message-ID: <3FA6BFF2.5238729B@engcorp.com> Erik Max Francis wrote: > > Most copy protection schemes these days, such as they are, are intended > to discourage casual violations. Things like requiring a serial number > or the right CD in the drive are usually considered fairly good common > ground solutions, because they're well-known territory and the average > customer won't be put off too much by them. And, sadly, there is a large number of "average customers" who seem to be aware of Warez sites and know enough to download and install the broken versions of software. The number of people I know with "free" versions of XP is somewhat shocking. I think Quicken is one of the few programs I've seen lately which seems to remain somewhat intact. (I'm quite sure I'll hear otherwise now, but so far I haven't seen rampant copying.) The basic technique used there is online registration, which I assume decrypts and/or enables certain critical portions of the code after server verification of credentials, and prevents repeat registrations using the same CD. Maybe that's a good new baseline for such protection. -Peter From andrew-pythonlist at puzzling.org Thu Nov 27 02:19:39 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 27 Nov 2003 18:19:39 +1100 Subject: Memory Hungry in Windows In-Reply-To: References: Message-ID: <20031127071939.GA10357@frobozz> On Thu, Nov 27, 2003 at 02:00:27PM +0800, Geiger Ho wrote: > Hi, > > I have a program. It opens a text file about 2 MB. It reads in every > line and appends them to a string. It then does a re.sub() to replace the > contents of the long string and then write to a file. Repeatedly appending strings is slow, and probably likely to cause memory fragmentation. Does your re.sub have to operate on the whole file at once, or can it work one line at a time? If it can, I would apply the re.sub to each line as I read it in, and immediately write it out to the output file. If you do need to operate on the whole file, you should probably do: long_string = open('some_file').read() rather than what it sounds like you're doing: long_string = '' for line in open('some_file'): long_string += line This should be faster and require less memory. > In Linux, it consumes about 5 MB, but in W2k, it concumes 20 MB! Why > there is so much difference for the same piece of code? This has > frightened me that I don't know if the program will crash for no memeory > available somedays. I expect this is a result of the differences between how linux and windows reports memory usage (particularly with things like shared libraries), as well as differences between the platform malloc implementations (although with pymalloc the default in 2.3, that shouldn't be as large a factor). -Andrew. From sombDELETE at pobox.ru Thu Nov 20 16:21:26 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Fri, 21 Nov 2003 00:21:26 +0300 Subject: Python Database Objects (PDO) 1.2.0 Released References: Message-ID: [Jon Franz] >>>> [on PDO design] Looks like you did it right considering all tradeoffs. Good luck :) -- Serge Orlov. From fredrik at pythonware.com Fri Nov 14 14:41:35 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 14 Nov 2003 20:41:35 +0100 Subject: for what are for/while else clauses References: Message-ID: Diez B. Roggisch wrote: > today I rummaged through the language spec to see whats in the for ... else: > for me. I was sort of disappointed to learn that the else clauses simply > gets executed after the loop-body - regardless of the loop beeing entered > or not. > > So where is an actual use case for that feature? for item in seq: if item == target_item: print "Found", item break else: print "Nothing found, dude!" > I imagined that the else-clause would only be executed if the loop body > wasn't entered, so I could write this > > for r in result: > print r > else: > print "Nothing found, dude!" > > instead of > > if len(result): > for r in result > print r > else: > print "Nothing found, dude!" which is usually written as: if result: for r in result: print r else: print "Nothing found, dude!" or if not result: print "Nothing found, dude!" else: for r in result: print r From paul at boddie.net Fri Nov 7 10:57:45 2003 From: paul at boddie.net (Paul Boddie) Date: 7 Nov 2003 07:57:45 -0800 Subject: Unicode Hell References: Message-ID: <23891c90.0311070757.164bf4a0@posting.google.com> "Stuart Forsyth" wrote in message news:... > > The script then moaned about it being non-ascii and crashed. The exact > error is: > > Error Type: > Python ActiveX Scripting Engine (0x80020009) > Traceback (most recent call last): File "

Router Status

Account Name
Firmware Version 4.13 Aug 20 2003
Internet Port
MAC Address 00:09:5b:29:3d:b4
IP Address 66.72.206.129
DHCP None
IP Subnet Mask None
Domain Name Server 66.73.20.40
206.141.193.55
LAN Port
MAC Address 00:09:5b:29:3d:b3
IP Address 192.168.0.1
DHCP Server
IP Subnet Mask 255.255.255.0
Wireless Port
MAC Address (BSSID) 00:09:5b:29:3d:b3
Name (SSID) natchieland
Region USA
Channel 1
From eppstein at ics.uci.edu Mon Nov 24 17:44:37 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 24 Nov 2003 14:44:37 -0800 Subject: Delete common entries between two dictionaries References: <4Guwb.7197$9O5.6638@fed1read06> <97ba91-169.ln1@dman13.dyndns.org> Message-ID: In article , "Amy G" wrote: > How do I do this same thing but with lists??? > > I apparently have two lists... not dictionaries. > > This is what it prints if I add > print domains_black domains_black = [x for x in domains_black if x not in domains_white] If domains_white is a long list, this will be inefficient due to the linear search to test whether each x belongs to it. In that case, you might be better off using a set: mask = Set(domains_white) domains_black = [x for x in domains_black if x not in mask] Also, this creates a new list. If you instead want to change the same list in-place, you could replace "domains_black =" with "domains_black[:] =". -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From frr at easyjob.net Wed Nov 5 11:33:44 2003 From: frr at easyjob.net (Fernando Rodriguez) Date: Wed, 05 Nov 2003 17:33:44 +0100 Subject: How to list the superclassesof an object References: Message-ID: On Wed, 05 Nov 2003 16:17:11 GMT, Alex Martelli wrote: >>>> x.__class__.__bases__ >(, ) I didn't know the existence of the __bases__ attribute, and it doesn't show with dir(). How can I get a list of ALL the attributes of an object? I thought that dir() listed every attribute.... O:-) > >You may need a recursive walk up the (DA) graph if you also want >bases of bases, etc, among 'superclasses'; alternatively, but >ONLY for newstyle classes (recommended anyway for many reasons): I haven't used python in a while and all my classes are 'old style'. I'd like to get up to date. Where can I find info about the differences / advantages of these new classes? Is it safe to convert all my previous classes to new ones, and how can I do it? O:-) TIA From peter at engcorp.com Mon Nov 10 18:07:56 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Nov 2003 18:07:56 -0500 Subject: Blocking readline() Call? References: Message-ID: <3FB01A4C.3838D7C4@engcorp.com> Scott Brady Drummonds wrote: > > "Scott Brady Drummonds" wrote in > message news:booqnf$ioc$1 at news01.intel.com... > > Hi, everyone, > > > > I'm just figuring Python out but have become stalled with the following > > snippit of code: > [code deleted] > > JP said: > > I think you mean "break" here, not "continue". > > Peter said: > > Correct this: you want "break", not continue > > Mel said: > > 'continue' doesn't mean what you think it means. Try 'break'. > > So, what is it that you people are trying to tell me? Please don't beat > around the bush. Sorry we were unclear, Scott. See Paul Clinch's post for an answer that is more concise and perhaps easier for you to understand. ;-) ;-) -Peter From scrutinizer at gmx.at Tue Nov 18 16:20:38 2003 From: scrutinizer at gmx.at (Francesco) Date: Tue, 18 Nov 2003 22:20:38 +0100 Subject: simple program to prevent from exceptions References: <3fba648f$0$58700$e4fe514c@news.xs4all.nl> Message-ID: Hello Irmen. > >> I know pychecker, but is there a simpler program, >[...] > >What's difficult about pychecker? If I use pychecker in boa constructor, it takes sometimes several minutes, before I get any result. But maybe this could be, that I have switched on too many options. > >> I think for example of using a varible, without setted before. > >Because of Python's highly dynamic nature, these sort >of static code checking is generally very hard to do. I feared so :) > >Personally, I stick with Pychecker, fix the things it >bitches about, and other errors will be caught by >testing soon enough. yes you'r right; it was only a little idea > >--Irmen -- Francesco From usenet at joefrancia.com Sat Nov 29 02:54:42 2003 From: usenet at joefrancia.com (Joe Francia) Date: Sat, 29 Nov 2003 07:54:42 GMT Subject: jython applet In-Reply-To: References: Message-ID: <6hYxb.1898998$Id.287201@news.easynews.com> jennifer haynes wrote: > I can't Date() to print out in an applet > this is what I have > > from java.util import Date > from java import awt, applet > from java.lang import String > > class Enhanced(applet.Applet): > def paint(self, g): > today = Date() > g.drawString(today, 10, 30) > > > > if __name__ == '__main__': > import pawt > pawt.test(Enhanced()) > http://www.catb.org/~esr/faqs/smart-questions.html From nospam at nowhere.hu Mon Nov 24 13:25:19 2003 From: nospam at nowhere.hu (Miklós) Date: Mon, 24 Nov 2003 19:25:19 +0100 Subject: 2.2.2 Annoyance References: Message-ID: Michael Hudson wrote in message news:m3r7zxzukb.fsf at pc150.maths.bris.ac.uk... > "Jegenye 2001 Bt" writes: > > > According to the manuals of Python 2.2.2, passing a slice object to > > __getitem__ is all right and should work... > > Really? Where does it say that? Python Reference Manual, 3.3.4 Emulating container types (Release 2.2.2, documentation updated on October 14, 2002. ) """ __getitem__(self, key) Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of """ > > > For Python 2.3 passing a slice object to __getitem__ does work though. > > Yes. Do you have a good reason for sticking to 2.2? > Yes, see my previous post on this. (That site wants to stay with 2.2 for the time being.) Actually I patched the code to circumvent this and I haven't tried 2.2.3 as for this yet. (I didn't know about 2.2.3 until Terry's response..) All this is no big deal ... unless you pull too many hairs of your receding head because of a bug like this. :-)) Cheers, Mikl?s > Cheers, > mwh > > -- > Python enjoys making tradeoffs that drive *someone* crazy . > -- Tim Peters, comp.lang.python From relee_s at hotmail.com Tue Nov 4 18:58:08 2003 From: relee_s at hotmail.com (Relee Squirrel) Date: Tue, 04 Nov 2003 23:58:08 -0000 Subject: New to Python - Compiled Language? In-Reply-To: Message-ID: --- In python-list at yahoogroups.com, "Francis Avila" wrote: > "Relee Squirrel" wrote in message > news:mailman.410.1067915526.702.python-list at p... > > Please reply both here and directly to my email address > > relee_s at h... > > > > I just found out about Python today and it sounds very interesting, > > but I'm having trouble finding solid information about my main > > question. Is Python a compiled language, or merely a sequence of > > commands fed into a seperate program? > > I'm not sure how this distinction names corelatives, or even why it's > important. > > Python is a bytecode compiled language (as opposed to machine-code compiled, > but see Psycho http://psyco.sourceforge.net/introduction.html (et al.?), > which compile Python to native machine code like a JIT compiler). > > Python is also an interpreted language. It interprets the bytecode. (This > is, presumably, your "sequence of commands fed into a seperate program"?) > > Python is also interactive: > Read:eval:print :: code:bytecode:interpreting bytecode. > > ... > > Is Python a language which can be compiled into an executable program? > > Um, what do you mean by "executable"? You can execute Python code, sure, > given a Python interpreter. Python will simply compile it before running > the generated bytecode (compilation is transparent and fast enough that we > ignore it, for all practical purposes). You can also only give Python the > bytecode, and it'll use that (these are *.pyc files). > > Or, you can use Psycho. (I think there's something out there that converts > Python to C code, too?) > > Or, you can bind up the Python code with a Python interpreter, using py2exe > or workalikes. > > Or, you can write C that uses the CPython libraries, but doesn't use the > Python interpreter. It's arguable whether this is still Python, but hey. > > But what computer language is there that doesn't produce--at least > theoretically--an executable program? > > I simply don't understand your categories. Python is a real-life bona-fide > computer programming language. You write code, give it to the Python thingy > (whatever you want to call it), and it makes the computer do stuff. Like > any language. > > Python isn't a "scripting" language any more than lisp is. It's not a very > good shell-script replacement (see perl for that); it's a general- purpose > language. Does "scripting" mean "does not compile to machine code"? Or > maybe it means "no pointers"? "Scripting" names a problem domain, not a > language species (except insofar as that problem domain is a given > language's strength. Even then, Python isn't a scripting language!) > > I think you're probably going about this the wrong way. Pythonistas > generally extend Python with C(++) for one of two reasons: > 1) Because native Python simply isn't fast enough (rare) > 2) To wrap libraries that aren't in Python (very common, so common that > there is boilerplate code in the distribution to speed you along.) > > Otherwise, they program everything in Python! So when I read this: > > > the tools and utilities referred to existing in Python > > would increase the development time of my projects. > > I think, "Well, just using Python would increase it even *more*!" > Then I read this: > > > However, what I'm > > creating are programs, not just scripts. > > I think, "What the?! Only C++ programs are 'real' programs?!" > > Look, I know you said you just heard about Python, so I'm being far gruffer > than I should be. I'm sorry. I can't say anything specific because you > weren't very specific about how you think Python can serve your needs. I > may be entirely off base. However, there are only three ways *I* can think > of as to how Python could possibly help you: > 1) Prototype your code in Python, then write it in C++. > 2) Embed Python into an existing C++ application, as a "scripting language" > for that application. > 3) Just write the whole darned thing in Python! > > Try this: download Python, follow the included Python tutorial, and code up > some small non-trivial application that duplicates part of the functionality > of something you already have some C++ code doing in the application domain > for which you want to use Python's "tools and utilities". I guarantee you, > that even if you code in a very un-Pythonic fashion, the Python code will be > simpler, shorter, clearer, more robust and powerful, have fewer bugs, be > more fun to write, and 9 times out of 10, fast *enough*. Repeat this a few > times, and you'll probably want to stop using C++ altogether. > > But that's just me. Explore the www.python.org site a bit more, and you'll > find many faqs, commercial success stories, tutorials, HOWTOs, links to > Python-related sites, the entire documentation for present, past, and future > language and library versions, tutorials, Package Index, etc, etc, where you > can learn more. > -- > Francis Avila > > -- > http://mail.python.org/mailman/listinfo/python-list From fredrik at pythonware.com Wed Nov 19 17:09:39 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 19 Nov 2003 23:09:39 +0100 Subject: Parsing HTTP messages References: Message-ID: Chris Gray wrote: > My initial question is, what Python library do I use to parse HTTP > messages? mimetools.Message is a good choice. httplib.HTTPHeader is a slightly better choice (it's a subclass of mimetools.Message; see the httplib.py source code for more info) > But my understanding of RFC (2)822 is that there is no such thing as a > "start-line" in that format, and so the "email" module is right in trying > to treat the HTTP "start-line" as a header and that that start-line should > be stripped out before feeding it the remainder of the message which _is_ > in (2)822 format. > > Am I (don't laugh) missing something here? not really, as long as "stripped out" means "processed", not "ignored" (the start line contains the HTTP method and the target URL) From aahz at pythoncraft.com Tue Nov 18 10:07:35 2003 From: aahz at pythoncraft.com (Aahz) Date: 18 Nov 2003 10:07:35 -0500 Subject: pyc / pyo architecture independent? References: Message-ID: In article , Terry Hancock wrote: > >Are the .pyc / .pyo files safely architecture independent? (I.e. are >they now, and are they likely or even guaranteed to remain so?). Yes. I don't know about future guarantees, but you may be assured that it would be a Big Change if that were no longer true. >I know the bytecode can change between interpreter versions and other >interpreters like Jython, Stackless, and PyPy (does that exist yet?) >may not even choose to make them. But given that the same interpreter >is made available, will they work on, say, an ARM processor, a 68K, and >a i386 sharing them on the same network? Yes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From adalke at mindspring.com Fri Nov 14 17:30:55 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 14 Nov 2003 22:30:55 GMT Subject: Python's simplicity philosophy References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <8hfsb.7707$nz.895@newsread2.news.pas.earthlink.net> <9s8tb.22141$9_.810000@news1.tin.it> Message-ID: Alex: > Anyway, computational scientists using Python should be using Numeric > (if they aren't, they're sadly misguided). Or they are like me and work in a subfield where (specialized) database searches and graph theory is more useful. It was strange at SciPy with all those people using NumPy and doing CFD and our little group of computational life sciences people being rather bored. > Indeed, that's why 'sum' is a commonly used word in English -- exactly > because nobody's every DOING anything like that -- while, of course, > 'reduce' is totally obvious -- why, _anybody_ who's ever taken > Chemistry 101 knows it means "to remove oxygen"! While in Chemistry 102 they learn that it means to add electrons and can occur in a non-oxygen environment ;) http://reference.allrefer.com/encyclopedia/O/oxidreduc.html Andrew dalke at dalkescientific.com From ville.spammehardvainio at spamtut.fi Tue Nov 25 09:51:52 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 25 Nov 2003 16:51:52 +0200 Subject: command line arguments (newbie...) References: Message-ID: "Matteo Risoldi" writes: > In this program I did, I am parsgin command line arguments through the > getopt.getopt function in the following way (note: try/except and other I can say this w/o reading the rest of your mail: don't do it, use optparse instead. -- Ville Vainio http://www.students.tut.fi/~vainio24 From kun.liu at siemens.com Fri Nov 7 06:47:41 2003 From: kun.liu at siemens.com (Liu Kun, SLC ICM (BJ)) Date: Fri, 7 Nov 2003 19:47:41 +0800 Subject: How to use a .pyd Message-ID: <54CD3165FCE49A44A9A6F2179B3C36C3BC92B8@pekw092a> Hello, I want to use a method from _xxx_yyy.pyd, but I can not use import to load this file, how to use .pyd in python interpreter? Best Regards Liu Kun From ghowland at lupineNO.SPAMgames.com Tue Nov 18 19:06:12 2003 From: ghowland at lupineNO.SPAMgames.com (Geoff Howland) Date: Tue, 18 Nov 2003 16:06:12 -0800 Subject: Python Database Objects (PDO) 1.2.0 Released References: <8rtgrvkl8vae90116u3opgdn2inias1ti4@4ax.com> <1ankrv4ieuncf20o9bhfsc1bamc0o5i4p0@4ax.com> Message-ID: <3uclrvs3n62vl0ucb09brmnm3q9e535vsq@4ax.com> On Tue, 18 Nov 2003 14:15:10 -0500, "Jon Franz" wrote: >> I havent looked at the other DBAPI implementations lately, but with >> MySQLdb you can set the cursor type to DictCursor, and then you get >> back a sequence of dictionaries with the field names as the dict keys. > >This is true, but unfortunately it isn't standard behavior according to the >DBAPI 2.0 spec (pep 249). >Since it isn't standard, it seems everyone that does provide it >in the module provides it a different way.- if they provide it at all. > >With PDO you get this functionality everytime, with no need to change >your code when you switch databases and DBAPI modules to get it. >Plus, PDO's implementation of acccess-by-name uses less memory >than a sequence of mapping objects - excluding the case of very small >(1-3 record) results, that is. I can exapnd upon how/why if people >are curious. Sounds good, if you can update/insert back into the DB by the same dictionary then I'm sold. I'll go check it out. :) -Geoff Howland http://ludumdare.com/ From DennisR at dair.com Fri Nov 7 18:10:07 2003 From: DennisR at dair.com (Dennis Reinhardt) Date: Fri, 07 Nov 2003 23:10:07 GMT Subject: Problems with regexps References: <87fzgz98vh.fsf@internal.daycos.com> <874qxf946f.fsf@internal.daycos.com> Message-ID: > sample = 'FOO= BAR' > if re.search(r'[^=]\s*BAR', sample): > print 'Match 2.' The [^=] will match on the space preceding BAR. The \s* matches because there are zero spaces remaining. Result: match. Prediction: you can get the first expression to fail by putting in two spaces, not one. Caveat: untested. -- Dennis Reinhardt DennisR at dair.com http://www.spamai.com?ng_py From martin at v.loewis.de Sat Nov 22 02:41:48 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 22 Nov 2003 08:41:48 +0100 Subject: Tkinter / Unicode and UTF-8 In-Reply-To: References: Message-ID: <3FBF133C.8050503@v.loewis.de> Thomas wrote: > I just used the 'Python' and 'tkinter' RPMs from www.python.org to > update ('rpm -U ...') the RPMs provided with the Fedora Core 1 Linux > distribution. Which RPM did you use specifically? If it is http://www.python.org/ftp/python/2.3.2/rpms/redhat-9/python2.3-tkinter-2.3.2-1pydotorg.i386.rpm then you can't use it on Fedora 1: The RPM is for Redhat 9, after all, not for Fedora 1. > But (my main problem!): I still do not understand why the first > example does not work, while the second does!? Because you are using incorrect binaries. You will have to build Python from source on Fedora 1, or wait for Redhat to fix the package. The pydotorg RPM assumes that Tk uses UCS-4 internally, as it does on Redhat 9. On Fedora 1, Tk uses UCS-2, so copying a Python Unicode string into a Tcl Unicode string copies twice as many character as you have (and overwrites some unrelated memory in the process). There is, unfortunately, no way to detect the problem at run-time. So I repeat: You *have* to compile from source. Regards, Martin From edreamleo at charter.net Tue Nov 18 17:11:18 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Tue, 18 Nov 2003 16:11:18 -0600 Subject: Using other tools with unittest? Message-ID: Has anyone used tools like pychecker (or even Python's own debugger or profiler) during unit testing? Here are some things that might be natural to do: 1. pychecker can run all kinds of fancy tests on code. I'm wondering whether these tests could be incorporated somehow into individual unit tests. For example, one might use pychecker to assert that a subclass does, or does not, override a method of a base class. Yes, one could write that test "by hand". The question is: how good is pychecker for this sort of thing? Anyone have any experience? 2. Python's debugger is simple because Python so helpfully provides the sys.settrace function. Has anyone used sys.settrace for unit testing? For example, suppose you wanted to make a list of the methods that are exercised by a test suite. The tracing function registered by sys.settrace could easily do this. Etc. 3 In a slightly different direction, has someone used a simulation of aspect-oriented programming in Python to make statements about test coverage, or for other testing purposes? Thanks. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From janeaustine50 at hotmail.com Wed Nov 12 11:37:01 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 12 Nov 2003 08:37:01 -0800 Subject: socket's strange behavior with subprocesses Message-ID: Running Python 2.3 on Win XP It seems like socket is working interdependently with subprocesses of the process which created socket. ------------------------------------ #the server side >>> import socket >>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) >>> s.bind(('localhost',9000)) >>> s.listen(5) >>> z=s.accept() >>> import os >>> f=os.popen('notepad.exe') #notepad appears on the screen >>> z[0] >>> z[0].recv(6) 'foobar' >>> z[0].send('hello world') 11 #the client side >>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) >>> s.connect(('localhost',9000)) >>> s.send('foobar') 4 >>> print s.recv(1024) hello world ------------------------------ Now when the client requests to recv 1024 bytes, and since there is no more to read from the socket it blocks. #client side >>> s.recv(1024) #it hangs and the server side tries to close the socket: #server side >>> z[0].close() >>> #yes, it seems to have worked. Alas, the client side doesn't wake up! It doesn't wake up unless the notepad is exited first; only after that, 'Connection reset by peer' is raised. What does the socket has to do with subprocesses? From ulysses_dm at yahoo.com.cn Wed Nov 12 04:10:33 2003 From: ulysses_dm at yahoo.com.cn (ulysses) Date: 12 Nov 2003 01:10:33 -0800 Subject: can't run py app after compile to exe by py2exe , gettext Message-ID: <43e3984e.0311120110.2bea96cc@posting.google.com> hi. I use python 23,py2exe 0.4.3 ,wxpython do my py app in win32. I use gettext to support multi languages. I build a small fuction for load language at top of main module. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def setLan(lan): import gettext langs = gettext.GNUTranslations(open (join ( localPath, ( "lan/"+lan+".mo" ) ) ) ) langs.install() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Above run normally in debug mode, when I compile to exe by py2exe. the exe can't run, no error raised, I can see exe in task manager. but after few seconds , exe disappear automaticlly. If I remove the function setLan, EXE can show main GUI. But the function I has used it in another app,python22 ,wxpython. So I use other way of show multi language. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def setLan(): t = gettext.translation("tbt", os.path.join(dir,"locale\\"), languages=['en']) t.install() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ situation same as before, can run in script mode, exe can't show. Remove this function, program ok. I don't what happen , I have test many many times. Somebody help me :( ulysses From FBatista at uniFON.com.ar Mon Nov 17 12:01:29 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 17 Nov 2003 14:01:29 -0300 Subject: Dictionary problem Message-ID: #- myList = [] #- for i in range(3) : #- myDict['id']=i #- myList.append(myDict) The problem here is you're binding the same dictionary to each element in the list. So, when the dictionary changes, change all the elements. #- myList becomes: [{'id':2}, {'id':2}, {'id':2}] but I want: [{'id':0}, #- {'id':1}, {'id':2}] #- #- thanx for any hint how to achieve that You need to store a copy of the dictionary: >>> myList = [] >>> myDict = {} >>> for i in range(3): myDict['id'] = i myList.append(myDict.copy()) >>> myList [{'id': 0}, {'id': 1}, {'id': 2}] . 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 gandalf at geochemsource.com Wed Nov 26 10:24:03 2003 From: gandalf at geochemsource.com (Gandalf) Date: Wed, 26 Nov 2003 16:24:03 +0100 Subject: kinterbas db column type References: Message-ID: <3FC4C593.2060605@geochemsource.com> > i need to know the database column types returned by kinterbasdb. > Implicit type conversion is i nice thing to have, but it hides the > real types in the database. > So how could i get this information? If you use InterBase only, you can get that information from the metadatabase. Try this: RDB$RELATIONS - this stores table information RDB$FIELDS - this is for the fields (here you have the RDB$FIELD_TYPE field) RDB$RELATION_FIELDS - connects relations to fields you can figure out the others. (Oh, it is for InterBase 6.0 but the others are similar or the same) Cheers, L 1.0 From firi_mu at fjcl.fujitsu.com Sun Nov 30 20:43:17 2003 From: firi_mu at fjcl.fujitsu.com (Philippe Mougin) Date: Mon, 01 Dec 2003 10:43:17 +0900 Subject: Unicode output to file In-Reply-To: <200312010129.21021.eugine_kosenko@ukr.net> References: <200312010129.21021.eugine_kosenko@ukr.net> Message-ID: <20031201103923.1E9F.FIRI_MU@fjcl.fujitsu.com> Hi Eugine, As is stated in the PEP page given in the error message, you need to add these 2 comment lines at the beginning of your source code is using an encoding different from ASCII (starting from Python 2.3): #!/usr/bin/python # -*- coding: -*- So in your case, I presume you should use something like : #!/usr/bin/python # -*- coding: cp855 -*- f = file("content.new", "wb") ... Cheers, Philippe. > Hi! > > The next program > > f = file("content.new", "wb") > print f.encoding > f.write(u"?ph?r") > > Gives the next results: > > sys:1: DeprecationWarning: Non-ASCII character '\xcf' in file xp.py on line > 10, but no encoding declared; see http://www.python.org/peps/pep-0263.html > for details > None > Traceback (most recent call last): > File "xp.py", line 10, in ? > f.write(u"?ph?r") > UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: > ordinal not in range(128) > > I use here Russian letters, and need special encoding for them. The property > 'encoding' is read-only, and is None by default. How to cast the encoding for > a file? > From __peter__ at web.de Tue Nov 4 13:10:51 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Nov 2003 19:10:51 +0100 Subject: breaking iteration of generator method References: Message-ID: Brian wrote: > Hello; > > What happens when a program breaks (think keyword 'break') its iteration > of a generator? Is the old state in the generator preserved? > > Ex: > > # .gen() is generator method. > > for i in myObject.gen(): > if i == specialValue: > break > > Do subsequent calls to .gen() start off with new locals? Or, would > the iteration begin after the yielded 'i' that caused the for-statement > to exit? > > > Many thanks, > > Brian. Running the following little demo should answer you questions. The Mark class is used only to show when the generator dies, it relies on CPython's garbage collection algorithm. class Mark(object): def __init__(self): print "created" def __del__(self): print "gone" def gen(): mark = Mark() for i in range(10): yield i for i in gen(): print i, if i == 5: print "breaking" break g = gen() for i in g: print i, if i == 5: print "breaking" break while True: print g.next() Peter From ramen at lackingtalent.com Fri Nov 21 19:12:10 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sat, 22 Nov 2003 00:12:10 -0000 Subject: Singleton generators as code blocks Message-ID: Hey all, I was just reflecting upon the old code block debate, and the thought occurred to me that Python really does have a form of code blocks in its implementation of generators. It was a pretty natural conclusion, and I'm not sure why I didn't think of it before. For instance, compare Python's generator-style iteration versus Ruby's codeblock-style iteration: Python: for item in seq: print item Ruby: seq.each { |item| puts item } Now, aside from the difference in mechanics, these two methods basically accomplish the same thing. "seq" could be a regular list, or it could be a lazy sequence. The syntax remains the same. One of the simplest arguments in favor of codeblocks (or macros, but I'm not going to go there ) was the ability to write a function like "with_open_file" that would open a file, perform some action on the file, and then close the file automatically. I'm going to use this as an example because of its simplicity, not because I think that there is an overwhelming need for such a function. In Python, I was able to implement a generator version quite simply. It seemed so obvious that I thought maybe there was a thread in the past where this was already mentioned; if so, forgive me for stating the obvious: def open_file(filename, mode='r'): f = file(filename, mode) yield f print 'closing...' f.close() for f in open_file('input.txt'): print f.read() The above code prints the conntents of the file "input.txt", then the string "closing...", and then closes the file. This seems to illustrate that generators and codeblock-accepting functions are really very similar, and that maybe codeblocks wouldn't really add much of anything to Python after all. I still have to wonder if maybe I'm missing something here... Has anyone used this sort of "singleton generator" technique? -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From ruach at chpc.utah.edu Fri Nov 7 11:53:23 2003 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Fri, 07 Nov 2003 09:53:23 -0700 Subject: Creating a random integer.... In-Reply-To: <8f43ba42.0311062140.344ed651@posting.google.com> References: <8f43ba42.0311062140.344ed651@posting.google.com> Message-ID: Python has a module for doing just that its called random. Try this: import random # print a random interger between 0 100 print random.randint(0,100) # print a random number from the list lst lst = [1,3,6,17,87,330] print random.choice(lst) Hope this helps. I recommend picking up a copy of Python Standard Library by Fredrick Lundh at your local book store or library. It will have more detailed information about the random module and the PSL. -matthew Code_Dark wrote: > Hi, sorry to bore you with my newbie questions, but I _am_ a newbie > so.. right. Anyway, I was working out a "number guessing game", which > works fine, except I wanted to make the number a random number so it's > different every time... can you please tell me what to do to get > python to create a random number? > > Thanks, > > - Code Dark From vincent at visualtrans.de Tue Nov 25 01:10:17 2003 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 25 Nov 2003 07:10:17 +0100 Subject: sleep() function, perhaps. References: Message-ID: "Ryan Spencer" schrieb im Newsbeitrag news:pan.2003.11.25.05.26.36.747748 at earthlink.net... | | Hello Everyone, | | I want to have a row of periods, separated by small, say, .5 second | intervals between each other. Thus, for example, making it have the | appearance of a progress "bar". | | [code] | import time | | sleep(.5) | print "." | sleep(.5) | print "." | [end code] | | But, it would (with those .5 second intervals) | print out much like the following. | | . | (pause) | . | (pause) | | I would rather those periods be on a single line, not printing on a new | line each time. import time,sys while 1: sys.stdout.write(".") time.sleep(0.5) You could also use: print ".", (note the trailing comma) but that will leave you with an additional space after the dot HTH, Vincent Wehren | Any suggestions? | | Thank you in advance, | ~Ryan | From robin at jessikat.fsnet.co.uk Sun Nov 30 13:03:19 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 30 Nov 2003 18:03:19 +0000 Subject: medusa as win32 service Message-ID: I wonder if this is the right way to write a medusa(asyncore) server with the win32all framework. Other example services seem to create an event to pass the stop signal from SvcStop into a separate termination method, but I'm unsure how that would mix with the polling loop. This simple framework seems to start and stop OK, but I wonder if I'm missing some obvious race or something. import win32serviceutil, win32service, class MeducaService(win32serviceutil.ServiceFramework): _svc_name_ = "MedusaService" _svc_display_name_ = "Medusa Service" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) print "Received Quit from Win32" socket_map = asyncore.socket_map while socket_map: k, v = socket_map.popitem() try: print "Shutting down",k,v v.close() except: pass del k, v def SvcDoRun(self): start_medusa() -- Robin Becker From mbabcock at fibrespeed.net Mon Nov 3 08:54:26 2003 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Mon, 03 Nov 2003 08:54:26 -0500 Subject: Explanation of macros; Haskell macros In-Reply-To: References: Message-ID: <3FA65E12.1070204@fibrespeed.net> > > >The costs: syntax seems to be constrained to have a very regular surface >structure full of parentheses; the language must describe and implement a >representation of code as data which would otherwise be unnecessary; every >compiler must include an interpreter; it's hard to report errors to the >user showing the code as it's written in the source if the error is found >after macro expansion. > I don't really want to jump into the middle of a discussion here, but if someone wanted to do this in Python, one *can* of course write Python code that generates Python code and then executes it. This gives the compile-time type macro execution timeframe; build the code you want to execute with Python before executing it then execute it. There's no need for an additional macro-like system when your runtime allows you to execute your own strings. I know this is a higher-order discussion on the merits of macro systems in other languages and how they'd benefit (or not) Python, but I decided to throw my $0.02 (CAN) in. -- Michael T. Babcock C.T.O., FibreSpeed Ltd. http://www.fibrespeed.net/~mbabcock From reply.in.the.newsgroup at my.address.is.invalid Mon Nov 17 18:40:39 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 18 Nov 2003 00:40:39 +0100 Subject: Python Database Objects (PDO) 1.2.0 Released References: <8rtgrvkl8vae90116u3opgdn2inias1ti4@4ax.com> Message-ID: Jon Franz: >A Resultset is actually very different from a cursor - The first and >most blatant difference being that with a Resultset, you get column >access by name. Thanks Jon, that clarifies it. -- Ren? Pijlman From jroznfgre at jngpugbjreQBGbet.cy Sun Nov 2 18:29:07 2003 From: jroznfgre at jngpugbjreQBGbet.cy (JZ) Date: Mon, 03 Nov 2003 00:29:07 +0100 Subject: form processing question References: <423f3$3fa58837$42a655ea$20950@msgid.meganewsservers.com> <87ism2754c.fsf@pobox.com> <6bd64$3fa590f3$42a655ea$21185@msgid.meganewsservers.com> Message-ID: On Sun, 2 Nov 2003 18:19:06 -0500, "WmGill" wrote: >Like I said, I'm experimenting. I was thinking of using the standard cgi >module. but I'm open to suggestions. Look at Spyce framework: http://spyce.sourceforge.net It is similiar to PHP but uses Python syntax. -- JZ ICQ:6712522 From jjl at pobox.com Thu Nov 20 08:07:49 2003 From: jjl at pobox.com (John J. Lee) Date: 20 Nov 2003 13:07:49 +0000 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <3FBB805D.40A8DA75@engcorp.com> <3FBBA68A.6D819C5C@engcorp.com> <7x8ymcp2eh.fsf@ruckus.brouhaha.com> Message-ID: <87y8ubw5lm.fsf@pobox.com> Paul Rubin writes: > "Dave Brueck" writes: [...] > > How's this: it would be really great to have a key-based data > > obfuscator (read: weak encryptor) ship as a standard part of > > Python. > > But that's precisely what rotor is, and IMO it does a bad job. That's not a "but", that's an "and". It does a bad job of strong encryption, it does the job for obfuscation. It *is* a step up Anybody can write a program to decrypt XORed data in a line of code (maybe emacs has a keystroke for it), decryption of rotor encryption requires the extra effort to find a library to crack it, or to know enough to write your own. Whether that small point justified its initial inclusion is certainly debatable, but now it's in there, it seems like a mistake to deprecate it. John From ville.spammehardvainio at spamtut.fi Sat Nov 15 07:01:00 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 15 Nov 2003 14:01:00 +0200 Subject: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <8hfsb.7707$nz.895@newsread2.news.pas.earthlink.net> Message-ID: Douglas Alan writes: > Well, bah! There are precious few constructs in this world that are > clearer and more readable than > > reduce(add, seq) I asked my non-programmer girlfriend what she thinks your construct does - she didn't know. She immediately understood what sum(seq) does. -- Ville Vainio http://www.students.tut.fi/~vainio24 From fredrik at pythonware.com Fri Nov 7 02:14:38 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 7 Nov 2003 08:14:38 +0100 Subject: Any suggestions to speed this up References: <92c59a2c.0311041209.2e89e054@posting.google.com> Message-ID: "MetalOne" wrote: > def buildBitmap(rawData, w, h, maxColorVal): > """ppm format, http://netpbm.sourceforge.net/doc/ppm.html > Constructs a wxBitmap. The input is a raw > grayscale image, 8 bits per pixel.""" > imageHdr = "P6\r%d %d\r%d\r" % (w, h, maxColorVal) > #expand grayscale to rgb > imageBuf = imageHdr + string.join([v*3 for v in rawData], "") > return wxBitmapFromImage( wxImageFromStream( > cStringIO.StringIO(imageBuf) )) > > Virtually all the time is consumed expanding the 1 byte of grayscale > data into 3 bytes to get RGB. For example, V=128 is converted to > R=128,G=128,B=128. this might work: def buildBitmap(rawData, w, h, maxColorVal=255): """pgm format, http://netpbm.sourceforge.net/doc/pgm.html Constructs a wxBitmap. The input is a raw grayscale image, 8 bits per pixel.""" imageHdr = "P5\r%d %d\r%d\r" % (w, h, maxColorVal) return wxBitmapFromImage( wxImageFromStream( cStringIO.StringIO(imageBuf) )) if it doesn't, use PIL: http://www.pythonware.com/products/pil/index.htm something like this might work (untested; tweak if necessary): from PIL import Image def buildBitmap(rawData, w, h): im = Image.fromstring("L", (w, h), rawData) im = im.convert("RGB") file = cStringIO.cStringIO() im.save(file) file.seek(0) # rewind return wxBitmapFromImage(wxImageImageFromStream(file)) also see: http://effbot.org/zone/pil-image.htm if you're running under Windows, you may be able to get better performance by wrapping the PIL image in a Dib object, and copying the Dib directly to screen; see: http://effbot.org/zone/pil-imagewin.htm From usenet2003 at krap.dk Sat Nov 8 06:02:43 2003 From: usenet2003 at krap.dk (Svenne Krap) Date: Sat, 08 Nov 2003 12:02:43 +0100 Subject: [newbie] GTK+/QT/Tkinter ? In-Reply-To: References: Message-ID: Alexandre Rogers wrote: > Is there an IDE/GUI builder for Tkinter ? > Try looking at wxPython (the framework, http://www.wxpython.org) and wxGlade (the GUI-builder, http://wxglade.sourceforge.net/) I find wxPython extremely pleassant to work with. Svenne From spam.meplease at ntlworld.com Sun Nov 23 11:13:24 2003 From: spam.meplease at ntlworld.com (deglog) Date: 23 Nov 2003 08:13:24 -0800 Subject: python xml dom help please Message-ID: Apologies if this post appears more than once. The file - ---------------
--------------- is processed by this program - --------------- #!/usr/bin/env python from xml.dom.ext.reader import PyExpat from xml.dom.ext import PrettyPrint import sys def deepen(nodeList): for node in nodeList: print(node.nodeName) if node.previousSibling != None: if node.previousSibling.nodeType == node.ELEMENT_NODE: if node.previousSibling.hasChildNodes(): print("has children") node.previousSibling.lastChild.appendChild(node) else: node.previousSibling.appendChild(node) deepen(node.childNodes) # get DOM object reader = PyExpat.Reader() doc = reader.fromUri(sys.argv[1]) # call func deepen(doc.childNodes) # display altered document PrettyPrint(doc) --------------- which outputs the following - --------------- Game Game A B --------------- Can anybody explain why the line 'print(node.nodeName)' never prints 'C'? Also, why 'has children' is never printed? I am trying to output --------------- --------------- I know there are easier ways to do this, but i want to do it using dom. Thanks in advance. From deets.nospam at web.de Fri Nov 21 06:29:45 2003 From: deets.nospam at web.de (Diez B. Roggisch) Date: Fri, 21 Nov 2003 12:29:45 +0100 Subject: Garbage collection working improperly? In-Reply-To: References: Message-ID: Hi, > Builds up a great list in memory and immediately deletes it. Unfortunately if all you want is to create a loop, use xrange instead of range - it won't create that huge list. > the task manager shows me that i allocated about 155MB in memory before > del(), but del only releases about 40MB of them so i'm leaving about 117 MB > of reserved memory after deleting the list. > I'm using python 2.2.3 on WinXP. > Any ideas about that? How can i dealloc the left memory space? Nope, no idea - the only thing that I can think of is that python not necessarily releaseses the memory because it uses its own allocation scheme. I don't know that for sure, but I definitely would go for such a thingy if I was to implement a virtual machine. Its like in JAVA - each object instantiation and destruction isn't paired with system malloc/free calls, but some internal memory manager deals with that. And if it rans out of space, it will request more from the system. Regards, Diez From mis6 at pitt.edu Sun Nov 2 01:19:11 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 1 Nov 2003 22:19:11 -0800 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <87d6cjope5.fsf@pobox.com> <87he1vsopi.fsf@pobox.com> <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> Message-ID: <2259b0e2.0311012219.73aa445f@posting.google.com> Stephen Horne wrote in message news:... > On 29 Oct 2003 23:26:05 -0800, mis6 at pitt.edu (Michele Simionato) > wrote: > >I have got the impression (please correct me if I misread your posts) that > >you are invoking the argument "cats are macroscopic objects, so their > >ondulatory nature does not matter at all, whereas electrons are > >microscopic, so they ondulatory nature does matter a lot." > > That is *far* from what I am saying. > Oops, sorry! I was not sure about your point: sometimes I have difficulties in understanding what are you saying, but when I understand it, I usually agree with you ;) > The evidence suggests that conscious minds exist > within the universe as an arrangement of matter subject to the same > laws as any other arrangement of matter. I think that mind is a an arrangement of matter, too; nevertheless, I strongly doubt that we will ever be able to understand it. Incidentally, I am also quite skeptical about IA claims. > I prefer Penrose' theory I read a Penrose's book book years ago: if I remember correctly, he was skeptical about AI (that was ok). However, at some point there was an argument of this kind: we don't understand mind, we don't understand quantum gravity, therefore they must be related. (?) > most current theory is so > abstract that the explanations should be taken as metaphors rather > than reality anyway. True. > No problem with that, but we are seeing microscopic effects en masse > rather than macroscopic effects - something rather different, in my > mind, to a cat being both alive and dead at the same time. > The effects > when they occured were on the microscopic scale - only the artifacts > are macroscopic. I have nothing against what you say in the rest of your post, but let me make a comment on these points, which I think is important and may be of interest for the other readers of this wonderfully off-topics thread. According to the old school of Physics, there is a large distinction between fundamental (somewhat microscopic) Physics and non-fundamental (somewhat macroscopic) Physics. The idea is that once you know the fundamental Physics, you may in principle derive all the rest (not only Physics, but also Chemistry, Biology, Medicine, and every science in principle). This point of view, the reductionism, has never been popular between chemists of biologists, of course, but it was quite popular between fundamental physicists with a large hubrys. Now, things are changing. Nowadays most people agree with the effective field theory point of view. According to the effective field theory approach, the fundamental (microscopic) theory is not so important. Actually, for the description of most phenomena it is mostly irrelevant. The point is that macroscopic phenomena (here I have in mind (super)conductivity or superfluidity) are NOT simply microscopic effects en mass: and in certain circumstances they do NOT depend at all from the microscopic theory. These ideas come from the study of critical phenomena (mostly in condensed matter physics) where the understanding of the macroscopic is (fortunately) completely unrelated from the understanding of the microscopic: we don't need to know the "true" theory or a detailed description of the material we are studying, if we are near a critical point. In this situation it is enough to know an effective field theory which can explain all the phenomena we can see given a finite experimental precision, even if it is not microscopically correct. In critical phenomena the concept of universality came out: completely different microscopical theories can give the *same* universal macroscopic field theory. Actually, the only things that matter are the dimensionality of the space-time and the symmetry group, all others details are irrelevant. This point of view has become relevant at the fundamental Physics level too, since nowadays most people regard the Standard Model of Particle Physics (once regarded as "the" fundamental theory) as a low energy effective theory of the "true" theory. This means that even if it is not the full story, it explain the 99.99% of phenomena we can measure; moreover, it is extremely difficult to see clear signatures of the "true" underlining theory. The real theory can be string theory, can be loop quantum gravity, can be a completely new theory, but for 99.99% of our experiments only the effective theory matters. So, even if we knew perfectly quantum gravity, this would not help at all in describing 99.99% of elementary particle physics, since we would still need to solve the quantum field theory. And, for a similar reason, even if we knew everything about QCD, we could not use it to describe the wheather of Jupiter (which is described by a completely different effective theory) even if we had an ultra-powerful Python-powered quantum computer ... That's life, but it is more interesting this way ;) Michele From claird at lairds.com Tue Nov 18 11:31:54 2003 From: claird at lairds.com (Cameron Laird) Date: Tue, 18 Nov 2003 16:31:54 -0000 Subject: new guy References: Message-ID: In article , nards_collective wrote: >I'm new to Python, in fact I'm new to programming. I'm trying to write >a simulation program, for a biology class I'm teaching next year. the >following code is giving me trouble and i can't work out why. > > if e>= 1 : > a=e > else : > a=0 > > >I keep getting a syntax error. >This piece of code is meant to keep the value of a equal to or grater >than 0. Any odeas would be appreciated. . . . Others have already spoken to the details of syntax. The best help I can give is to recommend you read . Also, although it's nominally about a different language, you might like . Being "new to programming" is exciting! You'll accelerate your progress as you develop an instinct to change I keep getting a syntax error to I see the specific syntax error, '...' [copied EXACTLY from the screen]. Python has a lot to offer, and already has many successes in, biology and other physical sciences. Some day the references in might interest you. -- Cameron Laird Business: http://www.Phaseit.net From paul at boddie.net Mon Nov 24 06:50:49 2003 From: paul at boddie.net (Paul Boddie) Date: 24 Nov 2003 03:50:49 -0800 Subject: writing xml tree References: Message-ID: <23891c90.0311240350.234375c3@posting.google.com> david farning wrote in message news:... > I am doing my first work in python/xml > > Is is possiable to write a xmlTree in a single command? > for example > > doc = libxml2.parseFile (filename) > # add node to doc > > doc.write(filename) ?????????????? > > I have seen several examles writing one element or line at a time, but never > the whole tree. You can use the serialize method on the document node to get the document as text (or on any other node to get a document fragment as text): s = doc.serialize() # Use normal file writing mechanisms. Or you could use the saveFile method to write to a file: doc.saveFile(filename) I'd recommend using Python interactively to see which methods are available on the document node: import libxml2 doc = libxml2.parseFile(filename) dir(doc) Indeed, until I started responding to your question, I hadn't noticed saveFile, so there's a lot to discover. ;-) Paul From joconnor at cybermesa.com Tue Nov 11 11:13:38 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Tue, 11 Nov 2003 16:13:38 GMT Subject: Matrix - Metaphors, Analogies and the REAL References: Message-ID: <3fb10a9e.42064405@news.cybermesa.com> On Tue, 11 Nov 2003 12:20:58 GMT, "RaYzor" wrote: > >"3seas" <3seasA at Tthreeseas.DOT.not> wrote in message >news:xrQrb.21530$9M3.5754 at newsread2.news.atl.earthlink.net... >> If you are not interested, then don't bitch, its a short message. >> >> >http://www.matrixcommunity.org/cgi-bin/ultimatebb.cgi?ubb=get_topic;f=8;t=000918 >> >> I don't know if that link got broken. >> > >People who think the Matrix series of films are real in any way are amongst >the saddest people on Earth. Imagine if it was "Dark City" From bokkenka at yahoo.com Tue Nov 25 09:03:36 2003 From: bokkenka at yahoo.com (Ranger_Nemo) Date: 25 Nov 2003 06:03:36 -0800 Subject: 2 different python versions / how to install packages? References: Message-ID: """ If someone is interested in how to install and use a 'separate & clean' Python 2.3 as described above on Fedora Core 1, please let me know. I could post a short 'HOWTO'. """ I would. I've been working on it a bit for a couple weeks and haven't made any progress. TTFN, Ranger_Nemo From aleax at aleax.it Wed Nov 5 11:17:11 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 05 Nov 2003 16:17:11 GMT Subject: How to list the superclassesof an object References: Message-ID: Fernando Rodriguez wrote: > Hi, > > How can I list the superclasses of an object? O:-) >>> class A: pass ... >>> class B: pass ... >>> class C(A,B): pass ... >>> x=C() >>> x.__class__.__bases__ (, ) You may need a recursive walk up the (DA) graph if you also want bases of bases, etc, among 'superclasses'; alternatively, but ONLY for newstyle classes (recommended anyway for many reasons): >>> class C(object, A, B): pass ... >>> x = C() >>> x.__class__.__mro__ (, , , ) >>> the __mro__ attribute of a newstyle class does the walk on your behalf, in the right order, removing duplicates, etc, etc... Alex From sweetdima2 at msn.com Thu Nov 6 23:57:21 2003 From: sweetdima2 at msn.com (MAJED ASSAF) Date: Thu, 6 Nov 2003 22:57:21 -0600 Subject: QUESTION ABOUT PYTHON Message-ID: hello There Please I need help !! I don't know why my command prompt won't change to python even if I set the path it stays like the following Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\Owner> it won't change it stays on the document and settings -------------- next part -------------- An HTML attachment was scrubbed... URL: From belred1 at yahoo.com Fri Nov 14 01:09:34 2003 From: belred1 at yahoo.com (Bryan) Date: Fri, 14 Nov 2003 06:09:34 GMT Subject: Books I'd like to see In-Reply-To: References: Message-ID: Nick Vargish wrote: > I would like to see "wxPython Programming" from Grayson, John E. > > His book on tkinter is pretty darn good, but I'm much more interested > in wxWindows. I find the need to look up the C++ wxWindows > documentation and do a translation to the Python equivalent really > gets in my way of learning how to use the widgets properly. > > Nick > i 2nd this bryan From tweedgeezer at hotmail.com Wed Nov 5 01:18:13 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 4 Nov 2003 22:18:13 -0800 Subject: garbage colllector References: Message-ID: <698f09f8.0311042218.bef77c@posting.google.com> "Alberto Vera" wrote in message news:... > Hello: > I'd like to try the use of garbage collector, so I wrote these lines to > do it(*), but if I delete lines related to garbage collector this works > similar as it didn't have > The garbage collector is enabled by default. You'll very rarely have a good reason to manipulate it. Jeremy From max at alcyone.com Sun Nov 2 00:15:02 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 01 Nov 2003 21:15:02 -0800 Subject: suggestion for Python References: Message-ID: <3FA492D6.6E3D2571@alcyone.com> Fran?ois Miville-Dech?ne wrote: > I find your language very nice, it is actually more than three > quarters > of what I had been dreaming for years a programming language should > be. > But I mourn the passing of APL, another interpreted language. I like > interpreted languages, for they can be used in calculator mode, > testing > function after function without bothering to code long protocols in > the > language and outside it. The meat of this suggestion is what PEP 225 is about: http://www.python.org/peps/pep-0225.html -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Nothing is true -- all is permissible. \__/ Hassan i Sabbah From brian at sweetapp.com Mon Nov 10 17:40:52 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 10 Nov 2003 14:40:52 -0800 Subject: how to reference custom codec in a package? In-Reply-To: <16304.4415.165149.622961@montanaro.dyndns.org> Message-ID: <011001c3a7db$b2798290$21795418@dell8200> -----Original Message----- From: python-list-bounces+brian=sweetapp.com at python.org [mailto:python-list-bounces+brian=sweetapp.com at python.org] On Behalf Of Skip Montanaro Sent: Monday, November 10, 2003 2:29 PM To: python-list at python.org Subject: how to reference custom codec in a package? > I wrote a simple codec which strips accents from latin-1 characters (e.g., > maps '?' to 'e'). If it lives in a package how do I refer to it? For > example, what should this statement look like > x = unicode(x, "latin1").encode("latscii") You probably want to write a codec registry function. Something like this: import codecs def latscii_search_function(name): if name == 'latscii': try: import latscii except ImportError: return None else: codec = latscii.Codec() return (codec.encode, codec.decode, latscii.StreamReader, latscii.StreamWriter) codecs.register(latscii_search_function) Cheers, Brian From steve at ninereeds.fsnet.co.uk Sun Nov 2 04:40:42 2003 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sun, 02 Nov 2003 09:40:42 +0000 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> Message-ID: <9ij9qvkr2ooe4mujtutoailqufgkkfeddm@4ax.com> On Sun, 02 Nov 2003 08:12:09 GMT, "Andrew Dalke" wrote: >Orbital mechanics for the major planets are also chaotic, it's just that the >time frame for problems well exceeds the life of the sun. (As I recall; >don't have a reference handy.) Are you sure? I know that multi-object gravitational systems can be chaotic in principle (and I believe that the orbits of some of Jupiters moons are a case in point) but I thought the orbit of the planets around the sun had been proven stable. Which implies that you needn't worry about chaos unless you are worried about the minor deviations from the idealised orbits - the idealised bit can be treated as constant, and forms a very close approximation of reality no matter what timescale you are working in. It was one of the big successes of the Laplace transform, IIRC. But I could be mistaken. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From gandalf at geochemsource.com Wed Nov 26 08:21:23 2003 From: gandalf at geochemsource.com (Gandalf) Date: Wed, 26 Nov 2003 14:21:23 +0100 Subject: Where can i get the python source for windows References: <188007e5.0311260450.4d92012b@posting.google.com> Message-ID: <3FC4A8D3.5070203@geochemsource.com> > > >>i need the source code of python 2.3 for windows. >>I looked on ftp.python.org, but i can't find it. >> >> > >if you've managed to log in to ftp.python.org, it sure takes >some real effort to miss the source code: > > pub -> python -> 2.3 > >(where "pub" is the only directory on the top level) > >alternatively, you can browse to http://www.python.org, click >on the Python 2.3 link in the upper left corner, and look under >"download the release", where you'll find a link to: > > http://www.python.org/ftp/python/2.3.2/Python-2.3.2.tgz > > Fredrik, I'm affraid that is for Unix and OS X only. L 1.0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From gh at ghaering.de Mon Nov 24 13:07:13 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 24 Nov 2003 19:07:13 +0100 Subject: Database connectivity In-Reply-To: References: Message-ID: <3FC248D1.3090603@ghaering.de> SectorUnknown wrote: > I've written a database (Access mdb) front-end using Python/wxpython/and > ADO. However, the scope of the project has changed and I need to access > the same data on an MSSQL server. Also, the front-end needs to be cross- > platform (Windows and Linux). > > Does anyone have any suggestions on what database connectivity I should > use? I've looked at mxODBC and wxODBC briefly, but am not sure what is > the best way to go. [...] AFAIC you have two options: - Use mxODBC and save yourself/your company/your employer a considerable amount of time. - Program to the Python DB-API v2.0 and work around the differences between the various DB-API modules you'll need yourself. You'll probably end up the n-th abstraction layer on top of the DB-API. Another possibility is to see if an OR-thingie like PDO/SQLObject/... actually helps for database abstraction. I suppose they'll get really "fun" to use once you need advanced queries, though. Does anybody have any real-life experience with any of these Python OR mappers? -- Gerhard From pythonguy at Hotpop.com Fri Nov 14 06:19:49 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 14 Nov 2003 03:19:49 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> Message-ID: <84fc4588.0311140319.3778de15@posting.google.com> In the ideal "techie makes decisions" world this would have been a good thing. But not in the real world where the Suits make decisions in corporates. There might have been thousands of books published in C/C++ language and they have all helped to popularize it in one or the other way. Contrast, in the python world we have one Alex Martelli, one Wesley Chun, one David Mertz, really countable by hand. There is a limit to how much a single person can evangelize a language. Questions similar to what the O.P posted arise from the listeners. I would prefer to see more books on Python though they all might be useless from a pure techie point of view. Let us have a book on Software Projects in python for example. It might not have the technical superiority of a Martelli book, but more attempts like that will save the language and help the eyeball factor, which is so important in practical marketing. -Anand afriere at yahoo.co.uk (Asun Friere) wrote in message news:<38ec68a6.0311132310.630e10e2 at posting.google.com>... > python473 at yahoo.com (John Howard) wrote in message news:<9eabe547.0311131610.4dd7819c at posting.google.com>... > > I've sent several messages over the last year asking about python - > > Who teaches python? Is python losing steam? etc. I have noticed, eg, > > the declinng number of books at my local borders. The last time I > > visited a borders (last week), there was 1 (sic) book about python on > > the shelve compared to dozens on perl & java! > > > If you were developing in Java or Perl maybe you would need dozens of > books. But Python is so elegant and intuitive a single one will do. > ;) From gafStopSpamData at ziplink.stopallspam.net Tue Nov 11 10:56:43 2003 From: gafStopSpamData at ziplink.stopallspam.net (G.A.) Date: Tue, 11 Nov 2003 15:56:43 GMT Subject: What do you think of this Python logo? References: Message-ID: <8g12rvo9nagi57vng3s00gdg6er9pq4ktu@4ax.com> On 11 Nov 2003 20:26:08 +1100, Tim Churches wrote: >Much better to stick to a Monty Python-inspired theme, incorporating a I understand the desire to incorporate fun into Python, but I fear that any Monty Python inspired logo will connote frivolity. I don't think that's the image that should be conveyed. My initial take on the logo in the base note is that I like the cleaness of it. However, it took too much effort to recognize the outer loop as a snake, let alone a python. I kind of like the idea of a snake wrapped around the P. Gary From lliabraa at isrparc.org Thu Nov 20 08:45:23 2003 From: lliabraa at isrparc.org (Lane LiaBraaten) Date: Thu, 20 Nov 2003 13:45:23 +0000 Subject: mpeg player? Message-ID: <200311201345.24005.lliabraa@isrparc.org> Is there any way to play mpeg files with python without using pygame? TIA, LGL From sfb at alysseum.com Sun Nov 2 07:15:26 2003 From: sfb at alysseum.com (Simon Bayling) Date: Sun, 2 Nov 2003 12:15:26 +0000 (UTC) Subject: It's still I, Miville References: Message-ID: Fran?ois Miville-Dech?ne wrote in news:mailman.333.1067742542.702.python-list at python.org: > To take on another subject, an object-oriented language such as yours > should explicitly tackle the Microsoft Office constructs Python has been able to command Microsoft Office programs for the past 3-4 years, at least. The book "Python Programming on Win32" by Mark Hammond and Andy Robinson, published in Jan 2000 covers it. Install Python and the Win32All extensions. >>> from win32com.client import Dispatch >>> word = Dispatch('Word.Application') >>> word.Visible = 1 >>> doc = word.Documents.Add() >>> doc.Range(0,0).InsertAfter('Hello, here is some text in a Word >>> document') You can also explore various Office scripting examples at microsoft.com and translate them into Python without too much hassle. -- Simon. From ed at membled.com Sat Nov 1 07:35:01 2003 From: ed at membled.com (Ed Avis) Date: 01 Nov 2003 12:35:01 +0000 Subject: Python from Wise Guy's Viewpoint References: <65fn61-b61.ln1@ID-7776.user.dfncis.de> <3F994597.7090807@ps.uni-sb.de> <1j5o61-co2.ln1@ID-7776.user.dfncis.de> <9eso61-mu7.ln1@ID-7776.user.dfncis.de> <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <8yn6gmic.fsf@comcast.net> <1xssqozs.fsf@comcast.net> Message-ID: prunesquallor at comcast.net writes: >But let us suppose that someone improved the type system of Haskell >such that some useful complicated constructs that did not pass the >type checker were now able to be verified as correct. Wouldn't you need to define the semantics for these constructs too? And perhaps extend the compiler to generate code for them? My original point was that the type-checker won't reject programs which are valid Haskell, so it makes no sense to talk about the checker being too strict or not allowing enough flexibility. A type-checker for some other language such as Lisp would obviously have to not flag errors for any legal Lisp program. (That would probably mean not checking anything at all, with the programmer having to explicitly state 'yes I don't want to wait until runtime to catch this error'.) -- Ed Avis From fredrik at pythonware.com Mon Nov 17 06:40:02 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Nov 2003 12:40:02 +0100 Subject: for what are for/while else clauses References: <2259b0e2.0311142321.aba58d3@posting.google.com> Message-ID: Alex Martelli wrote: > > in every single case, it means "run once, if and only if the > > controlling condition is false". > > I'm not sure what you mean by "the controlling condition" in this case. the condition that controls if the conditional part of the statement is executed. from what I can tell, that's the usual definition. > In a for/else or while/else construct, the only way to make your > assertion true is to define "the controlling condition" as "a break > [or return] interrupted the for or while loop [or an exception was > propagated]" -- basically (quibbles on returns and exceptions apart) > just what I said about "no break was executed". for a while-statement, the controlling condition is the test at the top. for a for loop, the condition is "is there another item" (to quote the language reference: "When the items are exhausted (which is imme- diately when the sequence is empty) ... the loop terminates.". for a try-except clause, the condition is "did the suite raise an exception". > the fact that the 'controlling condition' is "a break statement > has executed" that's not how it works. From mwh at python.net Wed Nov 26 07:06:51 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 26 Nov 2003 12:06:51 GMT Subject: 2.2.2 Annoyance References: Message-ID: "Mikl?s" writes: > I understand the rationale for deprecating '__getslice__' from v2.0 > onwards was to make sequences and mappings to look more alike. But > then this change for __getitem__ should have been absolutely > introduced at that time or the semantics of CPython between 2.0 and > 2.2 doesn't make sense in this respect... Am I right in that? Well, sort of. Back in the 2.0 days you couldn't even write: >>> [].__getitem__ so >>> [].__getitem__(slice(0,1)) was right out! It's all a bit messy, and it's sorted out in 2.3. Cheers, mwh -- Monte Carlo sampling is no way to understand code. -- Gordon McMillan, comp.lang.python From ruari at charliefortune.com Tue Nov 4 02:56:39 2003 From: ruari at charliefortune.com (ruari mactaggart) Date: Mon, 3 Nov 2003 23:56:39 -0800 Subject: how do I stop the screen scrolling ? Message-ID: how do I put a pause, 'hit any key to continue' type thing in printing a long dictionary on the screen, please ? From joconnor at cybermesa.com Wed Nov 12 16:08:11 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Wed, 12 Nov 2003 21:08:11 GMT Subject: case-sensitivity References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FB2738E.2B8C13FE@engcorp.com> <3fb275b2.55356282@news.cybermesa.com> <7075rv0d1thucjc617gibn4te7uoumh71c@4ax.com> Message-ID: <3fb2a0ee.66426159@news.cybermesa.com> >I hope nobody is thinking of that approach seriously. It may work >well in places where the use is naturally limited in both scope and >degree, but it becomes unmanageable when the size and content are >allowed to grow with no limits on them. If you mean color-coded code with meaning, I don't know. but if you mean using databases for source-code management, it works very well and I much prefer it to text file based approaches. From johnk at aurema.commercial Sun Nov 23 19:32:33 2003 From: johnk at aurema.commercial (John Ky) Date: Mon, 24 Nov 2003 11:32:33 +1100 Subject: Compiling Python extensions for different Python installation Message-ID: <1069633966.973970@cousin.sw.oz.au> Hello: I have a machine that already has Python 2.2 installed. Since I do not have root access to the machine, I have installed Python 2.3 from source to my own private directory. I can use this fine. When I build my own C module extension and try to run it from Python 2.3 however, I get this message: /test-wrk/test_manager/commonlib.py:12: RuntimeWarning: Python C API version mismatch for module elxml: This Python has API version 1012, module elxml has version 1011. Could this be because the compilation was made against 2.2 and run from 2.3? If so, is there a way to force my module compilation against 2.3? Thanks -John From dcengija_IQ_Filter at inet.hr Wed Nov 26 02:06:15 2003 From: dcengija_IQ_Filter at inet.hr (Davor Cengija) Date: Wed, 26 Nov 2003 08:06:15 +0100 Subject: Extracting email attachment when is_multipart() is False References: <87r7zw9ur6.fsf@pobox.com> Message-ID: John J. Lee wrote: > "Davor Cengija" writes: >> This is a multi-part message in MIME format. >> >> ------=_NextPart_000_0026_01C3B347.DBEA9660 >> Content-Type: text/plain; > [...] > > You seem to be missing the RFC 822 headers (From, To, Subject, etc.). Yes, that's true. The question is if it's easier to write a parser for that kind of messages or to force the message producing application to output the headers as well. We'll see... Thanks From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Mon Nov 17 11:08:57 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Mon, 17 Nov 2003 19:08:57 +0300 Subject: line number var like perl's $.? In-Reply-To: References: Message-ID: Matthew Wilson wrote: > One thing I miss about perl was the builtin $. variable that gets > increased after each call to perl's file iterator object. For example: > > while ( my $line = ) { > print "$. $line"; > } > > or, more perlish: > > while () { > print "$. $_"; > } > > Tracking line numbers is such a common thing to do when parsing files > that it makes sense for there to be a builtin for it. > > Is there an equivalent construct in python? Or are people doing > something like this: > > linenum = 0 > for line in open('blah.txt'): > linenum += 1 > print linenum, ". ", line > > Better ideas are welcomed. If you upgrade to 2.3, you can use enumerate built-in: for no, line in enumerate(file('blah.txt')): print no, line should work (I didn't test it however) Otherwise you can create enumerate yourself: from __future__ import generators def enumerate(it): n = 0 for e in it: yield n, e n += 1 Or to use xrange trick: import sys for no, line in zip(xrange(0, sys.maxint), file('blah.txt')): print no, line (not tested either). regards, anton. From daniels at dsl-only.net Mon Nov 3 15:20:33 2003 From: daniels at dsl-only.net (sdd) Date: Mon, 03 Nov 2003 12:20:33 -0800 Subject: String substitution -- reactions? Message-ID: <3fa6c6a2$1@nntp0.pdx.net> Here's a sample of how to do string substitution for a string with double quotes around the names to be substituted. The following is 2.3 code, but 2.2 code is also listed in the recipe at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/231347 def dequote(text, dictionary): """Replace quoted parts of string with dictionary entries.""" parts = text.split('"') parts[1::2] = [dictionary[word] for word in parts[1::2]] return ''.join(parts) So, dequote('''Dear "user", we here at "provider" want to ....''', dict(user='Resident', provider='Att.Net')) can be used to fill out forms (or prepare html pages). If you need to be able to include double quotes, simply make sure that the dictionary provided get an entry like the one in {'':'"'}, then using doubled double quotes may be used to represent quote marks, as is common in a number of languages. -Scott David Daniels Scott.Daniels at Acm.Org From tjreedy at udel.edu Thu Nov 27 13:00:03 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Nov 2003 13:00:03 -0500 Subject: Extract double in binary file References: Message-ID: "Pascal" wrote in message news:e567c03a.0311270107.9fc983d at posting.google.com... > Some precisions: ('examples': 'precisions' does not work here in English) > 0.00 > 00-00-00-00-00-00-7F-00 > 1.00 > 00-00-00-00-00-00-00-81 > 2.00 > 00-00-00-00-00-00-00-82 > 3.00 > 00-00-00-00-00-00-40-82 > 4.00 > 00-00-00-00-00-00-00-83 > > 10.00 > 00-00-00-00-00-00-20-84 > 1000.00 > 00-00-00-00-00-00-7A-8A > > 1.11 > 14-AE-47-E1-7A-14-0E-81 The only obvious pattern I see is that 2**0 -> 81, 2**1->82, ... 2**9->8A (where A==10) ie, for non-zero, last byte is 81 + exponent of largest power of two, which seems like type of float, and first 6 are 0 if integral. May be proprietary format. TJR From SEE_AT_THE_END at hotmail.com Wed Nov 5 01:49:08 2003 From: SEE_AT_THE_END at hotmail.com (Georgy Pruss) Date: Wed, 05 Nov 2003 06:49:08 GMT Subject: XORing long strings opimization? References: <3ISpb.24447$BD3.4566933@juliett.dax.net> <%AWpb.24470$BD3.4569022@juliett.dax.net> Message-ID: Well, nothing to add actually, but my results: import string import array def xorstring0(s1,s2): # the original method # argument tests were here # Create lists l1 = map(ord, s1) l2 = map(ord, s2) # Xor it all together xorlist = [] xorlist = [chr(x ^ y) for (x, y) in zip(l1, l2)] return string.join(xorlist,"") # Backward compatible def xorstring1(s1,s2): xorlist = [chr(ord(x) ^ ord(y)) for (x, y) in zip(s1, s2)] return string.join(xorlist,"") # Backward compatible def xorstring2(s1,s2): xorlist = [chr(ord(s1[i]) ^ ord(s2[i])) for i in range(len(s1))] # range return string.join(xorlist,"") # Backward compatible def xorstring3(s1,s2): xorlist = [chr(ord(s1[i]) ^ ord(s2[i])) for i in xrange(len(s1))] # xrange return string.join(xorlist,"") # Backward compatible def xorstring4(s1,s2): a1 = array.array("B", s1) a2 = array.array("B", s2) for i in xrange(len(a1)): a1[i] ^= a2[i] return a1.tostring() s1 = 'abcew'*200000 s2 = 'xyzqa'*200000 fns = [ xorstring0, xorstring1, xorstring2, xorstring3, xorstring4 ] # check if all works OK for some short data -- # protection from some rough error or typo sx = fns[0]( s1[:100], s2[:100] ) for fn in fns: assert sx == fn( s1[:100], s2[:100] ) import time tms = [60] * len(fns) # assume some unreal big times for n in range(30): # loop 30 times for i in range(len(fns)): tb = time.time() sx = fns[i]( s1, s2 ) # do it! tm = time.time() - tb tms[i] = min( tms[i], tm ) for i in range(len(fns)): print "fn%d -- %.3f sec -- %.2f" % (i,tms[i],tms[i]/tms[-1]) # fn0 -- 5.578 sec -- 6.37 # fn1 -- 4.593 sec -- 5.25 # fn2 -- 2.609 sec -- 2.98 # fn3 -- 2.531 sec -- 2.89 # fn4 -- 0.875 sec -- 1.00 BTW, for the same million char strings, a C function runs 0.0035 sec, or 250 times faster! G-: From fjh at cs.mu.oz.au Tue Nov 11 10:29:59 2003 From: fjh at cs.mu.oz.au (Fergus Henderson) Date: Tue, 11 Nov 2003 15:29:59 GMT Subject: Python from Wise Guy's Viewpoint References: <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <3F9D5D21.2060408@ps.uni-sb.de> <3fb097fe$1@news.unimelb.edu.au> <3fb0c2cd$1@news.unimelb.edu.au> Message-ID: <3fb10071$1@news.unimelb.edu.au> Pascal Costanza writes: >b) documentation > >Documentation can be handled well with comments and well-chosen names. Certainly it _can_ be, but keeping good, up-to-date documentation is a difficult task. In my experience, average programmers do a better job of documentation in languages which encourage explicitly declaring the types of interfaces than in those which do not. -- Fergus Henderson | "I have always known that the pursuit The University of Melbourne | of excellence is a lethal habit" WWW: | -- the last words of T. S. Garp. From eric.brunel at pragmadev.N0SP4M.com Mon Nov 10 09:33:24 2003 From: eric.brunel at pragmadev.N0SP4M.com (Eric Brunel) Date: Mon, 10 Nov 2003 15:33:24 +0100 Subject: Talking through pipes interactively (on win32) References: Message-ID: Jane Austine wrote: > I need to control a command line program via python. > > I first tried popen2 and 3 but I couldn't find a way to talk to the > subprocess interactively; that is, read some and then write some, and > read some more again... (suppose controlling an interactive shell > program) When I try this with popen family, it just hangs. I have to > close one pipe before reading from the other. > > I know that there is a wonderful thing called Expect, but it's not > available on my machine(win32). > > Can anyone help me out? Can you please post a small script showing the exact problem you have? Communicating with a program via pipes works on Windows: we do it all the time. It can be pretty complicated, but it can be done. -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From duncan at NOSPAMrcp.co.uk Wed Nov 5 04:56:24 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 5 Nov 2003 09:56:24 +0000 (UTC) Subject: Why no try-except-finally ? References: <20031105044006.29195.00000177@mb-m22.aol.com> Message-ID: keflimarcusx at aol.comNOSPAM (KefX) wrote in news:20031105044006.29195.00000177 at mb-m22.aol.com: > I bring this up because I originally wrote this in my game code: > > try: > PlayGame() > except: > err_msg = "FATAL ERROR: " + sys.exc_info()[0] > logger.critical(err_msg) > finally: > DeInit() > > In other words, if something went wrong, an error message would be > printed out to the log, and then in either case, my game would try to > exit gracefully. Of course, rewriting it without the finally: is no > big deal (just write DeInit() in the except block and again after the > block)...in this case. What if I wanted to execute a bunch of lines? > Code duplication is bad. Hang on, there is something wrong with what you say here. If you really had the code you wrote above, and you put DeInit() in the except block and again after it then any time an exception was thrown you would call DeInit twice. Is this *really* what you wanted? This code would reliably call DeInit every time, whether or not an exception was thrown, without code duplication: try: PlayGame() except: err_msg = "FATAL ERROR: " + sys.exc_info()[0] logger.critical(err_msg) DeInit() -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From dietrich at zdome.net Wed Nov 19 04:47:26 2003 From: dietrich at zdome.net (Dietrich Epp) Date: Wed, 19 Nov 2003 01:47:26 -0800 Subject: Reading a Bitstream In-Reply-To: <653b7547.0311181810.786118af@posting.google.com> References: <653b7547.0311181810.786118af@posting.google.com> Message-ID: <61B3CC96-1A75-11D8-910E-0003934ACDEC@zdome.net> On Nov 18, 2003, at 6:10 PM, Patrick Maupin wrote: > Dietrich Epp wrote: > >> Are there any good modules for reading a bitstream? Specifically, I >> have a string and I want to be able to get the next N bits as an >> integer. Right now I'm using struct.unpack and bit operations, it's a >> bit kludgy but it gets the right results. > > As Miki wrote, the array module will probably give you what > you want more easily than struct.unpack. If you need more > help, just post a few more details and I will post a code > snippet. (As to the rest of Miki's post, I'm not sure that > I really want to know what an "Upnacker" is :) Maybe I should clarify: I need to read bit fields. Neither are they aligned to bytes or do they have fixed offsets. In fact, in one part of the file there is a list of objects which starts with a 9 bit object type followed by fields whose length and number depend on that object type, ranging from a dummy 1-bit field to a tuple of four fields of length 9, 5, 8, and 8 bits. I looked at the array module and can't find what I'm looking for. Here's a bit of typical usage. def readStuff(bytes): bits = BitStream(bytes[2:]) isSimple = bits.Get(1) objType = chr(bits.Get(8)) objType += chr(bits.Get(8)) objType += chr(bits.Get(8)) objType += chr(bits.Get(8)) count = bits.Get(3) bits.Ignore(5) if not isSimple: objId = bits.Get(32) bytes = bytes[2+bits.PartialBytesRead():] return bytes, objType This is basically the gamut of what I want to do. I have a string, and create a bit stream object. I read fields from the bit stream, some may not be present, then return an object and the string that comes after it. The objects are aligned to bytes in this case even though their fields aren't. I can't figure out how to get array to do this. Array does not look at all suited to reading a bit stream. struct.unpack *does* work right now, with a lot of help, I was wondering if there was an easier way. From mwh at python.net Mon Nov 24 12:21:49 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 24 Nov 2003 17:21:49 GMT Subject: Why should input(prompt="hello:") fail? References: <37ba82ff.0311240831.6e0dfba7@posting.google.com> Message-ID: wongwung at hotmail.com (zhi) writes: > Really confused, when I use keyword style argument as following: Often builtin functions don't take keyword arguments. There's been a gentle move towards supporting them over the years, but there are many, many places that haven't been reached. Cheers, mwh -- Usenet is like a herd of performing elephants with diarrhea -- massive, difficult to redirect, awe-inspiring, entertaining, and a source of mind-boggling amounts of excrement when you least expect it. -- spaf (1992) From docelm at web.de Mon Nov 24 03:01:53 2003 From: docelm at web.de (Christian Lehmann) Date: 24 Nov 2003 00:01:53 -0800 Subject: update a word-bookmark with the win32.com extension References: <48bafd6d.0311180542.5f7582ea@posting.google.com> Message-ID: <48bafd6d.0311240001.1e2e9095@posting.google.com> > > Please include the error message in your postings. Here is the error messages: Traceback (most recent call last): File "D:\DataFinder\python\readFormFields.py", line 95, in ? date = searchField("date") File "D:\DataFinder\python\readFormFields.py", line 70, in searchField field.Text = "Hell" File "C:\Python\lib\site-packages\win32com\client\__init__.py", line 377, in _ _setattr__ apply(self._oleobj_.Invoke, args + (value,) + defArgs) pywintypes.com_error: (-2147352567, 'exception error occured.', (0, 'Microsof t Word', 'The area can?t be deleted', 'C:\\Programs\\Microsoft Office\\Office10\\1031\\wdmain10.chm', 25508, -2146822260), None) From gh at ghaering.de Tue Nov 4 21:29:36 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 05 Nov 2003 03:29:36 +0100 Subject: SMTP Authentication In-Reply-To: <20031104181955.GA16137@intarweb.us> References: <20031104181955.GA16137@intarweb.us> Message-ID: <3FA86090.2000409@ghaering.de> Jp Calderone wrote: > On Mon, Nov 03, 2003 at 09:41:37PM +0100, Achim Domma wrote: > >>Hi, >> >>I try to authenticate via script to my mail server. I found some hints via >>google, that SMTP authentication is a problem, but no solution. Using >>set_debuglevel(1), I can see something like that: >> >>[snip transcript] >> >>Can somebody give me a hint on how to encode the pwd? Or another way to send >>mail, if the server requires authentication? > > > http://twistedmatrix.com/documents/api/twisted.protocols.imap4.CramMD5ClientAuthenticator.html > > [...] Aha. Twisted is the solution for everything, right? SMTP.login() should work perfectly ok. I'd need a transcript *and* the real username and password to debug this, though. But chances are that the problem is at the SMPT *server* end, not the client end. You could try to force the PLAIN login method instead of the CRAM-MD5 authentification method, by doing something like: import smtplib s = smtplib.SMTP("mylene.ghaering.de") s.ehlo() s.esmtp_features["auth"] = "LOGIN PLAIN" s.debuglevel = 5 s.login("myusername", "mypassword") Let me know if this helps. -- Gerhard From usenet_spam at janc.invalid Sun Nov 2 23:48:48 2003 From: usenet_spam at janc.invalid (JanC) Date: Mon, 03 Nov 2003 04:48:48 GMT Subject: Finding the "home" folder [Linux/Windows] References: Message-ID: Andrew schreef: > windows 98/me: c:\my documents\username Many Win9x systems run without a "user", so there is no username then... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From mmoum at woh.rr.com Tue Nov 4 19:55:57 2003 From: mmoum at woh.rr.com (DoubleM) Date: Wed, 05 Nov 2003 00:55:57 GMT Subject: Tkinkter - how can I control where the main widget appears Message-ID: Given the following trivial program: from Tkinter import * root = Tk() l = Label(root, text = "Hi There") l.pack() root.mainloop() How can I control where the main window appears on the screen? Ideally, I would like to center it. Thanks for your help, Mike From jjl at pobox.com Fri Nov 7 07:38:59 2003 From: jjl at pobox.com (John J. Lee) Date: 07 Nov 2003 12:38:59 +0000 Subject: ANN: PyKDE now does KDE plugins References: Message-ID: <87sml01hgc.fsf@pobox.com> Jim Bublitz writes: [...] > required. This is the first in what's planned to be a number of > extensions for PyKDE that allow plugins and related objects to > be created entirely in Python; David Boddie is nearing release > of modules for authoring KParts for export (PyKDE already > imports KParts), KDE Control Center modules, and IOSlaves. > > Future plans include allowing QWidget subclasses created in > Python to be imported into Qt Designer with complete > functionality, and possibly Python scripting and plugins for KDE > apps like KOffice and Kontact. The underlying mechanisms and > code are similar in all cases. [...] Wow, sounds like impressive stuff. How does it work? Is there a standard .so proxy that can be used by all Python plugins? What sort of memory footprint do these plugins have? > In some cases, specific .so libs will still be required (depends > on the plugin loader), but the Python modules will include > autogeneration of the necessary C++ code, along with installers > to simplify the task of making the plugins available. What makes the difference between all-Python and needing a bit of C++ here? John From soundinmotiondj at yahoo.com Thu Nov 6 14:42:58 2003 From: soundinmotiondj at yahoo.com (Stan Graves) Date: 6 Nov 2003 11:42:58 -0800 Subject: Please Help Explain References: Message-ID: <3d6c6fc3.0311061142.70010150@posting.google.com> "Jakle" wrote in message news:... > +++++++++++++++++++++++++++++++++++++++ > # penny.py 11-05-03 > > days = raw_input("How many days: ") > > def calc(n, days): > i = 1 > while i <= days: > n = n*2 > i = i+1 > return n/float(100) Technically, the return should be: return (n-1)/float(100) The point is to sum the total, and your method over estimates the sum by 1. You can verify this by running the program for 2 days and looking at the total. If the pay is one penny on the first day, and two pennies on the second day - the the sum at the end of two days is 3 cents...not four cents as suggested by the above code. --Stan Graves stan at SoundInMotionDJ.com http://www.SoundInMotionDJ.com > > print calc(1, int(days)) > +++++++++++++++++++++++++++++++++++++++ From haris.bogdanovic at zg.htnet.hr Sun Nov 2 13:11:30 2003 From: haris.bogdanovic at zg.htnet.hr (Haris Bogdanovic) Date: Sun, 02 Nov 2003 19:11:30 +0100 Subject: simple echo server In-Reply-To: References: <3fa3fab9$0$58702$e4fe514c@news.xs4all.nl> <3FA4284A.6010701@zg.htnet.hr> <3fa4395a$0$58698$e4fe514c@news.xs4all.nl> <3FA4CB41.8080306@zg.htnet.hr> Message-ID: <3FA548D2.6080900@zg.htnet.hr> Simon Bayling wrote: > Haris Bogdanovic wrote in > news:3FA4CB41.8080306 at zg.htnet.hr: > > >>>>It's the example from python docs (socket section). If you have >>>>somewhere your personal user account you can try it aswell. >>> >>I ment telnet account. Is that the place where people normally put >>their server part of the application or can I put somewhere else (is >>there a common way to do this) ? > > > Telnet account to what? > You can put it anywhere you can run Python code on an operating system > with TCP/IP. > > >>>>Tell me what you managed to do. > > > I copied the server example and ran it. > I copied the client example, altered the HOST to 127.0.0.1 and ran it. > > It connected and sent/recieved "Hello, world", then finished. > > Just as it should do. > > Now, what error message are you getting? > > -- Simon. It works for me fine too, when client and server execute on the same computer (mine) but I get "access denied" error when I put server.py on my free telnet account ("m-net.arbornet.org"). Is that the place where I should put server.py if I want to implement chess server or is there some other common place where servers are put ? Thanks Haris From __peter__ at web.de Tue Nov 4 14:50:06 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Nov 2003 20:50:06 +0100 Subject: XORing long strings opimization? References: <3ISpb.24447$BD3.4566933@juliett.dax.net> Message-ID: Noen wrote: > Oh, didnt notice that as I wrote it. Thanks... > Anyway, this is how it should be. > > def XOR(s1,s2): > """ XOR string s1 with s2 """ > output = "" > # Argument check > if (type(s1) and type(s2)) != type(""): > raise TypeError, "Arguments are not strings" > if len(s1) != len(s2): > raise ValueError, "Size differs in strings" > # Xoring > for i in range(len(s1)): > output += chr(ord(s1[i]) ^ ord(s2[i])) > return output Oops, I missed one: >>> xor2.XOR(1, "") Traceback (most recent call last): File "", line 1, in ? File "xor2.py", line 7, in XOR if len(s1) != len(s2): TypeError: len() of unsized object Did you expect this? Peter From gte181u at prism.gatech.edu Sun Nov 2 18:54:45 2003 From: gte181u at prism.gatech.edu (Vamsi Mudrageda) Date: Sun, 02 Nov 2003 18:54:45 -0500 Subject: Thx All In-Reply-To: References: Message-ID: Thx everyone. I was really surprised by all the quick responses. Ok, to sum up my understanding. I can freely develop and distribute python/pyqt/qt programs on my Linux, but I must make the program freely available, ie. GPLed. No problem there. On Windows however, I need to buy a license from TrollTech if I want to use their latest offerings (or I can explain my situation to them and let them decide) as they no longer offer the non-commercial license for Windows. Once I get the license, I can make executables that can run on other Windows w/o that user having to buy a license for qt or pyqt. Did I miss anything? The windows part is a little disappointing (I am a college student, can't really afford the licenses... tho BlackAdder looks good), and I hope TT will change something in the future. Qt looks great (according to KDE), and since my program is mainly for Linux, I guess I will head in that direction. Again, thx all. PS. I will also write my situation to TrollTech as they suggested in their "we no longer support the non-commercial license" webpage and report their response back here. From eppstein at ics.uci.edu Mon Nov 24 17:15:37 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 24 Nov 2003 14:15:37 -0800 Subject: Adding new methods at runtime to a class References: Message-ID: In article , Roy Smith wrote: > > Before we send you into what most would consider black magic in Python, you > > should explain why you want to. > > > > In most cases, this is *not* what you want to do - there are better, more > > elegant and much more Pythonic ways of doing it. > > > > Tim Delaney > > > > Why is it unpythonic to add methods at runtime? That's the nature of a > dynamic language. If foo.bar doesn't have to exist until the moment > it's evaluated, why should foo.bar() have to? Or maybe a better way to > ask it is why should foo.bar have to be callable at any other time than > when you evaluate foo.bar()? > > I would say that the fact that all of a class's methods have to be > declared at once is itself somewhat unpythonic. Black magic? It's not very difficult... >>> class foo:pass ... >>> f=foo() >>> def printme(self): print "I am " + repr(self) + "." ... >>> foo.method = printme >>> f.method() I am <__main__.foo instance at 0x40aa8>. And, just to verify that it really is a method and not just a function: >>> foo.method(1) Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method printme() must be called with foo instance as first argument (got int instance instead) Ok, the error message doesn't use the right name but in other respects it works as you would expect. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From dthierbach at gmx.de Thu Nov 6 10:00:37 2003 From: dthierbach at gmx.de (Dirk Thierbach) Date: Thu, 6 Nov 2003 16:00:37 +0100 Subject: Explanation of macros; Haskell macros References: Message-ID: Coby Beck wrote: > The problem was a fairly ordinary one and is easy to describe at a high > level. The server existed to control a complicated configuration process > and later process data according to the result. It was a simple socket > server and I got to dictate the form of the commands and arguments. > Ultimately, it boiled down to (funcall command client-session args). > I would be very happy to learn other approaches, there are always > many ways to skin a cat. (how un-PC is that saying these days ;) Here's a very simplified example how to do something similar in Haskell. I probably missed lots of details (I don't know how the session object works, and have no idea what the session-blueprints are, I have no details about the send and receive commands, and so on), but maybe it should give you an idea. The main task is to define a function that implements a server command, given some constraints and the code for the command. The command should work on the arguments received over the socket. So we need some code that does the marshalling und un-marshalling of the data. Here, I will cheat and just use the "Dynamic" library to simulate that. In reality, one could use a similar approach to write marshalling routines, or use the standard read and show routines, or whatever. I'll use the functions toDyn :: Typeable a => a -> Dynamic that converts any "typeable" value into a Dynamic value, and fromDynamic :: Typeable a => Dynamic -> Maybe a which converts it back, or fails with a value of "Nothing" if the type doesn't match. The class Typeable will need instances for all the types we want to convert. Let's assume there is a type "Session" for sessions. Then the type of define_server_cmd will be define_server_cmd :: Typeable a => (a -> Bool) -> (Session -> a -> IO ()) -> (Session -> Dynamic -> IO ()) which pretty much expresses out expectations about this function given above. The implementation is straightforward: define_server_cmd constraints code session dyn_args = do maybe (error "Wrong type of arguments") (\args -> if constraints args then code session args else error "Constraints violated" ) (fromDynamic dyn_args) Your set-field-sequence example would probably look something like (I am guessing a lot here) set_field_sequence = define_server_cmd constraints code where constraints field_list = all (`elem` logical_types) field_list code session field_list = do let field_sequence = source_blueprint session state = get_state session writeIORef field_sequence field_list send session (show state) You don't need the first constraint, because the unmarshalling will check if the arguments are indeed a list. I am not sure if the second constraint is also a type check or if it checks the contents or names of the fields. As another example, let's define the code for a print command seperately (so it is testable), and then make a server command out of it with the constraint that the first argument is less then 100: print_cmd_code :: Session -> (Integer, String) -> IO () print_cmd_code session (x, y) = print ("First=" ++ show x ++ ", Second=" ++ show y) print_cmd = define_server_cmd (\(x, _) -> x < 100) print_cmd_code As I said, this is a very simple example, so let's see what is missing. > So I needed (wanted) a way to, in one stroke, > - define the method, properly specialized on the session object Should work. > - ensure it became an allowed function to call Should work. > - define a way to gather the arguments needed from the client > according to number of args and the type of each. Should work. Note that the compiler automatically figures out at compile time which code to combinbe to marshall or unmarshall the "dynamic" value, and verifies the type as well. No need to do this explicitely. > - provide a facility for arbitrarily complex validation of any > of the arguments or combinations thereof. Should work. > - ensure that any changes, enhancements or additions to > argument passing would require a single point of change in my code. Should work. One potential drawback of the above approach is that you have to write down the argument list twice, once for the contraint check, and once for the actual code. But since one might want to do pattern matching on the arguments, this might be exactly the right thing and not a drawback. The type checker will verify that the arguments are of the same for both parts. > Additional benefits: > - automatically provided information to a kind of "help" facility. I didn't see that in your code, but one could probably handle this in the same ways as errors below. > - allowed for very informative error messages, both in the debug > environment and as returned data for clients. I kept the error handling *very* simple by just throwing exceptions. In reality, this would be handled by an error function that sends back the error message. Type errors could be automatically handled. It is of course not possible to send back sourc code as a string without using a macro; and while error messages of this kind are arguably informative to someone who knows lisp, they might be very confusing to someone who doesn't :-) So I'd add explicit error messages, and maybe a few infix functions as syntactic sugar to write them down nicely. > - simplified the main server loop while remaining completely flexible The main loop would need to lookup the server functions (which all have the same type), and then execute the functions without unmarshalling the arguments, since that is done inside the function. Also simple and flexible. > I did have to define a set of safe-read functions for lists and > integers and strings etc for a combination of security and > timing-out reasons. Yes. This code would go in the typeclasses mentioned at the beginning, and as you say, you'd need that in Lisp, too. > But the grammar was just s-expressions. The grammar is completely up to the coder, be it s-expressions, XML, or whatever. However, it should include the type of the arguments passed over the socket. > I actually have macros I use now that generate strings of SQL code, > some of it as format strings that will be used at a later stage of > processing (a "format string" would be something like "SELECT NEW.~A > FROM ~A WHERE ~A > 3" where the ~A's get filled with variables > later) It might be interesting for you to have a look at HaXML or one of the other XML libraries that do a similar thing with XML, using only HOFs. I don't see any reason why SQL couldn't be handled in a similar way. > But back to macros, and really any language feature, they are all > just tools and it is always a judgment call as to what the best tool > for a job is and judgements are always subjective. It is very hard > to convince anyone that a tool they are completely unfamiliar with > is the best one for some problem they never thought they had. Amen to that. - Dirk From peter at engcorp.com Tue Nov 4 16:45:40 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 04 Nov 2003 16:45:40 -0500 Subject: Selling Python Software References: Message-ID: <3FA81E04.21176B0E@engcorp.com> Will Stuyvesant wrote: > > I guess I am going to send them an MIT licence (although I am afraid > those licences are pretty useless in The Netherlands), the .pyc files > for the algorithm and the utility modules, and a .py file for the main > program. No need even for that .py file, is there? You can easily execute a .pyc file directly if the .py doesn't exist. To create it, easiest way is just to do "import mymainmodule" from the interactive prompt, then copy the resulting .pyc somewhere else. Alternatively, keep you .py as the main entry point, but do nothing inside it except import another module and execute code in it. But if you can do that, then invoking that module directly is easy too: "python -c 'import main; main.main()'" does the trick... -Peter From jtanis at charter.net Wed Nov 26 03:24:05 2003 From: jtanis at charter.net (James Tanis) Date: Wed, 26 Nov 2003 03:24:05 -0500 Subject: Newbi q: show prog In-Reply-To: References: Message-ID: <1069835044.25589.3.camel@localhost.localdomain> Open console first.. go to run and type 'command', that should start the session then you just cd to your programs directory and do the python file.py. On Wed, 2003-11-26 at 03:07, Rony wrote: > Christoffer T wrote on 25 Nov 2003 23:27:17 -0800 in : > > You propably have an error in your code. > To check: > Open a dos window in your program directory > type python file.py > you wil see the output and the window won't close > > > > Sorry for bad subjekt. > > > > I have just started to learn programing, and python sound like a god > > choice. > > But there is something I do not understand. > > I want to write the code in notepad, and then open in a window. I use > > win98. > > I have tried to write "python file.py" in run, but it just very fast > > open and close dos window. So what should I do to get to show the > > program. > > I know that I can write directly in python but that only is good for > > testing small bits right. > > I hope u can help me get going, cours it all sound exiting making > > programs. -- James Tanis jtanis at charter.net From Dennis.Benzinger at gmx.net Tue Nov 25 17:39:37 2003 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Tue, 25 Nov 2003 23:39:37 +0100 Subject: timeit.repeat() inaccuracy on W2K? Message-ID: <3fc3da6d$1@news.uni-ulm.de> I just played around with the new timeit module. Using the following code I get some strange results: import timeit def test(s): result = 0 for c in s: result += ord(c) return result t = timeit.Timer("test('dennisbenzinger')", "from __main__ import test") print t.repeat(number=50000) Most of the time I get a result like >> [3.3263199652469799, 3.3338471789012294, 3.3557058229467716] with all execution times are about 3. But sometimes I get something like >> [3.3410785448988629, 4802.7882074397721, 1203.1983464378854] where one or two execution times are much higher than the other ones, although the program took about the same time to execute and certainly not some thousand times as long... I'm running Python 2.3.2 on Windows 2000 with ServicePack 4 From newsgroups at jhrothjr.com Wed Nov 26 07:22:48 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 26 Nov 2003 07:22:48 -0500 Subject: Pychecker under Windows References: <153fa67.0311252016.2e02b575@posting.google.com> Message-ID: "Steve Holden" wrote in message news:iEXwb.1475$US3.586 at okepread03... > "Kylotan" wrote ... > > Is there a practical way to use Pychecker in Windows? It doesn't work > > under IDLE. (In fact, it seems to end up breaking everything, and > > every subsequent statement and expression I execute gets ignored.) > > Running it from the Python interpreter in DOS means everything scrolls > > off the screen. Ideally I'd like to redirect it to a file, or be able > > to use it in IDLE. > > > > You can redirect python output to a file from the Windows command line. The > only caveat is for *some* command processors (NT in particular, IIRC) output > redirection only works if you explicitly call the python interpreter (i.e. > use the command "python prog.py > file.out") rather than implicitly call it > (i.e. use the command "prog.py > file.out"). Alternatively, if you're running under an NT derivative, use the .cmd command interpreter rather than the .bat command interpreter. Then you get that nice scroll bar so you can see what scrolled off. Works great on XP at least. John Roth > > regards > -- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/pwp/ > "I'd spoll my own name wring if I didn't have a spilling chocker" > > > > From peter at engcorp.com Tue Nov 11 11:23:20 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Nov 2003 11:23:20 -0500 Subject: What do you think of this Python logo? References: <8g12rvo9nagi57vng3s00gdg6er9pq4ktu@4ax.com> Message-ID: <3FB10CF8.61CB72FD@engcorp.com> John Roth wrote: > > "G.A." wrote in message > news:8g12rvo9nagi57vng3s00gdg6er9pq4ktu at 4ax.com... > > On 11 Nov 2003 20:26:08 +1100, Tim Churches > wrote: > > > > > > >Much better to stick to a Monty Python-inspired theme, incorporating a > > > > I understand the desire to incorporate fun into Python, but I fear that > any > > Monty Python inspired logo will connote frivolity. I don't think that's > > the image that should be conveyed. > > > > My initial take on the logo in the base note is that I like the cleaness > of > > it. However, it took too much effort to recognize the outer loop as a > > snake, let alone a python. I kind of like the idea of a snake wrapped > > around the P. > > A snake wrapped around a failed project would be even better, but > I will admit that I can't figure out a good, immediately recognizable icon > for a failed project... Maybe the Netscape logo? (ducks and runs) -Peter From jbublitzno at spamnwinternet.com Sun Nov 9 02:06:20 2003 From: jbublitzno at spamnwinternet.com (Jim Bublitz) Date: Sun, 09 Nov 2003 07:06:20 GMT Subject: ANN: PyKDE now does KDE plugins References: <87sml01hgc.fsf@pobox.com> <87llqrgiva.fsf@pobox.com> <9y9rb.3612$xr.997430341@twister2.starband.net> <87wuaainlg.fsf@pobox.com> Message-ID: <6Ilrb.3754$yd6.1052428423@twister2.starband.net> John J. Lee wrote: > Have you seen GCC-XML and pyste (part of Boost Python)? I've looked at both just out of curiousity, but not in enough detail to say anything intelligent about either. I'm very comfortable with sip, and from that bias didn't see anything that would make me want to switch methods. The kde-bindings people are using gcc-xml for "Smoke" I believe, which as I understand it is kind of a generalpurpose multi-language bindings generator. Jim From ulysses_dm at yahoo.com.cn Sun Nov 23 08:27:55 2003 From: ulysses_dm at yahoo.com.cn (ulysses) Date: 23 Nov 2003 05:27:55 -0800 Subject: gettext crazy question References: <43e3984e.0311201935.64aac584@posting.google.com> Message-ID: <43e3984e.0311230527.74eed7a3@posting.google.com> martin at v.loewis.de (Martin v. L?wis) wrote in message news:... > ulysses_dm at yahoo.com.cn (ulysses) writes: > > > So I debug gettext module. I find following interest question. > > -=gettext line 154=- > > buf = fp.read() > > > > I sure fp(file object) has open. > > > > It can't read all binary code. buf 's lengh smaller than real file. > > exp ,whole file 1000 byte. gettext only read 187 . > > It looks like the file is opened in text mode, not in binary mode. > > Did you, by chance, open the file yourself? You should use binary > mode, then. > > Regards, > Martin I use same statement open file. different is MO file. when don't fill some line, gettext can open mo normally. From StefanoZAP.THIS at gaburri.net Thu Nov 6 13:45:16 2003 From: StefanoZAP.THIS at gaburri.net (stefanogaburri) Date: Thu, 06 Nov 2003 19:45:16 +0100 Subject: [XPOST] [REQ] open source multimedia authoring tools? In python maybe? In-Reply-To: References: Message-ID: Kevin Ollivier wrote: > Hi, > > I'm working on just what you are asking for. =) It's called > EClass.Builder and it basically is for creating HTML-based e-learning > modules for delivery via Internet/CD-ROM. Yay! It'll save me some hand-coding :) Seriously, I'd love to check it out and maybe contribute; I'm gonna subscribe now to the mailing list; I'll see you there... I wonder why I didn't find it on sourceforge? I tried every possible keyword from "authoring" to "CBT" to "e-learning" but Eclass didn't come out. Oh well, that's what USenet is for I guess (besides flame wars, of course) thanks, S From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Nov 10 16:50:30 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 10 Nov 2003 22:50:30 +0100 Subject: cgi module doesn't process query string values with POST, old bug report Message-ID: <3fb00826$0$58716$e4fe514c@news.xs4all.nl> Hello I've got a nuisance with the cgi module. (Python 2.3.2) When processing a HTTP POST request, it ignores the query string parameters that may also be present. I.e. only the parameters from the POST body are processed. I've looked at a rather old bug report on SF; http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=411612 but that bug is closed. The last comment is from Steve Holden, and it says "...My approach will be to have the new functionality depend on the provision of additional keyword arguments..." Can somebody comment on this? (Steve?) I can't seem to find any of this logic in the current (2.3.2) cgi.py module. Is it in there somewhere or has this bug been forgotten? I have now added some code myself after creating a FieldStorage object, to parse any additional query args using cgi.parse_qsl. This way any query args are added to my form fields, possibly overwriting the fields that were sent in the POST body. But Steve's comment in the old bug report made me wonder why the standard cgi module doesn't include this possibility. --Irmen de Jong From martin at v.loewis.de Wed Nov 19 13:55:14 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 19 Nov 2003 19:55:14 +0100 Subject: PEP263 and execfile() References: Message-ID: "Denis S. Otkidach" writes: > What about warnings.filtererrors() in future versions of Python > when this warning will be turned into error? I guess it's OK as > temporal hack but it's not a solution of the problem. > May be execfile and compile functions should have optional > encoding parameter? I'm not sure about execfile, but compile > must have it. By the time the warning will be turned into an error, nearly all files will have an encoding declaration, or only contain ASCII. Then, it won't be a problem that there is an exception if there is an error in a file executed with execfile. Regards, Martin From max at alcyone.com Fri Nov 21 16:55:55 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 21 Nov 2003 13:55:55 -0800 Subject: Exceptions, assigning a tuple References: <3fbdb857$0$1727$5a62ac22@freenews.iinet.net.au> <3FBDBA3E.23D54A7C@alcyone.com> <3fbdbbdf$0$1739$5a62ac22@freenews.iinet.net.au> <3FBDBDED.D37C503F@alcyone.com> <3fbdc12f$0$1734$5a62ac22@freenews.iinet.net.au> <3FBDC541.63DA3821@alcyone.com> Message-ID: <3FBE89EB.7AA3FFE7@alcyone.com> "Gon?alo Rodrigues" wrote: > Hmm. More generally you have to implement __iter__ for a class to be > iterable, be in for loops => can be list-ified, tuple-ified, > etc.-ified. Defining an explicit __iter__ method is another way, and is particularly useful when you're dealing with a class whose iteration can be encapsulated easily in a separate iterator object that you can return (and you're running Python 2.2 or up). That isn't always the case. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ Golf is a good walk spoiled. -- Mark Twain From JTesser at nbbc.edu Tue Nov 25 07:10:15 2003 From: JTesser at nbbc.edu (Jason Tesser) Date: Tue, 25 Nov 2003 06:10:15 -0600 Subject: Web Authentication to AD Message-ID: <04875CB4331F0240A0AD66F970978651011376C8@paul> Has nobody tried to do this kind of thing? -----Original Message----- From: python-list-bounces+jtesser=nbbc.edu at python.org [mailto:python-list-bounces+jtesser=nbbc.edu at python.org]On Behalf Of Jason Tesser Sent: Monday, November 24, 2003 7:00 AM To: Python List (E-mail) Subject: Web Authentication to AD I would like to write a python web service that would take a username and password entered on a web form and authenticate to Active directory. A few questions about this. 1. How can I do it :-) 2. I would like the script to be in the same server as the websites which is a linux box. So I need it to call active directory on a M$ box. If this is too hard could someone at least explain the process if I make this a service on the M$ box. Which I guess I can do if keeping it on the Linux box is too much. 3. I would like to expand the service so that I could check the computer the user is on and not make them enter a username and password if they are already logged in to the domain. I huess I would have to use Java Script for this. Any ideas here? Thank you in advance. Jason Tesser Web/Multimedia Programmer Northland Ministries Inc. (715)324-6900 x3050 -- http://mail.python.org/mailman/listinfo/python-list From fmsumkin at users.sourceforge.net Mon Nov 24 07:13:33 2003 From: fmsumkin at users.sourceforge.net (Fedor Sumkin) Date: Mon, 24 Nov 2003 14:13:33 +0200 Subject: ANN: BlackAdder 1.0-031121 released Message-ID: BlackAdder 1.0-031121 for Python development on Windows and Linux The release includes PyQt 3.8 documentation. Rancho Santa Margarita, CA -- 24 November 2003 -- theKompany.com, producers and distributors of high-quality open source and commercial Linux software, are pleased to announce the availability of BlackAdder 1.0-031121, a Windows/Linux UI development environment for Python based on Qt. BlackAdder combines a visual design environment with debugging, syntax highlighting, ODBC interfaces and extensive HTML documentation into a comprehensive platform for developing Python applications with PyQt. BlackAdder is an exciting product for rapidly developing applications on Linux or Windows using the popular Python language. Besides being a powerful IDE with an extensive array of tools to make developing your application quick and easy. BlackAdder is tightly integrated with PyQt which is a set of bindings for Python to allow you to make use of the popular Qt multi-platform windowing toolkit from Trolltech. Our optional Business Edition gives you a full commercial license for both PyQt and Qt as used from BlackAdder. Features: * Integrated Qt Designer * Syntax highlighting text editor * Supports the latest versions of Python, PyQt and Qt * eGenix.com mx Extensions for ODBC access from Python have been included. * Integrated Debugger * The debugger allows class instance objects to be displayed. * No restrictions are placed on the types of files that can be included in a project. * Project Explorer for adding existing file sets to a project * Extensive project management capability * and much more& BlackAdder can be purchased or free demos downloaded from www.thekompany.com/products/blackadder. -- Best regards From goodtaste at 126.com Thu Nov 13 06:48:03 2003 From: goodtaste at 126.com (=?gb2312?B?1cXWvsP3?=) Date: Thu, 13 Nov 2003 19:48:03 +0800 Subject: quest about telnetlib Message-ID: <005d01c3a9dc$0fd03b30$35c8c8c8@mcgsdev1.com> code below cannt work import getpass import sys import telnetlib import select tn = telnetlib.Telnet() print tn.open("162.105.31.222",23) print tn.read_eager() print "ok" output is: ------------ None ok ------------ the host is avaiable,but my python program cannt connect to it ,why? From mikit at zoran.co.il Tue Nov 4 11:09:03 2003 From: mikit at zoran.co.il (Miki Tebeka) Date: 4 Nov 2003 08:09:03 -0800 Subject: I sti-ll... haven't found,.... what I'm looking for. References: Message-ID: <6250403b.0311040809.213c5c4@posting.google.com> Hello, > I think I explained badly what I need - I want the long string to pause for > each full screen, so I can read it. It shoots off the top, so I can only > read the end... Have a look at the _Printer class in site.py (comes with installation). HTH. Miki From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Wed Nov 26 13:05:12 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Wed, 26 Nov 2003 21:05:12 +0300 Subject: invert dictionary with list &c In-Reply-To: References: Message-ID: Des Small wrote: > Lately I have found myself using a pattern to make new dictionaries > quite often, by which I mean twice: > > def invert(d): > nd = {} > [nd.setdefault(val, []).append(key) for k, v in d] > return nd > > def count(l): > d = {} > [d.setdefault(w, 0) += 1 for w in l] > return d > > Is this the pythonic way to do such things? Ideally I'd like to write > them as one liners, but I can't see how. > > Des Most pythonic way IMHO would be: def invert(d): nd = {} for k, v in d.iteritems(): nd[v] = nd.get(k, []) + [k] return nd def count(l): d = {} for e in l: d[e] = d.get(e, 0) + 1 return d Or to define dict with default values: import copy class defdict(dict): def __init__(self, default = None): self._default = default super(dict, self).__init__(self) def __getitem__(self, k): return self.get(k, copy.deepcopy(self._default)) # or setdefault when def invert(d): nd = defdict([]) for k, v in d.iteritems(): nd[v] += [k] return nd def count(l): d = defdict(0) for e in l: d[e] += 1 return d However, if you insist on one-liners, I can suggest some ;): def count(l): return reduce( lambda d, e: (d.update(dict([(e, d.get(e, 0) + 1)])), d)[1], l, {} ) def invert(d): return reduce( lambda d, (k, v): (d.update(dict([(v, d.get(v, []) + [k])])), d)[1], d.iteritems(), {} ) (given in several lines, but can be written in one) or even count = lambda l: reduce( lambda d, e: (d.update(dict([(e, d.get(e, 0) + 1)])), d)[1], l, {} ) :) regards, anton. From kirk at strauser.com Tue Nov 18 12:55:05 2003 From: kirk at strauser.com (Kirk Strauser) Date: Tue, 18 Nov 2003 17:55:05 GMT Subject: recommendations for python web programming tools References: Message-ID: <877k1x36pa.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2003-11-18T17:11:40Z, Matthew Wilson writes: > I looked a little at Zope, and it looks like it has a huge learning curve. > Is that true? It depends. What's your OOP experience level? Zope doesn't *require* OOP methods, but that's where it gets much of its power. > How long would it take for a person that's written lots of CGI scripts to > get up to speed on Zope? Are you already decent with Python? If so, install Zope and work through the built-in tutorial. You should be able to get up and running in no time. - -- Kirk Strauser -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/ulxU5sRg+Y0CpvERAi/QAKCP8fYIDCATefwD8Qe6gRpgkSPHkQCffOUh Ju8bcHmNr6oF4KlrWctInWQ= =tjbr -----END PGP SIGNATURE----- From domma at procoders.net Wed Nov 5 02:15:39 2003 From: domma at procoders.net (Achim Domma) Date: Wed, 5 Nov 2003 08:15:39 +0100 Subject: SMTP Authentication References: <20031104181955.GA16137@intarweb.us> Message-ID: "Gerhard H?ring" wrote in message news:mailman.453.1067999320.702.python-list at python.org... > Let me know if this helps. It works fine, thanks a lot! Achim From email9898989 at yahoo.com Wed Nov 19 10:06:47 2003 From: email9898989 at yahoo.com (email9898989 at yahoo.com) Date: 19 Nov 2003 07:06:47 -0800 Subject: This is getting ridiculous (Re: PyQt, Qt, Windows and Linux) References: Message-ID: > The "official" Qt3 book is due in February of 2004, and the > included CD will include a non-commerical version of Qt 3.2.1 > for Windows [...] it appears that you will be able to distribute > the Qt runtime DLLs with your non commerical application [...] So if I just want to make free software that works cross-platform, I'd have to buy this crappy C++ book to get a special restricted version of Qt3 for Windows that may or may not work with Python. This is ridiculous. From pmaupin at speakeasy.net Sat Nov 15 01:52:50 2003 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 14 Nov 2003 22:52:50 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <2259b0e2.0311140033.4e3ca8ea@posting.google.com> <2259b0e2.0311140906.87b7839@posting.google.com> Message-ID: <653b7547.0311142252.40ed1f48@posting.google.com> "Brandon J. Van Every" wrote: > I have seen the DEC Alpha CPU torn out from under me. As far as I'm > concerned, any hardware / language / API / OS has enemies, and those that do > not market themselves properly are endangered. Considering that Python was > available before Java, it is not the success story that it could or should > be. The ugly truth of high is it's 1/3 technology and 2/3 marketing. If > you believe otherwise, then you haven't had Intel or Microsoft hand you your > ass yet. I don't dispute that Python could/should do better against Java. (I'm actually pretty agnostic on this statement.) However, comparing hardware and software for cost/benefit is much worse than comparing apples and oranges. There are tangible, huge costs associated with fabbing and selling a chip. If you can only sell a few a year it's simply not worth it. Especially if you chip requires additional support chips which are no longer sold because it's not worth it for them, either. For software, open source makes the economics even sweeter. You can often easily justify the cost of paying to incrementally improve a package you use based solely on your own needs. For chips the economics are _way_ different. Assume for a moment that the Alpha was open-sourced, and you wanted to create a "modern" version of it. Are you willing to spend a half-millon dollars on tools, and another half-million or more on a mask set to be able to produce a 90nm version of it which won't even work with any of the existing support chips because the IO cells on your fancy new chip aren't even 3V-tolerant? Bottom line: the probability of long-term availability of and support for Alphas tends toward 0, while the probability of long-term availability of and support for Python tends toward 1 :) Pat P.S. The hardware economics _are_ currently undergoing a radical change. If your requirements do not include cutting edge speed, you _can_ build onesies/twosies using FPGAs for hundreds of dollars, or even in some cases tens or hundreds of units for tens of dollars. Or if you really only want a few fast ones, you could forego the cost of the mask set, and "only" spend a half-million or so for tools, and fifty to a hundred thousand for a few die on a "multi-project wafer". The future may hold "direct write" systems which do not require any mask set. If these become practical, the cost of the software tools will become a much bigger proportion of the total bill, but the number of potential projects will skyrocket, so history and simple economics show that competition will cause the tool prices to drop like a rock. Once that happens, you may very well be able to build your Alpha chips on demand :) From graham.lee at wadham.oxford.ac.invalid.uk Mon Nov 3 04:43:57 2003 From: graham.lee at wadham.oxford.ac.invalid.uk (Graham Lee) Date: Mon, 03 Nov 2003 09:43:57 +0000 Subject: nearest neighbor in 2D References: Message-ID: John Hunter wrote: > > One solution that comes to mind is to partition to space into > quadrants and store the elements by quadrant. When a new element > comes in, identify it's quadrant and only search the appropriate > quadrant for nearest neighbor. This could be done recursively, a 2D > binary search of sorts.... > What happens when you put a particle in near/at the boundary of a quadrant though? It's possible for the nearest neighbour to be in the nearest neighbour quadrant...although you could search over these as well. However, the number of independent areas implied by use of the word 'quadrant' suggests that this would be the same as iterating over all space.... :-) -- Graham Lee Wadham College Oxford From balex at sympatico.ca Sat Nov 1 23:30:20 2003 From: balex at sympatico.ca (Brian) Date: Sat, 01 Nov 2003 23:30:20 -0500 Subject: unittest -- simple question Message-ID: Hello; I am writing my test modules that are separate from the modules they test. The test modules can be invoked with if __name__ == "__main__" when run from a command line. Right now, if __name__ == "__main__", the test module executes runTests(), which defines a suite of tests. From the module being tested, I am calling into the test module -- to the function runTests(), if __name__ == "__main__". Is this how people make the tests executable from the module be tested? Many thanks, Brian. From benles at bldigital.com Sun Nov 9 14:32:46 2003 From: benles at bldigital.com (Ben Allfree) Date: Sun, 9 Nov 2003 11:32:46 -0800 Subject: Bad docs for os.path.isabs() Message-ID: The docs for os.path.isabs() state: isabs( path) Return True if path is an absolute pathname (begins with a slash). This is false becase os.path.isabs("C:\\foo") == True It should read: isabs( path) Return True if path is an absolute pathname (begins with a slash or drive letter). From aleaxit at yahoo.com Sat Nov 1 10:55:33 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 01 Nov 2003 15:55:33 GMT Subject: On PEP 322 (ireverse) References: <4xQnb.373812$R32.12367046@news2.tin.it> Message-ID: Aahz wrote: ... >>built-in functions normally can't, and in that way they differ from >>C-coded functions. So, iter would have to be changed into a different >>type that _does_ support some attributes. > > Did you mean "Python-coded"? Anyway, I doubt that adding an attribute Yep. > to iter() would cause problems the way changing it to a type constructor > would. I'm not suggesting this, mind, just curious why nobody else > mentioned the possibility. I think one needs *more* work to add an attribute to a C-coded function: it needs to be made into a different type. To add a classmethod to a type one only needs to supply the classmethod flag in one's C sources -- hard to see how that might be more troublesome...? Alex From fumanchu at amor.org Fri Nov 14 01:58:29 2003 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 13 Nov 2003 22:58:29 -0800 Subject: Try, except...retry? Message-ID: Alex Martelli wrote: > In retrospect, it WOULD perhaps be better if setdefault was designed > to take a callable (and optional args for it) and only call it if and > when needed -- that would add a little speed and clarity > > Yes, flags (hiding control flow in data!) and repeated code > do suck, but > you need neither to get exactly the same semantics as your > desideratum: > > while True: > try: allPiranhas['Doug'].weapon = u'satire' > except KeyError: allPiranhas['Doug'] = Pirhana() > else: break > > I could be wrong, of course: there is nothing that appears to me > to be "outrageously nonPythonic" in your proposal -- it just seems > that new statements need to be more of a win than this in order to > stand a chance. But a PEP on this is surely warranted, if you want > to try one. > > No special "implications", as the semantics are just about the > same as the above-indicated (flags-less, duplication-less) > "while True:" loop that is so easy to code explicitly today. > > It's just that, partly because of this (and attendant benefits > that writing out "while" DOES clearly indicate to the reader > that the following code may repeat, etc etc), it does not seem > to me that 'retry' is worth adding. But unless somebody does > write a PEP, you'll just have my opinion about this... Agreed. I'm new enough I'm still easy to convince. :) On a lark, I decided to dump the bytecodes and see what I could see. It comes out, in my math, to about 20 bytecodes saved using "retry" instead of "while True", mostly due to saving the nested block. See the lines I've marked with a * below, which I think would be taken out if we had retry. I'm not a master of Python, I assume the left column in dis.dis() output increments by more than one to mean that instruction takes more cycles. I also assume byte 60 would have to be replaced with a JUMP_ABSOLUTE to SETUP_EXCEPT. It depends on whether SETUP_EXCEPT would have to be reexecuted again--does it? Anyone? >>> def loop(): ... while True: ... try: ... print a ... except: ... a = 0 ... else: ... break ... >>> loop() 0 >>> dis.dis(loop) 0 SET_LINENO 1 * 3 SET_LINENO 2 * 6 SETUP_LOOP 56 (to 65) * >> 9 SET_LINENO 2 * 12 LOAD_GLOBAL 0 (True) * 15 JUMP_IF_FALSE 45 (to 63) * 18 POP_TOP 19 SET_LINENO 3 22 SETUP_EXCEPT 12 (to 37) 25 SET_LINENO 4 28 LOAD_FAST 0 (a) 31 PRINT_ITEM 32 PRINT_NEWLINE 33 POP_BLOCK 34 JUMP_FORWARD 19 (to 56) >> 37 SET_LINENO 5 40 POP_TOP 41 POP_TOP 42 POP_TOP 43 SET_LINENO 6 46 LOAD_CONST 1 (0) 49 STORE_FAST 0 (a) 52 JUMP_FORWARD 5 (to 60) 55 END_FINALLY * >> 56 SET_LINENO 8 * 59 BREAK_LOOP * >> 60 JUMP_ABSOLUTE 9 >> 63 POP_TOP 64 POP_BLOCK >> 65 LOAD_CONST 0 (None) 68 RETURN_VALUE Robert Brewer MIS Amor Ministries fumanchu at amor.org From gerrit at nl.linux.org Sat Nov 15 15:27:15 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sat, 15 Nov 2003 21:27:15 +0100 Subject: datetime and strptime Message-ID: <20031115202715.GA10582@nl.linux.org> Hi, it seems the datetime library does not have a .strptime class method. If I want to create a datetime object from a string, I currently have to do: datetime.date(*time.strptime(s, "%Y%m%d")[:3]) If the format is more complex (not in the order of a timetuple), it is even more complicated. In my opinion, it would be better to be able to do: datetime.date.strptime(s, "%Y%m%d") Is there a particular reason that this is not possible? Or is the only reason that it hasn't been implemented? yours, Gerrit, who wanted to write a patch until he saw datetime is written in C. -- 233. If a builder build a house for some one, even though he has not yet completed it; if then the walls seem toppling, the builder must make the walls solid from his own means. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From missive at frontiernet.net Sun Nov 9 09:11:05 2003 From: missive at frontiernet.net (Lee Harr) Date: Sun, 09 Nov 2003 14:11:05 GMT Subject: Ay Karamba! Message-ID: Have you seen SuperKaramba for KDE? Wow! http://netdragon.sourceforge.net/ It uses python to create desktop applets and themes. Very slick. Someone just ported it to FreeBSD :o) From jfromm at jasc.com Thu Nov 6 09:00:23 2003 From: jfromm at jasc.com (Joe Fromm) Date: Thu, 6 Nov 2003 08:00:23 -0600 Subject: Strange problems with encoding References: Message-ID: <3faa53fe$0$40212$39cecf19@news.twtelecom.net> "Sebastian Meyer" wrote in message news:pan.2003.11.06.13.28.39.37248 at technology-network.de... > Hi newsgroup, > > i am trying to replace german special characters in strings like > str = re.sub('?', 'oe', str) > > When i work with this, i always get the message > UniCode Error: ASCII decoding error : ordinal not in range(128) > Try adding sys.setdefaultencoding( 'latin-1' ) to your site.py module, or rewrite your fragment as from = '?' to = 'oe' s = re.sub( from.encode('latin-1'), to.encode('latin-1', s ) If you are running on Windows you might want to change 'latin-1' to 'mbcs', as that seems to be the most forgiving codec, but it is Windows only. Joe From garyr at fidalgo.net Wed Nov 26 16:43:39 2003 From: garyr at fidalgo.net (Gary Richardson) Date: Wed, 26 Nov 2003 13:43:39 -0800 Subject: problem using differ References: Message-ID: "Russell" wrote in message news:vsa5jn2060qe24 at corp.supernews.com... > I'm trying to automate the comparison of some source code but I'm having > trouble using the differ object. I'm new to Python so I'm probably doing > something wrong. I've created a small program (included below) that > demonstrates my problem. For some reason, Python doesn't recognize differ. > I keep getting this error: NameError: name 'differ' is not defined. What am > I doing wrong? > > Test Code follows: > import difflib > > a=[] > a.append('1. Beautiful is better than ugly.') > a.append('2. Explicit is better than implicit.') > a.append('3. Simple is better than complex.') > a.append('4. Complex is better than complicated.') > > b=[] > b.append('1. Beautiful is better than ugly.') > b.append('3. Simple is better than complex.') > b.append('4. Complicated is better than complex.') > b.append('5. Flat is better than nested.') > > d=differ() > d.compare(a,b) > > d=difflib.Differ() for k in range(4): dif = d.compare(a[k], b[k]) for p in dif: print p, print From p at trick.lu Sat Nov 15 14:47:24 2003 From: p at trick.lu (Patrick Useldinger) Date: Sat, 15 Nov 2003 20:47:24 +0100 Subject: reading piped input in Windows References: <95ocrv0gts1dn66dvgn84n9j7rcthbdglf@4ax.com> Message-ID: OK, I should have googled in the first place :-( For those who wondered, it doesn't work if you have .py extentions associated with python.exe and just type t1 ? p2. What works is 1- to have a py.cmd which calls python.exe, and then type "py t1.py ? py t2.py", 2- or probably also "python t1.py ? python t2.py" if python.exe is in your path (I didn't check this). -PU From karound at yahoo.com Thu Nov 13 17:25:52 2003 From: karound at yahoo.com (caroundw5h) Date: 13 Nov 2003 14:25:52 -0800 Subject: manipulating .xls data Message-ID: <5fdcce8b.0311131425.37592f1b@posting.google.com> I would like to manipulate my excel file as if it were a text file with python (check for duplicates, uppercase etc.). I would like to know: 1) how do convert it first to a CSV file and manipulate it. 2) are there any functiionalities in excel that will allow me to create my own functions. 3) what is the best way to manipualte excel files OTHER than COM. thank you all From eelgueta at navix.cl Fri Nov 14 07:55:29 2003 From: eelgueta at navix.cl (Edo) Date: Fri, 14 Nov 2003 09:55:29 -0300 Subject: devel package rpm install Message-ID: Hi All, When I do "rpm -i python2.3-devel-2.3.2-1pydotorg.i386.rpm", I get error: Failed dependencies: python2.3 = 2.3.2 is needed by python2.3-devel-2.3.2-1pydotorg However, "rpm -qa | grep py" shows: python2.3-2.3-3pydotorg (among others 2.2 packages) If this is not the place to ask, any direction is very welcomed. TIA. Ed. PS. RedHat 9, with full python2.2 and base 2.3 installed. From tzot at sil-tec.gr Wed Nov 5 13:43:07 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 05 Nov 2003 20:43:07 +0200 Subject: domain featured in O'Reilly book, available now References: <3FA94050.645D1162@engcorp.com> Message-ID: <9lgiqvomj36l22obgg6f069eh2lj5cub81@4ax.com> On Wed, 05 Nov 2003 13:24:16 -0500, rumours say that Peter Hansen might have written: [Alan comments that "toftoot.com", used as an example in "Learning Python", is available] >I understand the domain "xxoeitll.com" is not yet claimed, either. > >And as an added advantage, it has a higher likelihood of meaning >something rude in Aztec, as well. ;-) Imagine my surprise some years ago when I found out that the quite cryptic 'tzot' I traditionally used as a username (chris was oh so already-taken in unix systems), was a quite common mayan word (a dialect of Mayan, a small barracuda, 'arm', 'labyrinth', 'lost one' are its meanings so far as per google...) I don't know if it means python too, what with all those dragon and snake gods, but I wouldn't be surprised :) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From python at meyer-luetgens.de Wed Nov 5 05:55:43 2003 From: python at meyer-luetgens.de (=?ISO-8859-1?Q?Jan-Erik_Meyer-L=FCtgens?=) Date: Wed, 05 Nov 2003 11:55:43 +0100 Subject: dictionary keys, __hash__, __cmp__ In-Reply-To: References: Message-ID: Miika Keskinen wrote: > On Tue, 04 Nov 2003 21:52:42 +0100, Jan-Erik Meyer-L?tgens wrote: > >>In the Python Language Reference, I found the following statements about >>using objects as dictionary keys: >> >> 1. "__hash__() should return a 32-bit integer." >> >> 2. "The only required property is that objects which >> compare equal have the same hash value." >> >> 3. "If a class does not define a __cmp__() method it >> should not define a __hash__() operation either." >> >> >>Can I asume that: >> >> -- keys are interchangeable (equivalent), >> if the following is valid: >> >> hash(key1) == hash(key2) and key1 == key2 > > Yes. note that key1 == key2 implies hash(key1) == hash(key2) ... only if I define __cmp__() and __hash__() appropriate (and not breaking the 2nd rule) >> -- I can ignore the 2nd statement, if I am aware of >> the fact that: if objects are equal it dosn't mean that they are >> the same key. > > > So you're introducing scenario where different objects are considered > equal in means of __cmp__ while having different hash. I think that's not > normal. > That's the point. I know that this in not normal. But is it possible? >> -- I can savely ignore the 3rd statement, because python >> falls back to cmp(id(obj1), id(obj2)), if __cmp__() is not defined. > > > Yes. id(obj1) != id(obj2), so obj1 != obj2. Only requirement left is that > __hash__() returns 32 bit integer. Personally i would emphasis word SHOULD > NOT in third rule. I'm sure there is situations where it's perfectly > normal to use id-value's and custom hashes. Anyways you can redefine > __cmp__() simply to (and thus avoiding to break against third rule): > > def __cmp__(self, other): > return id(self).__cmp__(id(other)) > > But I want __cmp__() for another comparison. As an real world example I have a file object which should be stored in a dictionary. __cmp__() compare the contents of two files. Thus I must define the __hash__() method. I use id(obj) as the hash function. So I've breaking the rule: Objects which compare equal have the same hash. I use the file objects as dictionary keys and it seems to work. My assumption is that keys are interchangeable (equivalent), if hash(key1) == hash(key2) and key1 == key2. In my example keys are equivalent, when they are identical. id(file_object1) == id(file_object2) and file1 have the same contents as file2. Is this assumption valid? Or is there some sophistication in the python implemention, that break things sometimes? Resulting in deletion of important files :-) -- Jan-Erik From newsgroups at jhrothjr.com Mon Nov 24 18:54:49 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 24 Nov 2003 18:54:49 -0500 Subject: code blocks in Python References: <8ef9bea6.0311221215.804bdb3@posting.google.com> <8ef9bea6.0311221913.427cb53e@posting.google.com> <8ef9bea6.0311231634.1ca497ac@posting.google.com> <8ef9bea6.0311232220.4e308a4c@posting.google.com> <8ef9bea6.0311241105.e53c47d@posting.google.com> <8ef9bea6.0311241527.61a27b6c@posting.google.com> Message-ID: "Hung Jung Lu" wrote in message news:8ef9bea6.0311241527.61a27b6c at posting.google.com... > Skip Montanaro wrote in message news:... > > > I come back again to repeat it one more time: the compile() function > already exists and works in Python. Before you do your posting, please > think about the compile() function first. (Do I need to say it one > more time? I don't mind.) So what? Functionality is not added to Python simply because it looks like a logical extension of something else that already exists. First, you need to show a compelling use case. So far, I've seen one thing in your proposal: dynamic binding of free variables in a function, rather than static binding. All questions of syntax aside, please show me why this matters, bearing in mind that I've never programmed in a language that has this, and am not going to be convinced by references to such languages. While I'm not *the* person that has to be convinced (that's Guido), I'm probably representative. If you don't manage a compelling case for why dynamic binding is a useful option, then you're not going to get anywhere with this proposal. By the way - if I understand the guts of the proposal, the compile function has nothing to do with it, and wouldn't be used to implement it in any case. John Roth From davidcfox at post.harvard.edu Wed Nov 5 13:28:24 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Wed, 05 Nov 2003 18:28:24 GMT Subject: reduce() anomaly? In-Reply-To: References: Message-ID: Stephen C. Waterbury wrote: > This seems like it ought to work, according to the > description of reduce(), but it doesn't. Is this > a bug, or am I missing something? > > Python 2.3.2 (#1, Oct 20 2003, 01:04:35) > [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> d1 = {'a':1} > >>> d2 = {'b':2} > >>> d3 = {'c':3} > >>> l = [d1, d2, d3] > >>> d4 = reduce(lambda x, y: x.update(y), l) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1, in > AttributeError: 'NoneType' object has no attribute 'update' > >>> d4 = reduce(lambda x, y: x.update(y), l, {}) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1, in > AttributeError: 'NoneType' object has no attribute 'update' > > - Steve. The update method updates the dictionary in place, but returns None. Thus, after the first call to x.update(y), reduce is trying to call x.update(y) with x equal to None. Hence the error. Alternatives which work include def rupdate(d, other): d.update(other) return d reduce(rupdate, l) and d = {} map(lambda x: d.update(x), l) David From wtrenker at shaw.ca Sun Nov 9 20:25:22 2003 From: wtrenker at shaw.ca (William Trenker) Date: Mon, 10 Nov 2003 01:25:22 +0000 Subject: More user feedback on Sets.py In-Reply-To: <1hSqb.1167$bQ3.696@nwrdny03.gnilink.net> References: <1hSqb.1167$bQ3.696@nwrdny03.gnilink.net> Message-ID: <20031110012522.21037518.wtrenker@shaw.ca> Raymond Hettinger wrote: > For Py2.4, I'm working on a C implementation of Sets.py I was exploring Aaron Watters' kjbuckets module today (Phillip Eby's PEAK framework uses it). Now that a C implementation of Sets.py is in the works, I wonder if this is the time to consider merging at least some of the directed-graph functionality of kjbuckets into Sets.c? The support in kjbuckets for graphs includes methods like: neighbors, reachable, and tclosure (transitive closure). For those who haven't looked at it, the kjbuckets module provides objects for sets, directed-graphs, and algebraically-operable-dicts in an implementation that is "tightly coupled at the level of C, allowing fast and powerful algebraic combinations of container objects." It is documented quite nicely here, http://gadfly.sourceforge.net/kjbuckets.html Just food for thought, Bill From jjl at pobox.com Thu Nov 27 18:36:30 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Nov 2003 23:36:30 +0000 Subject: Python bug report on SF, what now? References: <3fc660c2$0$1492$e4fe514c@news.xs4all.nl> Message-ID: <87ekvtmlj5.fsf@pobox.com> martin at v.loewis.de (Martin v. L?wis) writes: [...] > It will be noticed automagically. As it has a patch associated, you > should have submitted it as a patch, though - some of us (including > myself) give patches higher priority, as they indicate that the [...] Same for wishlist items with patches? Or should they go in RFE (Requests For Enhancement)? John From rynt at 9yahoo.com Fri Nov 14 11:13:36 2003 From: rynt at 9yahoo.com (R Baumann) Date: Fri, 14 Nov 2003 08:13:36 -0800 Subject: Help with Kinterbasdb SQL Error -206 Column unknown Message-ID: I'm a newbie with Python, and trying to connect to the Interbase/Firebird 'EMPLOYEE.GDB' file to play with it. Can anyone help with this? I'm running Firebird 1.5rc4 Python 2.3.2 kinterbasdb 3.1_pre6-win32-FB1.5-py2.3.exe winXP Pro SP1 I run the same code at home and it works fine. The only difference is, at home I'm running Interbase 5.5. Code follows. . . Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.0 >>> import kinterbasdb >>> con = kinterbasdb.connect( host='localhost', database='c:/Data/FireBirdIB/employee.gdb', user='SYSDBA', password='masterkey', dialect=3 ) >>> cur = con.cursor() >>> cur.execute("SELECT * FROM EMPLOYEE;") Traceback (most recent call last): File "", line 1, in -toplevel- cur.execute("SELECT * FROM EMPLOYEE;") File "C:\Python23\Lib\site-packages\kinterbasdb\__init__.py", line 1444, in execute self.description = _k.execute(self._C_cursor, sql, params) OperationalError: (-206, 'Unable to determine field precison from system tables: Dynamic SQL Error. SQL error code = -206. Column unknown. FIELD_SPEC.RDB$FIELD_PRECISION. At line 1, column 19.. ') >>> Thanks for any help Ruben From jkrepsBEAR at FISHneb.rr.com Tue Nov 11 08:54:58 2003 From: jkrepsBEAR at FISHneb.rr.com (GrayGeek) Date: Tue, 11 Nov 2003 07:54:58 -0600 Subject: ANN: ruleCore - The event pattern detector engine References: <438a319a.0311091143.256db982@posting.google.com> Message-ID: <1Q5sb.23278$M02.14529@twister.rdc-kc.rr.com> Marco wrote: > I would hereby like to announce that ruleCore 1.0beta6 is available > under the GPL license from www.rulecore.com > > ruleCore is an event-driven reactive rule engine with GUI tools, > all written in Python. > > The ruleCore Engine accepts events with XML-RPC and detects > complex patterns of events, called situations. A situation is > defined by combining events with different kind of nodes, such as > logical or timer nodes. > > For example, ruleCore can do things like: > "Detect the situation, if it is not december, when event HOST_DOWN > comes after event ROUTER_DOWN and event FAILOVER does not come > within 10 minutes" > > When a situation is detected a condition can be evaluated on all the > events that took part in the detection process. If the condition is > true an action is executed, normally a script. > > The ruleCore Engine is written in completely in Python. The GUI tools > are also in Python and uses Qt with the PyQt wrapper. Everything is > tested on recent versions of SUSE and RedHat. The rpm contains > *everything* needed to run ruleCore, so it should run on most Linux > distributions. > > Portability to Windows and Mac is a goal, but not tested yet. But as > everything is in Python it should run provided that all the required > software is installed. Although this is left as an exercise to the > interested reader. > > The ruleCore Engine is based on ideas from the research done on active > rules called Event-Condition-Action (ECA) rules. Google on ECA-rules or > check the references section on www.rulecore.com to learn more about > this type of event-driven active rules. > > /Marco Interesting concept. Where millisecond reaction time is not important it could even be considered 'realtime'. I've been working on a process control project and needed a Linux solution. There is an entire, well developed industry surrounding process control, standardized on the EN 61131-3 or IEC 1131-3 language description. Here is an example of industrial process control: http://omarz.htmlplanet.com/S7_Automation.htm The language defined above is used to program process controllers one of four methods, two graphical, and two using scripts. Here are some Linux based solutions: http://www.linux-automation.de/plc/index_en.html Here is a Linux program that utilizes one of the graphical methods, called "Ladder". http://membres.lycos.fr/mavati/classicladder/ I think you'll see the strong similarities between your rule engine and the classic ladder, as shown by the snapshots of the engine at work. -- - GrayGeek From bignose-hates-spam at and-benfinney-does-too.id.au Tue Nov 25 19:05:56 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 26 Nov 2003 10:55:56 +1050 Subject: wxPython - wx package (new style wxPython?) References: Message-ID: On Wed, 26 Nov 2003 01:01:59 +0100, Logan wrote: > Would you recommend to use the wx package of wxPython? Because it removes the redundancy in the module object names, yes. As for any other qualities the 'wx' package might have, I can't say; if it's exactly the same functionality and call styles as the existing wxPython.wx then I can't see a reason not to use it. > From the documentation: > > Provides a way to drop the wx prefix from wxPython objects by > dynamically loading and renaming objects from the real wxPython > package. This is the first phase of a transition to a new style > of using wxPython. > > What does 'this is the first phase of a transition to a new style > using wxPython' in the above mean? Will this new style become the > only way to use wxPython in future releases? 'from foo import *' is heavily deprecated in any case; this "new style of using wxPython" is merely saying (AIUI) that the 'wx' package allows a more natural usage of wxPython objects without needing to use a deprecated import style. -- \ "Quidquid latine dictum sit, altum viditur." ("Whatever is | `\ said in Latin, sounds profound.") -- Anonymous | _o__) | Ben Finney From mis6 at pitt.edu Fri Nov 14 03:33:03 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 14 Nov 2003 00:33:03 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> Message-ID: <2259b0e2.0311140033.4e3ca8ea@posting.google.com> python473 at yahoo.com (John Howard) wrote in message news:<9eabe547.0311131610.4dd7819c at posting.google.com>... > I've sent several messages over the last year asking about python - > Who teaches python? Is python losing steam? etc. I have noticed, eg, > the declinng number of books at my local borders. The last time I > visited a borders (last week), there was 1 (sic) book about python on > the shelve compared to dozens on perl & java! On my last inquiry about > who teaching python, I got two, maybe three, responses. I really want > to see python succeed! It's the best language I've seen. I see a lot > on www.python.org about development, but little on usage. I sent a > message to someone on the python site (I forget who - I know, no > excuse) about what I've done done on a site (grades, web application, > web registration, etc). No reponse. Sorry to ramble, but I wanted to > say a lot, but not have to go into a lot of detail. Python is not backed by Microsoft or Sun, so there are less courses and books about Python than about C#/Visual C++/Visual Basic or Java; Perl is not backed, but it was there well before Python, and lots of people know it and use it (even they do not necessarily love it ;), so it has a definite historical advantage. The present situation is clear: but then what? Should we ask Bill Gates to adopt Python as the next Visual Basic? Or ask Sun to switch to Jython? Or ask Larry Wall to convert to the Zen of Python? The only thing we can do in practice is to predicate the verb of Python to our friends, as we all do it already. Also, we can work on slick new logos and to a restyling of the Python Website. But this will not raise the number of Python books in the stores in a couple of weeks or months or years. It is quite sterile to complain against things we have no real way to control. We can only wait and see (as in that old chinese said ...) Michele Simionato From google.com.112139 at satilla.com Sun Nov 16 04:01:17 2003 From: google.com.112139 at satilla.com (Eric Baker) Date: 16 Nov 2003 01:01:17 -0800 Subject: Bug or Feature with (overriding) Class Variables? Message-ID: With this little snippet, i get an inconsistency between the behavior of string and dictionary class variables: Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> class foo: dict = {} string = "foostring" def bar(self): self.dict["bar-key"] = "bar-value" self.string = "bar-string" >>> # Lets create an instance of Foo >>> baz = foo() >>> baz.dict {} >>> baz.string 'foostring' >>> # No suprises yet, the class variables are shown >>> >>> # Now lets call bar() and change some vars >>> baz.bar() >>> baz.dict {'bar-key': 'bar-value'} >>> # Did it return a class variable or an instance variable? >>> baz.__class__.dict {'bar-key': 'bar-value'} >>> # As you can see, both show the same values >>> >>> baz.dict is baz.__class__.dict 1 >>> # So we see that both are actually the same instance >>> # of the dictionary class >>> >>> # Now we look at the string >>> baz.string 'bar-string' >>> # Obviously this was the instance variable >>> baz.__class__.string 'foostring' >>> # And this was the class variable >>> baz.string is baz.__class__.string 0 >>> # And we actually can see, that they are different >>> # instances of the string class Question: Which behavior is the correct one? Question: Is this a bug or a feature? From achin at eminence32.cjb.net Mon Nov 3 16:42:27 2003 From: achin at eminence32.cjb.net (Andrew Chin) Date: Mon, 03 Nov 2003 21:42:27 GMT Subject: Finding the "home" folder [Linux/Windows] References: Message-ID: true.. in that case i suppose the 'home directory' would be simply 'c:\my documents\' On Mon, 03 Nov 2003 04:48:48 GMT, JanC wrote: > Andrew schreef: > >> windows 98/me: c:\my documents\username > > Many Win9x systems run without a "user", so there is no username then... > -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From peter at engcorp.com Tue Nov 11 10:32:36 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Nov 2003 10:32:36 -0500 Subject: response time References: <1jSrb.2419$9_.105379@news1.tin.it> <87d6bzetsz.fsf@pobox.com> <3FB01787.529425BC@engcorp.com> <87u15bf6qs.fsf@pobox.com> <3FB0FAE0.73ECA8A1@engcorp.com> Message-ID: <3FB10114.499898B2@engcorp.com> Peter Hansen wrote: > > "John J. Lee" wrote: > > > > Peter Hansen writes: > > [...] > > > Strange, but based on a relatively mundane thing: the frequency (14.31818MHz) > > > of the NTSC color sub-carrier which was used when displaying computer output > > > on a TV. This clock was divided by 3 to produce the 4.77MHz clock for the > > [...] > > > in time-keeping, which then counted on every edge using a 16-bit counter > > > which wrapped around every 65536 counts, producing one interrupt every > > > 65536/(14.31818*1000000/12) or about 0.5492 ms, which is about 18.2 ticks > > [...] > > > > That doesn't explain it AFAICS -- why not use a different (smaller) > > divisor? An eight bit counter would give about 0.2 ms resolution. > > Can you imagine the overhead of the DOS timer interrupt executing over 500 > times a second?! It would have crippled the system. Oops: 5000 times a second, even worse. :-) I have a vague memory that the DOS timer interrupt could take well over a millisecond to execute on the old machines, so it simply wasn't feasible in any case. From robin.hansen at codito.ch Sun Nov 9 11:42:01 2003 From: robin.hansen at codito.ch (Robin Edgar Hansen) Date: 9 Nov 2003 08:42:01 -0800 Subject: Trouble storing object in session variable (ActivePython/IIS) Message-ID: <15fb41d2.0311090842.613dc052@posting.google.com> Hi! I'd like to store an object in a session variable and thus keep it 'alive' for the entire session. More precisely I wanted to do this (possibly in Application_OnStart()): import telnetlib cli = telnetlib.Telnet("localhost",9999) Session.SetValue("cli",cli) BUT, it seems only simple variables can be stored as session variables. Have I missed something (being new to the Python/ASP combo)? Comments would be much appreciated. Forgive me for bringing up a subject already discussed, but my searching thus far has been to no avail. Perhaps someone can offer an alternative solution? I should say, that using Apache is unfortunately not an option at this time; however I do aim to keep my options open. Thank you -Robin From duncan at NOSPAMrcp.co.uk Tue Nov 25 07:35:42 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 25 Nov 2003 12:35:42 +0000 (UTC) Subject: win32com (VBScript to Python) problem References: <6e24de564c.tim@worthy.demon.co.uk> Message-ID: Tim Howarth wrote in news:6e24de564c.tim at worthy.demon.co.uk: > I want to use this to shutdown all machines in the school in which I > work from a schedule on a server. > > I could use the VBscript version but there are long delays if a machine > is switched off - in Python I can thread the communication with > individual machines (to achieve this in VBScript I have to call a new > instance of w(c)script for each machine), effectively shutting them > down in parallel. This isn't a Python solution at all, but have you looked at PsTools (http://www.sysinternals.com)? It includes a command to remotely shutdown a machine including options to specify whether to log the user off, poweroff, reboot, hibernate etc. There is also a timeout so you can give users a chance to save their work (it displays a popup on their screen telling them the system is shutting down). You could just spawn a bunch of psshutdown processes off in parallel. It is free, although you cannot further redistribute it. PsTools also includes other programs which could be useful in a classroom environment (useful for teachers, devastating if the pupils get their hands on them and you don't have security set up right). -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From __peter__ at web.de Sun Nov 2 17:06:42 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Nov 2003 23:06:42 +0100 Subject: Two naive Tkinter questions References: Message-ID: Andrew Koenig wrote: > work with my application because I'm going to have lots of these buttons, > and I want to be able to set their colors independently. If you have many buttons with similar functionality, I'd suggest using a subclass, e. g.: import Tkinter as tk class ColorButton(tk.Button): def __init__(self, master, text, color): tk.Button.__init__(self, master, text=text, command=self.execute) self.color = color def execute(self): self["background"] = self.color root = tk.Tk() for color in "red green blue yellow".split(): ColorButton(root, text=color.capitalize(), color=color).pack() root.mainloop() Peter From tim.golden at viacom-outdoor.co.uk Tue Nov 25 10:18:33 2003 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 25 Nov 2003 15:18:33 -0000 Subject: win32com (VBScript to Python) problem Message-ID: > > http://tgolden.sc.sabren.com/python/wmi_cookbook.html > > (search for "Reboot a remote machine" -- I really must put > anchors on that > > page) > > > > If you follow that example, all you need to change is the final line > > to read something like: > > > > os.Win32Shutdown (Flags=12) > > Thanks to Tim, that works, though I still wonder why I can't do it > my original way. For the purposes of elucidation, I offer the following half-baked explanation, based on my re-reading my own code: For reasons unknown to me, you don't simply call an arbitrary named method on a WMI object; rather, you call the ExecMethod_ method of the object, having passed parameters in, which must themselves have been set up via Methods_ ().InParameters. The result and any outward parameters are picked up via the OutParameters property. (That was a bit simplified). Obviously, given the win32com module you can do all this by yourself. When all's said and done, that's exactly what my module is doing. However, it's as tedious as anything. So... the wmi module sets up a combination of __getattr__ hooks and currying classes to take the burden away from you. If you're interested enough, the relevant -- underdocumented -- code is in the _wmi_method class of the wmi module, hooked into from the __getattr__ method of the _wmi_object class which tries to work out whether you're referring to a method (in which case it sets up a proxy instance which is then called) or a property (in which case it returns the .Value property of the named property). There is a __setattr__ counterpart to all this, but as has been pointed out several times recently on this list, WMI is given more to reading than to writing. Well... you did ask! I would add, finally, that putting this code together some six months ago now, was both an education and a valuable experience, not simply in learning about WMI, but also in just how much information is available in the c.l.py archives if you look hard enough. I raise my hat to all those who have posted working code and explanations over the years. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. 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 pedery at ifi.uio.no Thu Nov 20 14:23:45 2003 From: pedery at ifi.uio.no (Peder Ydalus) Date: Thu, 20 Nov 2003 20:23:45 +0100 Subject: new guy References: Message-ID: <3FBD14C1.EC491FFA@ifi.uio.no> ...and remember to declare the e somewhere above the snippet to avoid a NameError... - Peder - From SEE_AT_THE_END at hotmail.com Sat Nov 15 21:19:54 2003 From: SEE_AT_THE_END at hotmail.com (Georgy Pruss) Date: Sun, 16 Nov 2003 02:19:54 GMT Subject: reading piped input in Windows References: <95ocrv0gts1dn66dvgn84n9j7rcthbdglf@4ax.com> Message-ID: Hmmm. t1.py | t2.py -- doesn't work, because: t1.py >tt -- DOES work t2.py >> sys.version '2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)]' >>> sys.getwindowsversion() # XP (5, 1, 2600, 2, 'Service Pack 1') G-: -- Georgy Pruss E^mail: 'ZDAwMTEyMHQwMzMwQGhvdG1haWwuY29t\n'.decode('base64') "Michael Geary" wrote in message news:vrctp0r6g8qf2b at corp.supernews.com... | Patrick Useldinger: | > I am writing a filter, i.e. a program that reads from stdin and writes | > to stdout. It works ok when run on its own, but does not work when I try | > to use another program's output. | > | > - The producer program (t1): | > print "a b c" | > print "d e f" | > | > - The filter program (t2): | > import sys | > r = sys.stdin.readlines() | > for i in r: | > print '<',i,'>' | > | > When i connect them using 't1 ? t2', I get the following error message: | > Traceback (most recent call last): | > File "[...]", line 2, in ? | > r = sys.stdin.readlines() | > IOError: [Errno 9] Bad file descriptor | > | > The same programs work correctly under Linux, so I suppose that Windows | > handles redirectionned input differently from 'normal' console input. | > Can anyone point me to a portable solution that works both under Windows | > and Linux? | | It works OK for me on Windows XP SP1 with Python 2.3.2: | | C:\Test\PythonTest >>t1.py | t2.py | < a b c | > | < d e f | > | | What versions of Windows and Python are you running? | | BTW, here's a simpler way to write the loop in t2.py: | | import sys | for line in sys.stdin: | print '<', line, '>' | | Or this, to get rid of the extra newlines (not clear if those are intended | or not): | | import sys | for line in sys.stdin: | print '<', line[:-1], '>' | | -Mike | | From __peter__ at web.de Fri Nov 21 19:34:45 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Nov 2003 01:34:45 +0100 Subject: Help Pliz ! stuck on page 4 of tutorial References: <91de052a.0311211610.48fdd0ea@posting.google.com> Message-ID: Adolfo wrote: > Hello everyone, I am a newbie starting Fredrik Lundh .pdf tutorial. > Running W2000. > > I am stuck in page four "Hello Again" program: > When I try running it, it shows the root Python window very fast and > dissapears. The intended Tk window with buttons: either does not > show, or dissapears fast before I can tell it is there. The first > program on the tutorial did run fine. > > Here's the program as shown on the tutorial: > > ==================================================== > from Tkinter import * > > class App: > > def_init-(self, master): > > frame = Frame(master) > frame.pack() > > self.button = Button(frame, text="QUIT", fg="red", > comand=frame.quit) self.button.pack(side=LEFT) > > self.hi_there = Button(frame, text="Hello", command=self.say_hi) > self.hi_there.pack(side=LEFT) > > def say_hi(self): > print "Hi there, everyone !" > > > root = Tk() > > app = App(root) > > root.mainloop() > =================================================== > > Any help will be much appreciated, > > Adofo Aguirre > Santa Barbara, CA If you have cut and pasted here exactly what you fed to the Python, proofreading should help. (Hint: def_init- and comand) Peter From bokr at oz.net Tue Nov 25 22:17:56 2003 From: bokr at oz.net (Bengt Richter) Date: 26 Nov 2003 03:17:56 GMT Subject: Execution state persistence for workflow application References: Message-ID: On Mon, 24 Nov 2003 08:11:57 +0100, Paolo Losi wrote: >Hi all, > I'm pretty new to the python language so please excuse me >if this is FAQ... I'm very glad to be part of the list! :-) > >I'm looking into a way to implement a generic workflow framework with python. >The basic idea is to use python scripts as the way to specify workflow >behavior. The framework should not only use scripts as a specification language >but is going to leverage on python interpreter for the execution of the >scripts. >One of the possible solution is to have a one to one mapping >between a interpreter process and a workflow instance. > I'm not clear on what all that meant ;-) for word_or_phrase in ["workflow framework", "workflow behavior", "workflow", "specification language", "intepreter process", "workflow instance"]: if you_please(): explain_what_you_mean_by(word_or_phrase) ;-) >Since I want to be able to model also long running processes I need to >cope with Execution state persistence. In other words.. >I'd like to stop the framework and restart it having all workflow >instance processes resume exactly where they left. > >Ideally I would be nice to have dumpexec() e loadexec() builtin functions >to dump and reload the state of the interpreter. I've not seen anything >like that unfortunately... That seems pretty large-grained. What happens if you have a power failure in the middle of dumpexec()? IOW, is sounds to me like you need something like a transactional database system to log your state changes, so you can pick up from a consistent state no matter what. The question then is how to design your system so that it has states that can be recorded and recovered that way. I think there would be a lot of overhead in capturing an entire system checkpoint image every time your app trasitioned to a new state, even if such a snapshot function were available. So OTTOMH ISTM you will wind up designing some state machine that can be initialized from a TDB, and which will log state changes incrementally in smaller chunks than all-encompassing blobs. I don't know what kind of control state you want to persist, but I would guess it should be in terms of getting from one data transaction to the next, not python loop variables and heap states and such. > >I've tried to look at exec statement but it doesn't seem to be good >for execution persistence... > >Questions are: > >- does there exist a python framework for workflow that use "workflow" is a bit too generic for me to guess what you have in mind. > python script as a specification language and that > support "long running" workflows? I don't want to reinvent the wheel... ditto > >- does the implementation idea quickly depicted makes sense to you? > >- how do you suggest to implement execution persistence? Is there > any "standard" solution? First thing in seeking help thinking about stuff is to define terms, perhaps informally by examples or metaphors, etc., since everyone doesn't speak the vernacular of your current focus. HTH Regards, Bengt Richter From donald.welch.nospam at hp.com Thu Nov 6 17:16:11 2003 From: donald.welch.nospam at hp.com (djw) Date: Thu, 06 Nov 2003 14:16:11 -0800 Subject: Assembler Parser/Lexer in Python References: <3fabc59e.42407448@news.dsl.pipex.com> Message-ID: <3faac858@usenet01.boi.hp.com> Simon Foster wrote: > > Anyone have any experience or pointers to how to go about creating > a parser lexer for assemble in Python. I was thinking of using PLY > but wonder whether it's too heavyweight for what I want. Anyone have > any thoughts? > -- > Simon Foster > Somewhere in the West of England Maybe kwParser? http://olympus.het.brown.edu/doc/gadfly/ -Don From tim.one at comcast.net Tue Nov 4 13:50:43 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 4 Nov 2003 13:50:43 -0500 Subject: prePEP: Decimal data type In-Reply-To: Message-ID: [Alex Martelli] > #- The Decimal type discussed in this PEP is the arithmetic fundament > #- for Money. Facundo started out with the idea of a PEP for a type > #- named Money that mixed arithmetic, parsing and formatting concerns. > Are you sure? Because, for example with a precision of 9: [Facundo Batista] > Are you sure? Because, for example with a precision of 9: > > 123 --> 123e0 > 1122334455667788 --> 112233445e7 > > Meaning that you lost the last digits. We're talking about billions > here, but an accounting person won't be happy with that. Then they shouldn't use such a tiny precision; that's essentially IEEE single precision. Default to a precision of, say, 100, and you can count the number of electrons in the universe exactly. Since each penny contains at least one electron ... . > I think that for Money with need a Fixed Point Decimal, but that's a > whole new problem. You really don't. Cowlishaw's spec provides all you really need (wrt arithmetical semantics) from a fixed point type, provided only that you ask for enough precision in advance. A precision of 100 is absurdly large for any conceivable accounting application. A precision of 20 would be way more than enough to account for total world economic output, down to the penny, since the beginning of time -- remember that the number of exactly representable quantities grows exponentially with precision. > ... > And I'm not quite sure that I understand what you mean with "unbounded > precision" (that you can not say with fixed or floating point). Could > you please explain that? thanks! Unbounded precision ("to the left" of the radix point) is what my old FixedPoint.py class did/does: if you multiply two FixedPoint integers, the result is exact, no matter how many decimal digits the exact product requires. The IBM spec allows for setting precision, but once set results are always rounded to that precision. IOW, under the IBM spec the precision is an upper bound on the number of significant digits in a result (but is a user-settable upper bound). In FixedPoint there is no upper bound. In REXX, people wanting the effect of unbounded precision usually set DIGITS (analogous to the spec's precision) to, e.g., 999999999. Not a good idea for most divisions , but for + - and * you'd run out of memory before a result ever got rounded. From apardon at forel.vub.ac.be Tue Nov 25 04:59:32 2003 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 Nov 2003 09:59:32 GMT Subject: Hidden files/folders on Windows Message-ID: Can someone explain how I can check whether a file or folder is hidden, using python. I have found references to win32api on the web, which would provide what I need but I couldn't find the module itself? Thanks in advance! -- Antoon Pardon From ruari at charliefortune.com Sat Nov 1 14:20:03 2003 From: ruari at charliefortune.com (ruari mactaggart) Date: Sat, 1 Nov 2003 11:20:03 -0800 Subject: global variables ? Message-ID: how do I assign a value to a variable inside a function then use it in the main body ? i am trying to unpickle a dictionary in a function to use it in the program ruari From csaba at phony_for_avoiding_spam.org Thu Nov 20 10:29:36 2003 From: csaba at phony_for_avoiding_spam.org (Csaba Henk) Date: Thu, 20 Nov 2003 15:29:36 +0000 (UTC) Subject: cooler piping Message-ID: For me, one reason for using Python is that with the help of it I can rid of several problems that I faced with during writing scripts in Bourneish shells. Biggest of these problem was the quotation madness stemming from the typelessness of the shell language. When using Python as a shell replacement I often launch apps from Python and use different piping constructs to pass data to/get data from these apps. I expect from the language that I could perform these actions simply and effectively. However, its not the case: there is os.pipe() which is low-level and its usage is complex, and there are several popen functions which are simple to use, but they evaluate the given command by passing it to the shell, throwing me back to the middle of the quotation hell I want to escape from. A typical case is when one tries to find out some info about a file by invoking the "file" command on it: the name of the file can be (almost) anything, thus doing os.popen("file " + filename) gets sucked easily (here filename is a variable storing the name of the file). (Don't tell me there is a module in Python with the fucntionality of the file command [I don't know wheter is], I could find out many similar examples.) What would be cool is having a function with an execvp-like syntax: if I could do something like os.fancypopen('file', ['file',fname])... Considering me, I came over this problem by using the following module: import os import sys def fancypopen(fname,args): pfd = os.pipe() if os.fork() == 0: os.close(pfd[0]) os.dup2(pfd[1],sys.stdout.fileno()) os.execvp(fname,args) else: os.close(pfd[1]) return os.fdopen(pfd[0],'r') def fancypopen2(fname,args): pfdout = os.pipe() pfdin = os.pipe() if os.fork() == 0: os.close(pfdout[0]) os.dup2(pfdout[1],sys.stdout.fileno()) os.close(pfdin[1]) os.dup2(pfdin[0],sys.stdin.fileno()) os.execvp(fname,args) else: os.close(pfdout[1]) os.close(pfdin[0]) return (os.fdopen(pfdin[1],'w'),os.fdopen(pfdout[0],'r')) sfancypopen = lambda f,a: fancypopen(f, [f] + a) sfancypopen2 = lambda f,a: fancypopen2(f, [f] + a) Now my question is that shouldn't (doesn't) Python include a *standard* module like this? That wouldn't be much hassle but would improve the usability of the language... -- Csaba "There's more to life, than books, you know but not much more..." [The Smiths] *** If you want to send me a mail, see it in the mailto link at http://www.renyi.hu/~ekho/egyelore.html From jjl at pobox.com Fri Nov 7 08:10:47 2003 From: jjl at pobox.com (John J. Lee) Date: 07 Nov 2003 13:10:47 +0000 Subject: Python, Unicode, Excel and Web Tesing References: Message-ID: <87k76c1fzc.fsf@pobox.com> calfdog at yahoo.com writes: [...] > I have been running into problems with Unicode as I can see others > have too. > I have seemed to find a simple solution when printing > > Since Excel seems to give back this format (u'Test1',) > > If I use this code I get > (u'Test1',) > (u'Test2',) > (u'Test3',) > (u'Test4',) > (u'Test5',) [...] > for i in val: > print i #Prints the unicode charaters These are length-1 tuples containing unicode strings. [...] > If I use the code below it works fine. > Test1 > Test2 > Test3 > Test4 > Test5 [...] > for i in val: > print i [-1] #Prints without the unicode charaters These are unicode strings. Why no u'' business? First, you need to know that str()'s job is to print readable strings. repr(obj)'s job is to print a string such that when you eval() it, you get back the same thing you started out with: >>> text = repr(u'foo') >>> eval(text) u'foo' >>> ie. repr(u'foo') == "u'foo'" whereas str(u'foo') == "foo" Now, print obj prints str(obj), but str(sequence) typically returns a string containing the repr() of every item in the sequence, NOT the str() of every item in the sequence. Hence: >>> str(u'foo') 'foo' >>> str((u'foo',)) "(u'foo',)" >>> John From usenet03q2 at hczim.de Sun Nov 2 18:52:42 2003 From: usenet03q2 at hczim.de (Heike C. Zimmerer) Date: Mon, 03 Nov 2003 00:52:42 +0100 Subject: PyQt, Qt, Windows and Linux References: Message-ID: Alex Martelli writes: >> 3) Can I create a .exe file for my windows on my Linux and copy it over? > > That's an issue for such tools as py2exe and McMillan's "installer"; at > this time, I do not believe they support that "cross-packaging" > functionality. I'm doing that with the McMillan installer using wine on Linux and it works for me. Heike From max at alcyone.com Tue Nov 18 04:30:55 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 18 Nov 2003 01:30:55 -0800 Subject: True inconsistency in Python References: <3FB8847F.6CB1BECA@alcyone.com> <3FB92086.9CBD0761@alcyone.com> <8qhirvgi2sf5l3vkfocq65mcb94c6pbb9s@4ax.com> <3FB95BC5.A33E6DDE@alcyone.com> <34nirv8qfphublscs12ct3acufciv828rp@4ax.com> <3FB98846.D5688F09@alcyone.com> Message-ID: <3FB9E6CF.C5F6C4D6@alcyone.com> Ron Adam wrote: > The main inconsistencies of 'True' and 'False' are due to the > possibility of the names 'True' and 'False' being reassigned. > > And the best way to fix this is by making 'True' and 'False' literals > or constants. But True and False are no different from None, int, str, or any of the other builtins. > It looks to me the benefits of changing this one item are worthwhile, > and the drawbacks if it very low. It is also consistent to have them > as basic constants and/or literals in the same way digits and the > alphabet are. The values True and False are to Type boo() as digits > are to int() or floats(), and as the alphabet is to string(). But, as I said, you're not going to run into this problem unless you're doing unsafe things already (like `from module import *'), or letting people you don't trust edit your source. I don't see this as a big problem. Accidental rebindings of things like int, str, and other builtin types/functions with common names seem _far_ more common than "accidentally" rebinding True or False. > So they have not special property of there own. From what I > understand, being a built in is a matter of where the code is, and > doesn't have anything to do with what it does. It's a practical > matter that the most frequently used items are built ins. Yes. And builtins other than True and False are far more frequently accidentally rebound. > So the inconsistency I saw was in that True and False are not treated > the same as other types made up from literals. 1 is always equal to > 1, and it's never equal to 2. The same can't be said for True and > False and bool(), It's not true for int, either. > Terry Reedy has pointed out to me that this will likely be changed in > the future. I think it will make Python more consistent by preventing > the possible reassignments of True, False, and None. It will change in the sense that rebinding these names may result in warnings or errors (already there's a warning for rebinding None in the usual way), not that they'll become literals. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ God will forgive me; that's his business. -- Heinrich Heine From peter at engcorp.com Wed Nov 19 09:38:21 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 19 Nov 2003 09:38:21 -0500 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> Message-ID: <3FBB805D.40A8DA75@engcorp.com> "John J. Lee" wrote: > > "Dave Brueck" writes: > > > Robin wrote: > > > It seems that the rotor module is being deprecated in 2.3, but there > > > doesn't seem to be an obvious alternative. I'm using it just for > [...Dave has switched to AES] > > Since I'm not going to great lengths to hide the key, it works out to be about > > the same strength of encryption as rotor. ;-) > > Quite. I don't understand why it's deprecated. We've known since the > fifties that the algorithm is broken, so wasn't it clear from the > start that this was for obfuscation, not strong encryption? Shouldn't > we just add a warning to the docs (if there's not one there already)?? If it's really for obfuscation, wouldn't a simpler algorithm be sufficient, such as "XOR each byte with 0x5A" or something like that? If the answer is "no, that's too easy to break", then it's not really just for obfuscation, is it? -Peter From mwh at python.net Mon Nov 24 09:53:56 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 24 Nov 2003 14:53:56 GMT Subject: 2.2.2 Annoyance References: Message-ID: "Jegenye 2001 Bt" writes: > Caveat: > > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) > Type "help", "copyright", "credits" or "l > >>> l = [1,2,3] > >>> l[1] > 2 > >>> l.__getitem__(1) > 2 > >>> l.__getitem__(slice(1)) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: an integer is required > >>> > > According to the manuals of Python 2.2.2, passing a slice object to > __getitem__ is all right and should work... Really? Where does it say that? > For Python 2.3 passing a slice object to __getitem__ does work though. Yes. Do you have a good reason for sticking to 2.2? Cheers, mwh -- Python enjoys making tradeoffs that drive *someone* crazy . -- Tim Peters, comp.lang.python From daniel.dittmar at sap.com Mon Nov 24 05:05:16 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Mon, 24 Nov 2003 11:05:16 +0100 Subject: Compiling Python extensions for different Python installation References: <1069633966.973970@cousin.sw.oz.au> Message-ID: John Ky wrote: > directory. I can use this fine. When I build my own > C module extension and try to run it from Python 2.3 > however, I get this message: > > /test-wrk/test_manager/commonlib.py:12: RuntimeWarning: Python C API > version mismatch for module elxml: This Python has API version 1012, > module elxml has version 1011. > > Could this be because the compilation was made against > 2.2 and run from 2.3? If so, is there a way to force > my module compilation against 2.3? Just make sure that any include directives in your Makefile point to your Python 2.3 include directory. It may be necessary to copy Python-2.3/pyconfig.h to Python-2.3/Include/pyconfig.h. Daniel From jimmy at retzlaff.com Sat Nov 1 12:35:01 2003 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Sat, 1 Nov 2003 09:35:01 -0800 Subject: py2exe question Message-ID: Alex Martelli wrote: > achrist at easystreet.com wrote: > > Alex Martelli wrote: > >> achrist at easystreet.com wrote: > >> > >> > The py2exe says that a console app should have the --console option > >> > and a windows app should have the --windows option. > >> > > >> > What is the way to py2exe a python program that uses both console and > >> > windows gui? > >> > Haven't tried, but logically it should be a console -- this doesn't > >> > restrict > >> what OTHER modules you can import, it just uses the equivalent of a .py > >> script run with python.exe rather than a .pyw run with pythonw.exe, > i.e. > >> a "DOS box" console does appear when the program is run. > > > > Logically, you don't need these switches. Outside of py2exe a *.py > > gets a console and can open gui windows, a *.pyw is a pure gui > > program. Why the switches atall? IDK? Thought I'd ask. > > The switches let you control what goes on explicitly, just as > you can control it explicitly by choosing one or the other of > the two interpreters (python.exe or pythonw.exe) at a command > prompt. I don't know what you mean by the 'idk' question. I think Al's point may be that if you run py2exe on a .pyw script it should automatically use the pythonw.exe stub and if you run it on a .py script it should use the python.exe stub. I wouldn't care for that behavior unless I could override it with the switches. I always use a .py extension when developing my GUI apps so I can see console output which is very handy for debugging output and seeing any unhandled exceptions. When I deploy my GUI app, I don't want the user bothered by a console so I explicitly ask for a windows only app. > > I'm having a little trouble getting a py2exe executable to run on > > a machine wo python installed. Just wondered if this has anything to > > do with it. > > I don't see the connection. As mentioned earlier (was it another thread?), temporarily letting py2exe display a console can aid in debugging py2exe specific problems by letting you see unhandled exceptions and other output. Once things are working then turn the console off again. I do have vague memories of hearing about people having problems with some buffers filling up if there is no console and there is a significant amount of console output. Temporarily turning on the console would let you know if you have tons of console output that might expose such a problem. I don't, however, see how this kind of thing would differ between machines with and without Python installed. Jimmy From adalke at mindspring.com Sat Nov 15 05:01:27 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 15 Nov 2003 10:01:27 GMT Subject: Python's simplicity philosophy References: Message-ID: Uncle Tim: > what do you call the act of changing a real-world > object, like a refrigerator or a wide-screen plasma TV, into a string, a > (function, args) tuple, or a (function, args, state) tuple sufficient to > reproduce the fridge or TV? I call it "documenting what I own for insurance purposes." I need the receipt and/or, for good measure, a picture of the TV in my home. The exercise of turning those into a string in such a way that my insurance company will accept it as proof is left to the student as an exercise. Well, you did ask. :) Interestingly, to pickle something you can add vinegar, which is a mild acid. Sadly, the chemistry I know is very skewed having come to chemistry via biophysics. I can't tell if adding vinegar makes the brine slightly reducing or slightly oxidizing. It would be quite amusing if the former. Will a Real Chemist [tm] please chime in? Andrew dalke at dalkescientific.com From mis6 at pitt.edu Wed Nov 12 07:10:38 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 12 Nov 2003 04:10:38 -0800 Subject: Metaclass' __init__ Does not Initialize References: Message-ID: <2259b0e2.0311120410.78f75787@posting.google.com> "achan" wrote in message news:... > As I was trying to create a metaclass, I found out that __init__ defined in > it does not initializes at all 1. Please, test your attempts before posting, it would be helpful for you as for the people who try to understand you. 2. Are you sure you want __slots__? 99.9% of times __slot__ are not needed, I never use them, and I would rather NOT have this feature available from Python (yes if available from C) since it is an endless cause of confusion. 3. Here is an example of a working metaclass with an __init__ as you want: class CMeta(type): def __new__(mcl, name, bases, dic): def __init__(self): for s in self.seq: print s newDict = {'__init__': __init__, 'seq' : [123]} return super(CMeta,mcl).__new__(mcl, name, bases, newDict) class Test(object): __metaclass__= CMeta a = Test() #=> 123 You may figure out for yourself your mistakes. Michele Simionato From Mike at DeleteThis.Geary.com Wed Nov 12 18:09:50 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 12 Nov 2003 15:09:50 -0800 Subject: Saving a picture contained in a web page to disk References: <25e5rvg60kf9c4l08kars34jgorqcpado3@4ax.com> Message-ID: Giulio Cespuglio: > I would like to save to disk a picture contained in a webpage. > > Unfortunately the image is dynamic, so the url is actually a query > which looks like > > http://adfarm.mediaplex.com/ad/bn/2397-11787-1843-5?mpt=1068644406357385 > > rather than the standard > > http://img-cdn.mediaplex.com/ads/2397/11787/q2_dell_inspiron_120x600.gif That doesn't matter at all. > I've been told that a scripting language like Perl, Python or PHP is > my best bet for this kind of tasks, would you agree? Absolutely! :-) > Could you please give a few function names to look at as a starting > point? > That should suffice, although a code snippet would be greatly > appreciated. Try running this code and see what you think: ######################### import urllib def saveUrlToFile( url, fileName ): f = open( fileName, 'wb' ) data = urllib.urlopen(url).read() f.write( data ) f.close() saveUrlToFile( 'http://adfarm.mediaplex.com/ad/bn/2397-11787-1843-5?mpt=1068644406357385', 'test.gif' ) ######################### -Mike From pf_moore at yahoo.co.uk Tue Nov 18 16:36:43 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Tue, 18 Nov 2003 21:36:43 +0000 Subject: PEP 321: Date/Time Parsing and Formatting References: <2ae25c6b.0311172147.65058189@posting.google.com> Message-ID: "John Roth" writes: > The trouble with "guess the format" is that it's not possible > to do it correctly in the general case from one sample. > Given enough samples of one consistent format, it's > certainly possible. However, that's a two pass process. I think you can do it with a hint or two. The key one is whether in ambiguous cases, you choose DD/MM or MM/DD. You need a second hint with 2-digit years, as 01-02-03 is *very* ambiguous (given that putting the year in the middle is insane, you only need a flag saying whether the year is at the start or the end). I'm not sure what other ambiguities you'd need to cater for? Paul. -- This signature intentionally left blank From aleax at aleax.it Fri Nov 14 05:46:04 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Nov 2003 10:46:04 GMT Subject: case-sensitivity References: <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <9l16rv0j7qd0drfap10boab5gsmh7v37o3@4ax.com> Message-ID: Ron Adam wrote: ... > I wonder how difficult it would be to write a program that searches > the library and counts the number of instances like spelling with > differing case are used? You mean "used within the same namespace"? Not too hard, since the key test is nothing more than something like: o so basically it boils down to finding all namespaces of interest. Easy for modules, easy for classes, NOT easy for class-instances as you'd really have to create the instances to check for such cases as, e.g.: class Foo(object): def blab(self): return self.BLAB def __init__(self, BLAB): self.BLAB = BLAB So here's a q&d check for such module-level conflicts I just cobbled together (avoiding obsolete modules): import sys, glob, os.path, sets avoid = sets.Set(''' FCNTL posixfile pre regsub statcache TERMIOS this tzparse xmllib '''.split()) for where in sys.path: modules = glob.glob(os.path.join(where, '*.py')) modnams = [os.path.basename(m)[:-3] for m in modules] for m in modnams: if m in avoid: continue try: modobj = __import__(m) except ImportError: continue dd = dir(modobj) lowdd = [ n.lower() for n in dd ] slowd = sets.Set(lowdd) if len(dd) != len(slowd): print '%s:'%m, n = 0 for d in dd: if lowdd.count(d.lower()) != 1: print d, n += 1 print The hits in the top-level of the standard libraries are: binhex: BinHex HexBin binhex hexbin copy: Error error popen2: Popen3 Popen4 popen3 popen4 pydoc: Doc doc random: Random random repr: Repr repr sre_parse: SUBPATTERN SubPattern sre: TEMPLATE template tarfile: VERSION version threading: _VERBOSE _Verbose tokenize: COMMENT Comment NAME NUMBER Name Number STRING String string xmlrpclib: Boolean boolean there are more in lib-tk and Numeric, but not everybody will be interested in those, I guess. Alex From pythonguy at Hotpop.com Mon Nov 17 00:58:55 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 16 Nov 2003 21:58:55 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> <84fc4588.0311140319.3778de15@posting.google.com> <874qx79eez.fsf@pobox.com> Message-ID: <84fc4588.0311162158.54f8fd80@posting.google.com> I think my O.P has been taken out of context here. Python is a great language, it is flexible, agile, great for newbies, good for experts at the samt time, allows for prototyping blah blah... I am sure everyone in this group will tend to agree with most of these oft repeated statements. My question was that, "If it is such a great language, why it is not getting the recognition it deserves"? Probably there is a need to change the attitude of Pythonistas about their language. It needs to probably come out from that "high pedestal" where books get written only if there is a definite need percieved. One way to do that is may be, just may be to actually create market for new python books. The "right" way to do this is by synergy. First we need to popularize the language, get the website in right shape, evangelize it, get it accepted by the Suits, then it will get accepted by the Suits as their language of choice in s/w projects and in due course every Java or C++ guy will be buying new Python books from the bookstall. Ah, but this topic often gets discussed again and again and I was wondering if there is a tendency to come full circle starting from the book topic, without really achieving anything. In fact, I have been commisioned to write a series of articles on Python in a popular computer magazine in India. I am trying to do what I can to evangelize the language in and around where I live, as I percieve potential in it, and perhaps potential for me to grow with the language. There is no way AFAIK any index to measure the popularity of a language by the plethora of books written on it. But it is common sense that if there are many authors writing books on a language it has got to be popular. Doesn't popularity mean the number of people interested in a certain thing? So if 'n' guys are writing books on Python and 'n*100' guys on C++, I would say, not as a techie, but as an average person, that C++ is more popular than Python. There was a company called Wrox writing P2P (Programmer 2 Programmer) books on many technical topics. I think it got absorbed by Wiley recently. Their choice of topics was "Popular" languages and technologies used by practicing software developers. I never saw a Python book in their stable. Of course, again dont start a thread about the technical perfection of Wrox books, since I know that their style & content cannot be compared with an O'reilly nutshell book. But as again, I am not talking about anything regarding the "greatness" of the language, but just simple arithmetic. -Anand "Brandon J. Van Every" wrote in message news:... > John J. Lee wrote: > > pythonguy at Hotpop.com (Anand Pillai) writes: > > [...] > >> There might have been thousands of books published in C/C++ > >> language and they have all helped to popularize it in one > >> or the other way. Contrast, in the python world we have one > >> Alex Martelli, one Wesley Chun, one David Mertz, really > >> countable by hand. > > > > And thank heavens for that. Most books on C++ (and the same goes for > > all kinds of other technical subjects) actually do nothing other to > > make it harder to find the decent books. Ironically, the good books > > often seem to get published first, followed afterwards by a glut of > > awful ones jumping on the bandwagon. So much for competition... > > But the questions are: > 1) do the "crappy" books sell briskly to someone? > 2) is a plethora of books a healthy sign for a language? From magnus at thinkware.se Fri Nov 28 12:07:13 2003 From: magnus at thinkware.se (Magnus Lyck?) Date: 28 Nov 2003 09:07:13 -0800 Subject: Python bug? Named parameters in recursive calls sometimes confuses python? References: <258fd9b8.0311271503.c134a25@posting.google.com> Message-ID: <258fd9b8.0311280907.6bbc4203@posting.google.com> Michael Hudson wrote in message news:... > magnus at thinkware.se (Magnus Lyck?) writes: > > Isn't it possible that the code has just returned twice? I don't know... But in that case, we have accidentally retained the value of "column" which we had one step down in the recursion, instead of reverting to the object which is bound to the local variable at this level. Still a Python bug! I wrote: > 2. Column G46_ANSTID (10002728) Table TGLON (10002512) > 3. Column G46_ANSTID (10002728) Table TGANST (9282768) <= N.B. As you can see below, the variables passed in to recursiveCopy as column and table are reassigned together, in: "for child_table, column in self.getDepTables(..." getDepTables returns data it gets directly from SQL queries, so it should never return a value which is passed in, and either way, in my case it's table that changes while column stays the same. (Are unicode objects interned?) Anyway, there is no way that the database could return the combination G46_ANSTID / TGANST. G46_ANSTID belongs with TGLON, and TGLON is dependant on TGANST. *IF* we simply returned from the recursive call to the previous level, column should be G06_PERS_INTRID (9282024), just as it was before, when table was TGANST (9282768). Column and table are reassigned together. If one of them changes while the other doesn't, there is something wrong! It happens here: def recursiveCopy(self, table, column, old_val, new_val): # Fetch row from source database print "1. Column %s (%i) Table %s (%i)" % (column, id(column), table, id(table)) sql = "SELECT * FROM %(schema)s.%(table)s WHERE %(column)s = ?" rows = self.src_fetch(sql, params=(old_val,), table=table, column=column) # I use "sql % kwargs" in a method called by src_fetch print "2. Column %s (%i) Table %s (%i)" % (column, id(column), table, id(table)) for row in rows: # Replace foreign key with value for target DB print "3. Column %s (%i) Table %s (%i)" % (column, id(column), table, id(table)) row[column] = new_val # <= This is where it crashes. # What's interesting is the print above before the crash. # row is a db_row.IMetaRow instance instance. # We need primary key values for recursive find # Only bother for table with a single p.k. parent_p_key_cols = self.getPK(table) if len(parent_p_key_cols) == 1: parent_p_key_col = parent_p_key_cols[0] oldId = row[parent_p_key_col] newId = self.insertIntoTarget(table, row) for child_table, column in self.getDepTables(table, parent_p_key_col): self.recursiveCopy(child_table, column, oldId, newId) > Unless you can produce an example that can be run somewhere other than > your setup, it's going to be pretty hard for someone else to debug > this! I realize that... :) I was hoping that someone else had seen something similar. Unfortunately I'm not even at liberty to publish the code I write now... The bug only appears for particular data (but it occurred twice, on different computers) and the program assumes a certain database etc. I doubt that I'll be able to reproduce it in a small package, and it wouldn't surprise me if it's an NT 4 specific bug. (Not a lot of users on that old platform I guess...) Assuming I have understood what the problem is, the relevant parts of the code looks something like this: class X: def fetch(self, sql, params, **kwargs): ... cursor.execute(sql % kwargs, params) return a list of db_row objects from cursor.fetchall() def recCopy(self, table, column, ...): sql = '...' rows = self.fetch(sql, params=(...), table=table, column=column) for row in rows: ... for child_table, foreign_key_col in getDependantTables(table): self.recCopy(child_table, foreign_key_col , ...) In the middle of one call of recCopy, a local variable seems to be rebound. The suspects are: * Recursion? * Named parameters, especially "x=x"? * Unicode objects? * Something in win32all/adodbapi? * Something in db_row? Metaclasses? (It's the pure Python version 0.8) * Windows NT 4.0 SP 6? * Just me? Can anyone suggest a way to go forward here? I have found ways to avoid the problem, but there seems to be a sinister Python bug lurking here and I would like to help bring it to the surface. Can I see what recursion depth I'm currently at? I have never used the more arcane powers of Python introspection such as the inspect module etc. From wmgill at wmgill.com Mon Nov 3 11:02:46 2003 From: wmgill at wmgill.com (WmGill) Date: Mon, 3 Nov 2003 11:02:46 -0500 Subject: form processing question References: <423f3$3fa58837$42a655ea$20950@msgid.meganewsservers.com> Message-ID: <5804$3fa67ce3$42a655ea$5957@msgid.meganewsservers.com> > You probably will be happier if you use something other than CGI,... I thought the cgi interface was the standard for HTML form processing? > I believe os.environ()['SCRIPT_NAME'] should give you what you want... I don't see where knowing the script name helps? Others have also suggested using other programs. I obviously need to be more clear in what I thought was a simple question. Lets say I have a simple html form that asks for: First Name, Last Name, department, Employee ID, and comments. An emplyee fills out the form,and clicks submit. My script looks up the employee ID and doesn't find him/her, so it returns (displays) the form for correction, but leaving all the submitted information in the original input fields so that the employee doesn't have to re-enter everything. I know how to do this in PHP, but want to try it in Python. Bill "Ian Bicking" wrote in message news:mailman.352.1067818417.702.python-list at python.org... > On Nov 2, 2003, at 4:41 PM, WmGill wrote: > > I am experimenting with Python, and want to convert some of my PHP > > scripts > > to python cgi scripts. In PHP I use PHP_SELF for the action target. > > This > > way I can "reuse" data in fields (i.e. if the user enters data in a > > field > > then submits the form, it comes back already filled in on each > > subsequent > > iteration). I know I can do this in Python, but before I spend a lot > > of > > time, is it very complicated, or can form field values be > > (re-)populated > > easily? > > You probably will be happier if you use something other than CGI, but > for CGI I believe os.environ()['SCRIPT_NAME'] should give you what you > want. (This URL introspection differs considerably between frameworks) > > -- > Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org > > From ryasko at gator.net Wed Nov 5 17:49:14 2003 From: ryasko at gator.net (Greg Yasko) Date: Wed, 05 Nov 2003 17:49:14 -0500 Subject: Perl file::find module equivalent in Python? Message-ID: Hi. Does anyone know if there's an equivalent of Perl's file::find module in Python? It traverses a directory. I've googled extensively and checked this newsgroup and can't find anything like it for Python. I'd be using it in Linux to regularly search for files with a script. Is this a good application for Python or does Perl have more functionality for quick & simple scripting in Linux? Thanks. -Greg Yasko From jjl at pobox.com Mon Nov 10 18:54:30 2003 From: jjl at pobox.com (John J. Lee) Date: 10 Nov 2003 23:54:30 +0000 Subject: Load Python Scripts from Memory References: <4d1a42cd.0311100525.6f846ead@posting.google.com> Message-ID: <87oevjdbk9.fsf@pobox.com> Alex Martelli writes: > Dean Ellis wrote: [...] > Run this code once, e.g. at program startup, and assuming the > get_pickled_... functions know how to get a pickled sourcecode > string or codeobject from wherever, the rest should work (I'm [...] Why would you want to pickle the source for transit over the network? John From wongwung at hotmail.com Mon Nov 24 11:31:55 2003 From: wongwung at hotmail.com (zhi) Date: 24 Nov 2003 08:31:55 -0800 Subject: Why should input(prompt="hello:") fail? Message-ID: <37ba82ff.0311240831.6e0dfba7@posting.google.com> Really confused, when I use keyword style argument as following: >>> input(prompt="hello") Traceback (most recent call last): File "", line 1, in -toplevel- input(prompt="hello") TypeError: input() takes no keyword arguments While the library reference says the function is: input( [prompt]) so, it should work.:( I am using python 2.3 for windows. Have anyone tried this? I am new to python, please help me, thanks. From david.bear at asu.edu Mon Nov 3 17:29:07 2003 From: david.bear at asu.edu (David Bear) Date: 03 Nov 2003 15:29:07 -0700 Subject: tar interface Message-ID: I just googled for a 'python tar interface module' and got over 33000 hits. ug. I'm looking for a python module that either interfaces to gnutar in a pythonic way or reads/writes tar files directly. I know there's always os.popoen etc, but was hoping for something a little more .. -- David Bear phone: 480-965-8257 fax: 480-965-9189 College of Public Programs/ASU Wilson Hall 232 Tempe, AZ 85287-0803 "Beware the IP portfolio, everyone will be suspect of trespassing" From woiski at dem.feis.unesp.br Wed Nov 26 13:11:33 2003 From: woiski at dem.feis.unesp.br (Emanuel Rocha Woiski) Date: Wed, 26 Nov 2003 16:11:33 -0200 Subject: No messages... Message-ID: <3FC4ECD5.2060703@dem.feis.unesp.br> I wonder what happened to the list.... Is it just me being punished for an alleged "bouncing"? (I have no problem at all with my mail server...) Thanks for any enlightenment.. woiski From francisgavila at yahoo.com Wed Nov 19 08:11:41 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Wed, 19 Nov 2003 08:11:41 -0500 Subject: Callable generators (PEP 288: Generator Attributes, again) References: <55688f89.0311180211.7ab1bc30@posting.google.com> Message-ID: Aahz wrote in message ... >In article <55688f89.0311180211.7ab1bc30 at posting.google.com>, >Francis Avila wrote: >> >>A little annoyed one day that I couldn't use the statefulness of >>generators as "resumable functions", [...] > > But generators *are* resumable functions; they just >don't permit injection of new values into their state. I see then that I don't need to convince you. :) But it is because you can't inject new values into their state that they are not resumable functions. They're pure state, not functions-with-persisting-state. If they were resumable functions, we could call them like functions and be returned values based upon passed parameters, except that the algorithm used would depend upon the generator's internal state. Now, the above sounds like a class, doesn't it? But yet we think of generators as functions. My post was an attempt to explain why this is so, and argue for a set of semantics based on that perception (because the PEP seems to want to regard them as classes). Generators are funny because they share properties of classes and functions, but I think they're more function-like than class-like, and that's why class-like interfaces (i.e. generator attributes) are a strange fit. >As Michele >pointed out, it's easy enough to wrap a generator in a class if you want >to monitor the changing state of an attribute. True--you simply have to use 'self' to access public values, as the PEP suggests. The only advantage the PEP has is that we don't need to wrap generators in a function to gain access to public attributes--the only reason for the wrapper class anyway is to give a namespace between global and local. Anyone can do that, so why do we need a magic __self__ attribute? So I agree, I don't like the PEP's specific proposal, but I still like the functionality it's attempting to provide. >The problem with injecting values is that there's no way to pick them >up; it's a "push" solution rather than a "pull" solution. You mean "pull" rather than "push"? Well, I just suggested a way to pick them up which is no different than how a function picks up parameters--they're pushed in rather than pulled in, by overwriting the local namespace before advancing the generator's state. Would you care to comment on my suggestion? -- Francis Avila From fjh at cs.mu.oz.au Tue Nov 11 06:06:59 2003 From: fjh at cs.mu.oz.au (Fergus Henderson) Date: Tue, 11 Nov 2003 11:06:59 GMT Subject: Python from Wise Guy's Viewpoint References: <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <3F9D5D21.2060408@ps.uni-sb.de> <3fb097fe$1@news.unimelb.edu.au> Message-ID: <3fb0c2cd$1@news.unimelb.edu.au> Pascal Costanza writes: >Fergus Henderson wrote: > >> Suppose the original ML program defines the following functions >> >> foo : int -> int >> bar : string -> string >> ... >> >> We can add dynamic typing like this: >> >> datatype Generic = Int of int >> | String of string >> | Atom of string >> | Cons Generic Generic >> | Apply Generic Generic >> | ... > ^^^ >How many do you need of those, especially when you want to allow that >type to be extended in the running program? In Haskell you would just use "Dynamic" instead of the above, and be done with it. In Mercury, you'd just use "univ". In SML, I don't know. Probably none. In fact, the first two entries in the type above are not really necessary, you could just represent ints and strings as Atoms. Even Apply could be represented using just Cons and Atom: instead of Apply x y, we could use Cons (Atom "apply") (Cons x y). >> Note that our symbol table includes an entry for the function "define", >> so that eval can be used to modify the dynamic bindings. > >DEFUN is just one example. What about DEFTYPE, DEFCLASS, DEFPACKAGE, and >so forth... Well, DEFTYPE in lisp really just defines a function, doesn't it? So that's not much different than DEFUN. Likewise, DEFCLASS just defines a collection of functions, doesn't it? OK, maybe these also record some extra information in some global symbol tables. That is easily emulated if you really want. I don't know exactly what DEFPACKAGE does, but if the others are any guide, it's probably not too hard either. -- Fergus Henderson | "I have always known that the pursuit The University of Melbourne | of excellence is a lethal habit" WWW: | -- the last words of T. S. Garp. From peter at engcorp.com Tue Nov 11 10:06:08 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Nov 2003 10:06:08 -0500 Subject: response time References: <1jSrb.2419$9_.105379@news1.tin.it> <87d6bzetsz.fsf@pobox.com> <3FB01787.529425BC@engcorp.com> <87u15bf6qs.fsf@pobox.com> Message-ID: <3FB0FAE0.73ECA8A1@engcorp.com> "John J. Lee" wrote: > > Peter Hansen writes: > [...] > > Strange, but based on a relatively mundane thing: the frequency (14.31818MHz) > > of the NTSC color sub-carrier which was used when displaying computer output > > on a TV. This clock was divided by 3 to produce the 4.77MHz clock for the > [...] > > in time-keeping, which then counted on every edge using a 16-bit counter > > which wrapped around every 65536 counts, producing one interrupt every > > 65536/(14.31818*1000000/12) or about 0.5492 ms, which is about 18.2 ticks > [...] > > That doesn't explain it AFAICS -- why not use a different (smaller) > divisor? An eight bit counter would give about 0.2 ms resolution. Can you imagine the overhead of the DOS timer interrupt executing over 500 times a second?! It would have crippled the system. In fact, from what I recall of the overhead associated with that interrupt, that might well have consumed every last microsecond of CPU time. Also, the hardware probably doesn't even support an "eight bit counter". That is, there's a good chance that the behaviour described comes entirely "for free", after setup, whereas using any other value would have required a periodic reload, in software, which would have been deemed an unacceptable burden on performance. I believe one of the first links to the Google search I mentioned has the part number of the timer chip in question, so you could investigate further if you're curious. And if you wonder why Windows still had to stick with the same value, well, let's just say that it's one of the best proofs that I've seen that even Windows 98 is nothing more than a glossy GUI shell on top of DOS. -Peter From noemail at noemail4u.com Fri Nov 14 13:07:44 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Fri, 14 Nov 2003 18:07:44 GMT Subject: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <8hfsb.7707$nz.895@newsread2.news.pas.earthlink.net> Message-ID: On Wed, 12 Nov 2003 13:19:15 -0500, Douglas Alan wrote: >I would say that if you didn't get introduced to at least the concept >of functional programming and a hint of how it works, then something >was seriously wrong with your CS education. >|>oug I've been lurking this thread for a while, but missed the beginning. Can I ask where you got your CS education (school and year)? >From the conversation, it seems that right or wrong, your education exceeds those in this group. Where should I send my children such that they receive a better CS education that I? --dang From JTesser at nbbc.edu Fri Nov 21 15:00:44 2003 From: JTesser at nbbc.edu (Jason Tesser) Date: Fri, 21 Nov 2003 14:00:44 -0600 Subject: [GENERAL] linking postgre to AD Message-ID: <04875CB4331F0240A0AD66F970978651011376BA@paul> sorry wrong list though if anyone has an answer feel free to give it :-) -----Original Message----- From: python-list-bounces+jtesser=nbbc.edu at python.org [mailto:python-list-bounces+jtesser=nbbc.edu at python.org]On Behalf Of Jason Tesser Sent: Friday, November 21, 2003 1:59 PM To: Python List (E-mail) Subject: RE: [GENERAL] linking postgre to AD ok so what would prevent users from using SQL tools to connect to the database and browse data? > As far as AD is concerned, I think Bruno Wolff described what to do best: > 1) Configure PostgreSQL to authenticate via PAM (pam_ldap) > 2) Create a table of appgroups & groupmembers that defines the application groups and their members, respectively > 3) Create views over the actual data that test for the appropriate group membership. > You can write your own function to simply the task: > CREATE FUNCTION isMember(text, text) RETURNS bool AS ' SELECT true FROM appgroups, groupmembers WHERE appgroups.name = $1 AND appgroups.appgroup = groupmembers.appgroup AND groupmembers.userid = $2; ' LANGUAGE 'sql'; > 4) Now, if you only want people in the 'Administration' group to view salaries: CREATE VIEW v_salaries AS SELECT * FROM salaries WHERE isMember('Administration', CURRENT_USER); > Or you could do the join against the base table for row-level security: CREATE VIEW v_salaries AS SELECT * FROM salaries, groupmembers WHERE salaries.appgroup = groupmembers.appgroup AND groupmembers.userid = CURRENT_USER; > 5) REVOKE SELECT on salaries from the public and GRANT select on v_salaries to the public. HTH, There is a security problem here if users are able to create their own functions: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=3D02B372.B6A4EFB6%40mascari.com HTH, Mike Mascari mascarm at mascari.com -- http://mail.python.org/mailman/listinfo/python-list From Mike at DeleteThis.Geary.com Wed Nov 19 04:30:20 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 19 Nov 2003 01:30:20 -0800 Subject: New Guy References: Message-ID: > Michael Geary: > > Is that the *exact* program? Nothing is indented Duncan Booth: > I suggest you need to use a different newsreader > program. The indentation is present in the code > from the OP, so it must have been stripped out > by Outlook Express. Thanks for the suggestion. I've been looking at other newsreaders (40tude Dialog, Xnews) but haven't found one I've liked as much as OE. I used to use Agent but switched to OE because Agent didn't handle multiple servers except in a very clumsy way. Problems like this may get me looking at other newsreaders again, though. -Mike From flyfeather at myrealbox.com Mon Nov 3 18:09:26 2003 From: flyfeather at myrealbox.com (Haoyu Zhang) Date: 3 Nov 2003 15:09:26 -0800 Subject: Function Name Resolution Problem Message-ID: Dear Freinds, I am learning Python throught the book "Learning Python" published by O'Reilly. In its 4.6.2, the author gave an example about incorrect use of a recursive function. Let me copy the content of the book as follows. --------------------------------------------------------------------- >>> def outer(x): ... def inner(i): # assign in outer's local ... print i, # i is in inner's local ... if i: inner(i-1) # not in my local or global! ... inner(x) ... >>> outer(3) 3 Traceback (innermost last): File "", line 1, in ? File "", line 5, in outer File "", line 4, in inner NameError: inner This won't work. A nested def really only assigns a new function object to a name in the enclosing function's scope (namespace). Within the nested function, the LGB three-scope rule still applies for all names. The nested function has access only to its own local scope, the global scope in the enclosing module, and the built-in names scope. It does not have access to names in the enclosing function's scope; no matter how deeply functions nest, each sees only three scopes. For instance, in the example above, the nested def creates the name inner in the outer function's local scope (like any other assignment in outer would). But inside the inner function, the name inner isn't visible; it doesn't live in inner's local scope, doesn't live in the enclosing module's scope, and certainly isn't a built-in. Because inner has no access to names in outer's scope, the call to inner from inner fails and raises an exception. --------------------------------------------------------------------- However, when I tested it in my python, it works correctly. So is it because the standard changes? Or any other reasons? The version in our university's server is 2.2.1. Thanks a lot for your help. Best, Haoyu From tim.one at comcast.net Sun Nov 23 15:03:22 2003 From: tim.one at comcast.net (Tim Peters) Date: Sun, 23 Nov 2003 15:03:22 -0500 Subject: Problems sending list/tuple to a C extension. In-Reply-To: Message-ID: [Christian Seberino] > ... > 1. It seems very strange that checking/not checking return > value of PyArg_ParseTuple would make the difference > between working code and code that bombs. Not ALL code > is like this!!! That's not right: virtually every Python C API call *can* return an error value (for example, it, or something it calls, may run out of memory, one time in billions). If you don't check every call for an error return, every place you don't check it will eventually cause a mysterious bug. > I ignore lots of return codes and things work fine lots of times! Dynamically, most calls don't return an error value. If you ignore checking the return value when it so happens it was a normal return value, then of course nothing bad happens. All such code is buggy, though, because it will fail (and in miserable ways) when an error value *does* get returned. > Any idea why this API is so picky this way unlike others? There's nothing unique about PyArg_ParseTuple here, so the question is based on a confusion. The only reason it *appears* unique to you is that it happens to be the first time you got in trouble from neglecting to check for errors. The good news is that you'll get over this illusion as you eventually spend most of your life tracking down "mysterious, unreproducible problems" . From jroznfgre at jngpugbjreQBGbet.cy Fri Nov 28 17:50:06 2003 From: jroznfgre at jngpugbjreQBGbet.cy (JZ) Date: Fri, 28 Nov 2003 23:50:06 +0100 Subject: libmysqld.dll - any working example? References: Message-ID: On Wed, 26 Nov 2003 17:31:35 GMT, Joe Francia wrote: >> Does anybody know any working example of using embedded MySQL library >> for Win32 (libmysqld.dll)?That example from MySQL manual does not >> work for me. I am looking for Python API to libmysqld.dll... > >You may want to consider this, which doesn't require you to ship any >external DLLs: >http://sourceforge.net/projects/mysql-python No, you did not understand me. I know this library and I have been using it for a long time. But the problem is I want to move my web (pythonic) application to CD and I wanted it to work with MySQL as a DLL library. I do not want to install full mysql serwer. I know how to use MySQLdb connection for a server, but I do not know how to connect to that dll. If MySQLdb can do this I do not know how use it. (MySQLdb.Connect() method has parameters of host, login but libmysql.dll do not need such parameters.) -- JZ From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Fri Nov 28 06:36:17 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Fri, 28 Nov 2003 14:36:17 +0300 Subject: invert dictionary with list &c In-Reply-To: References: Message-ID: Des Small wrote: > Des Small writes: > > >>anton muhin writes: > > [...] > > >>This, however, has given me ideas. It was never concision I wanted >>but rather redundancy elimination, and the pattern I wanted _can_ be >>written: >> >>def dict_cons(iter, func, default): >> def process_element(d, (k, v)): >> val = d.get(k, default) >> d.update(dict([[k, func(v, val)]])) >> return d >> return reduce(process_element, iter, {}) > > > Or rather: > > def dict_cons(iter, func, default): > def process_element(d, (k, v)): > d[k] = func(v, d.get(k, default)) > return d > return reduce(process_element, iter, {}) > > def count(l): > def pair_pad(l): return [(e, ()) for e in l] > return dict_cons(pair_pad(l), lambda k,d: d+1, 0) > > def invert(d): > def invertitems(l): > for k,v in l: yield v,k > def addtolist(k, l): return l+[k] > return dict_cons(invertitems(d.iteritems()), > addtolist, []) > > >>Which is not to say that it should be, of course. >>Whereupon, we can say: >> >>def count(l): >> def pair_pad(l): return [(e, ()) for e in l] >> return dict_cons(pair_pad(l), lambda k,d: d+1, 0) >> >>def invert(d): >> def invertitems(l): for k,v in l: yield v,k >> def addtolist(k, l): return l+[k] >> return dict_cons(invertitems(d.iteritems()), >> addtolist, []) >> >>Perhaps I'm terminally unpythonic, but I quite like these. > > > [...] > Or like this: def dict_update(iter, func, default, d): def process_element(d, e): d[e[0]] = func(d.get(e[0], default), *e[1:]) return d return reduce(process_element, iter, d) def count(l): return dict_update(l, lambda x: x + 1, 0, {}) def invert(d): return dict_update( [(v, k) for k, v in d.iteritems()], # In the future (I hope): ((v, k) for k, v in d.iteritems()), lambda l, e: l + [e], [], {} ) print count(list('aabbbbcc')) print invert({'A': 'a', 'B': 'b', 'C': 'a'}) regards, anton. From asdf at asdf123asdf.net Tue Nov 18 00:45:07 2003 From: asdf at asdf123asdf.net (Jimmy Johns) Date: Tue, 18 Nov 2003 00:45:07 -0500 Subject: pyOpenGL for python 2.3 References: <20031116022547.12054.00000233@mb-m26.aol.com> Message-ID: my problem is that I use vs .net. any solutions for this setup? Thanks. "KefX" wrote in message news:20031116022547.12054.00000233 at mb-m26.aol.com... > I built PyOpenGL with a binary of Python 2.3 just fine, once I grabbed all the > needed dependencies. What was your problem? > > - Kef > > >Hi, why hasn't there a version of pyOpenGL for python 2.3.x yet? Currently > >the binary installers for windows only work with python 2.2, and will give > >an when installing for python 2.3. I can't build it either unless I build > >python 2.3 from source as well. Is there a work around available?? Thanks > >in advance. > From costanza at web.de Mon Nov 3 11:06:09 2003 From: costanza at web.de (Pascal Costanza) Date: Mon, 03 Nov 2003 17:06:09 +0100 Subject: Explanation of macros; Haskell macros In-Reply-To: References: <87brs2tjut.fsf@memetrics.com> Message-ID: Joachim Durchholz wrote: > Is there anything that a macro does that can't be done by preevaluating > data structures that contain functions (or closures)? At first glance, > I'd say no, but then I don't know what macros are used for in practice. Macros are mainly used for abstracting away details of sophisticated protocols. For me, the "Hello, World" of macro programming is this: When you want to bind to a resource, you usually have to make sure that you also unbind again later on. The standard pattern in many languages, modulo syntactic variations, is this: try: bind resource do something finally: unbind resource The fact that you need to place the unbind in a finally statement reflects the requirement a protocol imposes on the use of rources: You have to make sure to execute the necessay steps in a certain order, and you have to make sure that certain steps are always executed, no matter what. There are lots of examples like this in programming, and especially more complicated ones. A macro allows you to abstract away from this. The same code, in a language with macro support, would look like this: with-bound-resorce: do something The macro "with-bound-resource" takes care of executing the right steps at the right time. Now, this is admittedly not an example for a particularly sophisticated protocol. Therefore, one of the usual gut reactions from people who are not used to macros yet is "but I can do this with higher order functions!" However, what this example already shows is: The with-bound-resource macro doesn't tell you anything about how it achieves its goals. Yes, the natural way to implement this example is with a HOF, but you could also use a completely different approach. _With macros you can build abstractions that completely hide their implementation details._ This becomes especially useful as soon as your protocols become more sophisticated, and you need to insert instructions at arbitrary places in the code being passed to a macro, or need to control evaluation of the code being passed in some other details. Because of this high level of expressive power that macros provide, Common Lispers use them regularly even for simple things. You can effectively write domain-specific abstractions that don't leak, and therefore it is justified to use them even for simple protocols. > Um, well, yes, there is one thing that macros can do: extending syntax > in ways that aren't part of the original language syntax. E.g. replacing > all those parentheses by indentation, or something similar un-Lispish. > (Extending syntax in such ways is a mistake IMHO, but YMMV. Anyway, I'm > more interested in the question if there's any /semantics/ that can be > done via macros but not via compile-time evaluation.) Compile-time evaluation is a red herring. Macros do their job by rewriting abstract syntax trees. (Lisp and macros go very well together because in Lisp, you essentially program using a notation that maps directly to an internal syntax tree, nearly without any parsing overhead.) Since the syntax tree is usually available at compile time, that's the natural time to let macros do their job. However, in theory it wouldn't be a problem to use macro expansion at runtime. (In Common Lisp, this is already possible in limited ways: an interpreted implementation of Common Lisp expands macros during evaluation, and when you call EVAL or COMPILE, macros are also expanded at runtime. However, you cannot pass macros around as first-class objects and APPLY them, at least not in the same way as functions. If you wanted to do that the language implementation would need to keep the lexical environment information available at runtime.) > Does anybody have a keyword-style list of useful applications of the > macro facilities? Do you have a keyword-style list of useful applications of functions? Pascal From hungjunglu at yahoo.com Thu Nov 20 07:52:10 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 20 Nov 2003 04:52:10 -0800 Subject: Multiple inheritance in Java/C# References: <8ef9bea6.0311182031.38034c10@posting.google.com> <4WLub.10649$ZF1.1133338@news20.bellglobal.com> Message-ID: <8ef9bea6.0311200452.46df1c29@posting.google.com> "Sean Ross" wrote in message news:<4WLub.10649$ZF1.1133338 at news20.bellglobal.com>... > Hi. > I believe this is usually done using a design pattern - I think its called > "the proxy object pattern" or it may be "the delegator pattern", I'm not > sure. I know that for doing CORBA programming with Java, you can have tie > classes (which I believe use the aforementioned design pattern) generated to > help simulate multiple inheritance. The idea is something like this: you > have class C which inherits from A but you would like to have a class that > inherits from A and B; make a class D that inherits from B, and that keeps > an instance of C; D is your class that "inherits" from A and B; when you > have an instance of d and you call a method derived from A, you delegate to > the instance of C, otherwise you handle it directly. I think that's the > general idea. You should be able to find specific examples somewhere online. Thanks. I am finding it to be the standard approach. In short: (containment+delegation) ---> aggregation. Kind of laborious. But that's the way of life without true MI. Hung Jung From mhammond at skippinet.com.au Sun Nov 30 18:45:36 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 01 Dec 2003 10:45:36 +1100 Subject: win32print how to lower cpu load? In-Reply-To: References: Message-ID: Emile van Sebille wrote: > Guy Robinson: > >>I've got this working print queue monitor and currently it checks > > the > >>queues every 1 second. I'm worried that I might miss events if I set >>the delay to more than this. Particularly as I would like to perform >>functions depending on status codes. > > > You could pause all the printers, live with the one second delay, and > selectively release jobs for printing and deletion. Or maybe arrange for all jobs to be placed in the queue in a "paused" state, and have your monitor release the jobs? Either way, for the OP, the general solution to this kind of question is to find the best solution in *any* language. Most often, you will find sample code in either VB or C++ - often from MS - but it can generally be ported to Python fairly easily once you understand exactly what you are trying to do. Mark. From http Mon Nov 10 12:03:01 2003 From: http (Paul Rubin) Date: 10 Nov 2003 09:03:01 -0800 Subject: Am I the only one who would love these extentions? - Python 3.0 proposals (long) References: <7xznf4jhi3.fsf@ruckus.brouhaha.com> Message-ID: <7xd6c0f96i.fsf@ruckus.brouhaha.com> Alex Martelli writes: > That's one of the benefits that the pypy project is intended to > provide: a "reference implementation" that's easiest to play with > for exactly such purposes as the experiments you mention. And -- > we do hope to release pypy 1.0 before Christmas...! Interesting and cool. During the early discussion of Pypy it sounded as if Pypy was specifically *not* intended for such purposes. It'll be great to see what comes out. From jdhunter at ace.bsd.uchicago.edu Thu Nov 27 09:11:43 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 27 Nov 2003 08:11:43 -0600 Subject: pymat and Matlab6.5 In-Reply-To: (juntu@operamail.com's message of "27 Nov 2003 00:45:18 -0800") References: Message-ID: >>>>> "Juntu" == Juntu writes: Juntu> The same prolem again. I found no binaries of Scipy for Juntu> Python2.3 under Windows Xp. To compile the source code you Juntu> need many package which really I do not want to install Juntu> them in my computer, and also I do not have enough Juntu> experience to do complilation process. Is there someone who Juntu> already compiled Scipy to work for Pyhton2.3 for Win32 Juntu> patform???. If you want to use scipy on win32, I recommend the enthought edition of python, which comes with scipy, wxpython, vtk and other goodies built in http://enthought.com/python/ They do have a version for python2.3. I was surprised not to see a win32 python2.3 binary for scipy on the scipy site. John Hunter From skip at pobox.com Thu Nov 20 12:43:36 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 20 Nov 2003 11:43:36 -0600 Subject: Threading a lengthy C function In-Reply-To: References: <3fbd00fa@nntp0.pdx.net> Message-ID: <16316.64840.848331.205769@montanaro.dyndns.org> Thomas> I always wondered why (apparently) SWIG does not release the Thomas> lock before calling into C code and acquire it back afterwards. Because it can't tell if the C code it's going to call will or won't make a call back to Python. In most cases that would work, but in a few cases it could lead to nasty bugs. Skip From jjl at pobox.com Tue Nov 11 16:28:41 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Nov 2003 21:28:41 +0000 Subject: response time References: <1jSrb.2419$9_.105379@news1.tin.it> <87d6bzetsz.fsf@pobox.com> <3FB01787.529425BC@engcorp.com> <87u15bf6qs.fsf@pobox.com> <3FB0FAE0.73ECA8A1@engcorp.com> Message-ID: <878ymmbnna.fsf@pobox.com> Peter Hansen writes: > "John J. Lee" wrote: [...] > > That doesn't explain it AFAICS -- why not use a different (smaller) > > divisor? An eight bit counter would give about 0.2 ms resolution. > > Can you imagine the overhead of the DOS timer interrupt executing over 500 > times a second?! No. > It would have crippled the system. In fact, from what > I recall of the overhead associated with that interrupt, that might well > have consumed every last microsecond of CPU time. I see. :-) [...] > burden on performance. I believe one of the first links to the Google > search I mentioned has the part number of the timer chip in question, so > you could investigate further if you're curious. [...] No thanks!-) John From FBatista at uniFON.com.ar Tue Nov 4 15:41:45 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 4 Nov 2003 17:41:45 -0300 Subject: prePEP: Decimal data type Message-ID: Tim Peters wrote: #- [Facundo Batista] #- > Are you sure? Because, for example with a precision of 9: #- > #- > 123 --> 123e0 #- > 1122334455667788 --> 112233445e7 #- > #- > Meaning that you lost the last digits. We're talking about billions #- > here, but an accounting person won't be happy with that. #- #- Then they shouldn't use such a tiny precision; that's #- essentially IEEE #- single precision. Default to a precision of, say, 100, and #- you can count #- the number of electrons in the universe exactly. Since each #- penny contains #- at least one electron ... . Nice picture, :). But in Money you *want* to get rounded in the decimal places. Example of decimal with precision = 100: 1122334455667788 --> 1122334455667788 1122334455.667788 --> 1122334455.667788 But in Money, you may want to get rounded to two decimals: 1122334455.667788 --> 1122334455.67 #- > ... #- > And I'm not quite sure that I understand what you mean #- with "unbounded #- > precision" (that you can not say with fixed or floating #- point). Could #- > you please explain that? thanks! #- #- Unbounded precision ("to the left" of the radix point) is what my old #- FixedPoint.py class did/does: if you multiply two #- FixedPoint integers, the So, unbounded precision and fixed point are the same? (I always assumed that) . Facundo From klappnase at web.de Tue Nov 25 07:58:40 2003 From: klappnase at web.de (klappnase) Date: 25 Nov 2003 04:58:40 -0800 Subject: Tkinter widget that functions like Explorer "Details" mode? References: Message-ID: Douglas Alan wrote in message news:... > Logan writes: > > > I think, you have to write such a widget yourself (which is in fact > > not so difficult - except for the 'adjustment of the column width'). > > Well, yes, that's the part that's been worrying me. > > |>oug Maybe you could try a Pmw.PanedWidget in combination with a Pmw MCListBox (a multi column listbox widget that comes as a contribution with Pmw) Cheers Michael From peter at engcorp.com Sun Nov 23 17:07:06 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Nov 2003 17:07:06 -0500 Subject: Catching JavaScript in InternetExplorer with Python / win32com References: Message-ID: <3FC12F8A.158067F7@engcorp.com> Florian Fredegar Haftmann wrote: > > I'm working on a tool which helps in testing applications with web-frontends (on > Windows) > On thing I would like to test ist the occurence of JavaScript errors; the idea > is that the test tool does many request and actions on the Internet Explorer and > collects all errors (including JavaScript errors) together into a report. I've > setted up a framework for controlling an Internet Explorer instance using Python > and win32com, but so far I have not found anything to actually catch JavaScript > errors. Has anyone experience with that? You might want to check out pyjtf at Sourceforge: http://pyjtf.sourceforge.net. It's a small package I released which does something like what you are asking about. You could use it for inspiration, butcher it for example code, or maybe even find a way to contribute to it. :-) -Peter From aleax at aleax.it Mon Nov 17 10:17:07 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 17 Nov 2003 15:17:07 GMT Subject: program surgery vs. type safety References: <9a6d7d9d.0311120822.553cd347@posting.google.com> <698f09f8.0311140417.567393b9@posting.google.com> Message-ID: dman at dman13.dyndns.org wrote: > On 14 Nov 2003 04:17:08 -0800, Jeremy Fincher wrote: >> Alex Martelli wrote in message >> news:... >>> Sure, >>> "tests can only show the _presence_ of errors, not their >>> _absence_". But so can static, compiler-enforced typing -- it >>> can show the presence of some errors, but never the absence of >>> others ("oops I meant a+b, not a-b"! and the like...). >> >> But it *does* show the absence of type errors, > > Not all the time. Casting (a la C, C++, Java) allows the programmer > to say "silly compiler, you don't know what you're saying" (usually, > it also converts int<->float and such, but apart from that). That > results in a runtime type error the compiler didn't detect. A Java > runtime will detect that later, but C and C++ will just behave wrong. Jeremy was arguing for a _GOOD_ static typing system, as in ML or Haskell, not the travesty thereof found in those other languages. I do not think I've seen anybody defending the "staticoid almost-typing" approach in this thread. Alex From daniels at dsl-only.net Fri Nov 21 12:22:59 2003 From: daniels at dsl-only.net (sdd) Date: Fri, 21 Nov 2003 09:22:59 -0800 Subject: Using an interable in place of *args? In-Reply-To: References: Message-ID: <3fbe578f$1@nntp0.pdx.net> Nick Vargish wrote: ... Is there a general method for calling a function that expects *args > with an iterable instead (tuple or, even better, a list)? I can see > how I could do something funky with exec, but I'd like to avoid that > if possible. I'm unsure of what you mean; if you explain why this doesn't solve your problem, we'll go from there?: I suspect you want something that can be used in the following way: obj = dstruct(...) ... obj.pack(5,4,3,2) To put a little meat in, I'll have pack simply print its args: class dstruct(object): ... def pack(self, *args): for element in args: print element This works, now what is unlike what you want? -Scott David Daniels Scott.Daniels at Acm.Org From aahz at pythoncraft.com Sun Nov 2 01:55:48 2003 From: aahz at pythoncraft.com (Aahz) Date: 2 Nov 2003 01:55:48 -0500 Subject: Food at Pycon References: Message-ID: [p&e] In article , Laura Creighton wrote: > >I thought that the food provided at PyCon last year was awful. Now I >find out it cost us approximately half the budget of PyCon, at 74$ a >head. I think that this is shameful. But Aahz thinks the convenience >factor, for those people who are willing to eat the food -- outweighs >the cost factor. It looks as if if is coming in at 70$ a head this >time. I'd rather have the 70$. But Aahz doesn't want to open this >discussion unless I can find 10 people who aren't interested in the >lunches. I'm saddened that you chose not to write a balanced post about the subject, so here is some additional information for people: The money Laura refers to covers three days of food. It's not just lunch, it's also breakfast pastry/coffee plus two coffee breaks (with cookies and sodas). The money includes tax and service charges. Yes, it's overpriced, but it's a pretty standard markup for conference food. The downside of not providing the food is that it's much less convenient to meet people during lunch if you have to forage. That applies less to people who already know lots of people in the Python community, of course. Another thing that Laura didn't mention is that we ran into a schedule crunch last year. With additional time, we can certainly make more of an effort this year to provide food that people will eat. We're also planning to order less food to accomodate those who won't eat conference food, which will result in less cost for everyone. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From hst at empolis.co.uk Tue Nov 11 12:57:55 2003 From: hst at empolis.co.uk (Harvey Thomas) Date: Tue, 11 Nov 2003 17:57:55 -0000 Subject: Writing UTF-8 string to UNICODE file Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB53BF0D@hendrix.empolisuk.com> Michael Weir wrote > > I'm sure this is a very simple thing to do, once you know how > to do it, but > I am having no fun at all trying to write utf-8 strings to a > unicode file. > Does anyone have a couple of lines of code that > - opens a file appropriately for output > - writes to this file > Thanks very much. > Michael Weir Are your strings Unicode strings? If they are, then write them as UTF-8 encoded strings by import codecs f = codecs.open('myfile', 'w', 'utf8') f.write(u'Unicode string') HTH Harvey _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From fredrik at pythonware.com Fri Nov 21 06:45:25 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 21 Nov 2003 12:45:25 +0100 Subject: for what are for/while else clauses References: <2259b0e2.0311142321.aba58d3@posting.google.com> Message-ID: Mel Wilson wrote: > >for a while-statement, the controlling condition is the test at > >the top. > > > >for a for loop, the condition is "is there another item" (to quote the > >language reference: "When the items are exhausted (which is imme- > >diately when the sequence is empty) ... the loop terminates.". > > > >for a try-except clause, the condition is "did the suite raise an > >exception". > > Interesting way to think about it. Thanks. > > So in some sample code: > > while some_condition: > some_action () > else: > last_action () > following_code () > > If the loop results in some_action being done, say, 17 > times; then that means that some_condition was found true 17 > times. The 18th time, some_condition is found to be false, > the else takes effect and last_action gets done one time. imagine a dialect of Python that supports C-style goto's and labels. in this dialect, while some_condition: some_action () else: last_action () can be rewritten as this_statement: if some_condition: some_action () goto this_statement else: last_action () next_statement: (which, of course, is exactly what Python's current compiler does, but on the bytecode level). "break" and "continue" can now be rewritten as "goto next_statement" and "goto this_statement". for "for-in" and "try-except", the code calculating the "some_condition" value is a bit different, but the rest works in exactly the same way. here's the for-in version: this_statement: if : variable = some_action () goto this_statement else: last_action () next_statement: and here's the try-except version (somewhat simplified): this_statement: some_action () error_handler: if : some_action () else: other_action () > The only wrinkle then is that the while loop construct > passes control to the following code after that one > last_action. But we expect that from a while loop. most Python statements pass control to the next statement when they're done. > The effect of a break in the suite controlled by the > while is to blow away execution of the whole while > construct, including the else. > > As an explanation, I like it. me too. From trentm at activestate.com Sat Nov 1 17:32:20 2003 From: trentm at activestate.com (Trent Mick) Date: Sat, 1 Nov 2003 14:32:20 -0800 Subject: ANN: ActivePython 2.3.2 & ActivePython 2.2.3 In-Reply-To: ; from theller@python.net on Sat, Nov 01, 2003 at 12:50:32PM +0100 References: Message-ID: <20031101143220.A4976@ActiveState.com> [Thomas Heller wrote] > Which is a pity, since the upcoming py2exe (for python 2.3) requires > win32all build 161 or later, if win32all is used. What is the "word on the street" for win32all builds 160 and 161? Currently the PyWin32 site says: http://starship.python.net/~skippy/win32/Downloads.html These versions are fairly new, and as such should be considered experimental. After a few success reports, these will be be considered the latest stable releases. ...so I was just being cautious. If people consider those builds stable enough I wouldn't have a problem upgrading ActivePython's win32all. Is there a whole lot that is new in builds 160/161? Trent -- Trent Mick TrentM at ActiveState.com From avharut at netscape.net Fri Nov 21 13:51:34 2003 From: avharut at netscape.net (avik) Date: 21 Nov 2003 10:51:34 -0800 Subject: a scipy installation problem? References: Message-ID: Robin Munn wrote in message > What happens if you do "import scipy" instead of "from scipy import *"? > > "from ... import *" is _almost_ always a bad idea anyway, since it > clutters up your namespace. It also causes issues with the reload() > function. Avoid that usage unless you *really* know what you're doing. Actually, up to now (during a short time, anyway) I have always used "import " without having any special reason to avoid "from import *" :-). In the case of scipy I just tried out the first thing that's written in its short tutorial and the same is with that: >>> import scipy Segmentation fault (core dumped) Regards avik From cbrown at metservice.com Mon Nov 24 18:41:52 2003 From: cbrown at metservice.com (Colin Brown) Date: Tue, 25 Nov 2003 12:41:52 +1300 Subject: Strange import bug References: <3fc2854a$1@news.iconz.co.nz> Message-ID: <3fc2960a@news.iconz.co.nz> "Adeodato Sim?" wrote in message news:mailman.1043.1069714565.702.python-list at python.org... ... The first (default) entry in sys.path is '', which means (I think) the current directory. So sys.path.append('./abc') appends after this entry; then, on "import abc", python uses first '' entry, which means it looks under current directory where it finds "abc" which gets imported *as a module*. ... Okay, but why does python not complain when it tries to import the current directory as a module? I would expect an error, maybe: "ImportError: xxx is not a valid python module" If it is considered a valid python module and is executing it then who knows what it is doing. There is still also the question of why the prepended path option fails in some cases under Win2K for me. Thanks Colin Brown PyNZ From malihi1 at 012.net.il Tue Nov 18 15:55:09 2003 From: malihi1 at 012.net.il (Sagiv Malihi) Date: Tue, 18 Nov 2003 22:55:09 +0200 Subject: using Python to run other programs References: <7T02VNBM37943.8988541667@Gilgamesh-frog.org> Message-ID: <3fba8735$1@news.012.net.il> hi, using python to run shell commands is very easy. all you need to do is create the command line you would want to run. in your case: command = "pgp -feat " + a and then run it using os.system(), like this: import os os.system(command) if you also want to get the output of the command, you can use the 'commands' module, like this: import commands output, rc = commands.getoutput(command) then you get the output into the variable 'output', and the exit code of the program into the variable 'rc'. sagiv. "Frog" wrote in message news:7T02VNBM37943.8988541667 at Gilgamesh-frog.org... > Hi, i'm not a programmer so I have a very stupid question. I'm trying to > make a practical script. I need to run an executable program in it but i > can't get it to work. Maybe someone here can figure it out easily: > > ----- > #! /python > > a = (recipient's e-mail address) > > pgp -feat a > > (sendmail to address after encryption) > ------ > > How do I get python to open the pgp program? > > Should I use an environment other than python? > > thanks! > > From cliechti at gmx.net Sun Nov 2 15:31:14 2003 From: cliechti at gmx.net (Chris Liechti) Date: 2 Nov 2003 22:31:14 +0200 Subject: py2exe question References: <3FA36D0A.45BCA44B@easystreet.com> <6FKob.391474$R32.12987108@news2.tin.it> <3FA3EE35.F382B493@easystreet.com> <3FA46952.60B2836D@easystreet.com> <3FA540B2.5453C98C@easystreet.com> Message-ID: achrist at easystreet.com wrote in news:3FA540B2.5453C98C at easystreet.com: > Chris Liechti wrote: >> >> achrist at easystreet.com wrote in news:3FA46952.60B2836D at easystreet.com: >> >> > Looks like 0.5.0a is not picking up any of my command line arguments >> > or producing any executable when I run it through the same batch >> > file that worked for 0.4.2. >> > >> > Any docs on how to make if work? >> >> there is an example in the lib/site-packages/py2exe/samples dir >> the syntax of the setup call is different >> > > I try to run the sample to see what comes out, and I get: > > tlb = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid) > pywintypes.com_error: (-2147319779, 'Library not registered.', None, > None) just comment out the line with the "typelib" in it and do not build the COM example. the com example seems torequire that makepy is run in advance, so that the typlib is there. the other examples worked fine for me. chris -- Chris From Ian.Sparks at etrials.com Wed Nov 19 22:29:49 2003 From: Ian.Sparks at etrials.com (Ian Sparks) Date: Wed, 19 Nov 2003 22:29:49 -0500 Subject: Help with some code Message-ID: <41A1CBC76FDECC42B67946519C6677A9A20CE2@pippin.int.etrials.com> Hi, I want to create specialized instances of a base class without having to : 1. declare a descendant class 2. create an instance of that descendant class. Instead, I want to : 1. Create an instance of the base class, specializing it by passing source-code to its constructor. Here's what I have so far : PASS = 1 FAIL = 0 class test: def __init__(self,name,code): self.name = name self.source = code co = compile(code,"",'exec') exec(co,globals(),self.__dict__) def execute(self): print self.__dict__['func'](self) if __name__ == '__main__': code = """ def func(self): print code #fun print self.name #test self return PASS #test globals """ x = test('my test',code) x.execute() It works and it's great that I can do this with python at all but I wonder if there's a cleaner way to do this. I'd rather have something more like : class test: def __init__(self,name,code): .... def execute(self): """This should be overridden by passed-in code""" raise NotImplementedError then... code = """ #Note no function declaration, that signature won't change so the code could auto-add it (deal with indent?) print code print self.name return PASS """ x = test('my test',code) x.execute() Any advice? From peter at engcorp.com Tue Nov 18 13:00:56 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Nov 2003 13:00:56 -0500 Subject: good ways to convert string into time References: <731fc603.0311180958.32135957@posting.google.com> Message-ID: <3FBA5E58.8B67D120@engcorp.com> Hank wrote: > > i have a string as follows > > 18Nov2003:18:23:43:405 It's a minor point, but what happens for days-of-the-month that are less than 10? Leading zero, or one character shorter? Same question goes for the other fields, I suppose... > Is there an easy way to convert that to absolute time? What i really > want to do is to parse these times from a log file and do time > comparisons, averages, stop minus start (elapsed). > > Probably create my own conversion table i guess? Probably not, actually... -Peter From P at draigBrady.com Tue Nov 4 06:35:33 2003 From: P at draigBrady.com (P at draigBrady.com) Date: Tue, 04 Nov 2003 11:35:33 +0000 Subject: bash Vs python ?? In-Reply-To: References: Message-ID: <3bMpb.4070$bD.16282@news.indigo.ie> Omar Khalid wrote: > > hello experts, > i have been assigned a project in which i have to do a lot of > command line processing by writing "automated testing scripts " > for a software on unix platform . > > what would be a better option in this scenario bash (unix shell > scripting ) or python ? > plz give me advantages & disadvantages of both . any web links ? probably a mixture of both is appropriate. bash is tuned for calling system commands directly and piping the output from these together in various ways. But it can be woefully inefficient and awkward for certain things, like string manipulation or looping for e.g. You may be better doing something like: bash_script | python_processing P?draig. From mwh at python.net Tue Nov 4 07:32:22 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 4 Nov 2003 12:32:22 GMT Subject: Please explain the meaning of 'stealing' a ref References: Message-ID: <7h3wuagiagy.fsf@pc150.maths.bris.ac.uk> Christos "TZOTZIOY" Georgiou writes: > I invested some time today because I got this crazy idea that if I > implemented a simple attribute-getting caching scheme implemented in > PyObject_GetAttr / PyObject_SetAttr that would turn out to be good. Are you aware of the cache-attr-branch (think it's called that) in CVS? > So I did implement one touching Objects/object.c (and pythonrun.c for > init/final purposes), and I got a 5% increase in pystone... of course, > when I exited the interpreter, I got a nice segfault :-) Also, > test.testall segfaulted at test_anydbm. I didn't expect anything > better, to be honest; it's obviously got something to do with inc/dec > refs. > > Now I'm googling for the various debug building options (I'm not sure > that -DDEBUG is enough etc), however I realised it's time to ask what I > never understood so far: what exactly is the meaning of a function > "stealing a reference"? Is it that the function does an incref or a > decref? Or is it something more obscure? This *really* should be explain in the API reference or the extended and embedding manual somewhere... have you looked there? Cheers, mwh -- There are two ways of constructing a software design: one way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies. -- C. A. R. Hoare From andy at wild-flower.co.uk Tue Nov 11 13:14:24 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Tue, 11 Nov 2003 18:14:24 +0000 Subject: lost connection In-Reply-To: <001101c3a4b4$385be180$1603a8c0@pc22> References: <000c01c3a4b2$3ecf1ac0$1603a8c0@pc22> <001101c3a4b4$385be180$1603a8c0@pc22> Message-ID: <200311111814.24509.andy@wild-flower.co.uk> On Thursday 06 Nov 2003 10:20 pm, Alberto Vera wrote: > I forgot to write this: > ...I unplug and 10 seconds later I plug the wire.. > > Regards > ----- Original Message ----- > From: Alberto Vera > To: python-list at python.org > Sent: Thursday, November 06, 2003 5:06 PM > Subject: lost connection > > > Hello: > I use these lines to connect to a database: > > conn = win32com.client.Dispatch('ADODB.Connection') > conn.Open('Provider...) > > But I have a problem: If I unplug the wire(network) then I can't make > anything to a database. > > I thought the conn.State has changed but allways has the same value of 1. > > Do you think is it a bug on Python? > > Thanks > > > > > --------------------------------------------------------------------------- >--- > > > -- > http://mail.python.org/mailman/listinfo/python-list alberto, if your telephone cord got cut during a phone conversation (maybe by a villain, like in the movies) would you expect to be able to carry on the converstaion again, without re-dialling, once the wire was repaired? That's more-or-less what you're asking your program to do. To get this type of effect, it's best to do a connect-work-disconnect cycle - you shouldn't really keep database connections alive for protracted periods of time. If you do it this way, you don't really have to worry too much about losing your connection: just trap the condition and re-try... hth -andyj From adourado at eln.gov.br Thu Nov 6 10:10:43 2003 From: adourado at eln.gov.br (Andre Dourado) Date: 6 Nov 2003 07:10:43 -0800 Subject: Need to pass dtml-in parameter Message-ID: I?m a newbie in Zope and I have a little problem. I'm trying to use a dtml-in tag to call a ZSQL, but the name of my ZSQL is stored in a sql table. I've tried things like: > where my_query is the column name of my sql table where the ZSQL name is stored. Thanks for any help. From gh at ghaering.de Wed Nov 12 08:10:14 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 12 Nov 2003 14:10:14 +0100 Subject: guten tag In-Reply-To: References: Message-ID: <3FB23136.1010702@ghaering.de> Necati Agirbas wrote: > Betreff: SCHULBESCHEINGUNG F?r Frau DERYA AGIRBAS, [...] Sie haben das wohl an die falsche Adresse geschickt (python-list at python.org), anstatt an die Adresse der Schule. MfG, -- Gerhard H?ring From timr at probo.com Tue Nov 11 03:20:46 2003 From: timr at probo.com (Tim Roberts) Date: Tue, 11 Nov 2003 00:20:46 -0800 Subject: truly working multipart uploads. References: Message-ID: <0s61rvob463h515mmgt5jugbknqcm27149@4ax.com> Hunter Peress wrote: >I have been unable to write a script that can do (and receieve) a multipart form upload. > >Also, it seems that there really are differences between python's implementation and else's. > >Can someone please prove me wrong with a script that works with itself AND with example 18-2 >from php: http://www.php.net/manual/en/features.file-upload.php Plop this script into a CGI directory somewhere, load it into your browser and do the upload. Use a text file; it echos the file back out to your browser. This uses the exact form from the php.net web page. #! /usr/local/bin/python import os import cgi q = cgi.FieldStorage() if not q.has_key('userfile'): print """\ Content-Type: text/html Testing
Send this file:
""" else: f1 = q['userfile'].filename if q['userfile'].file: contents = q['userfile'].file.read() else: contents = q['userfile'].value print "Content-Type: text/plain" print print "Filename = ", f1 print "Here's the content:" print contents -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jdhunter at ace.bsd.uchicago.edu Wed Nov 12 22:34:41 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 12 Nov 2003 21:34:41 -0600 Subject: Saving a picture contained in a web page to disk In-Reply-To: ("Michael Geary"'s message of "Wed, 12 Nov 2003 15:09:50 -0800") References: <25e5rvg60kf9c4l08kars34jgorqcpado3@4ax.com> Message-ID: >>>>> "Michael" == Michael Geary writes: Michael> Try running this code and see what you think: You mean import urllib urllib.urlretrieve(url, filename) right? , JDH From grey at despair.dmiyu.org Tue Nov 18 12:04:34 2003 From: grey at despair.dmiyu.org (Steve Lamb) Date: Tue, 18 Nov 2003 17:04:34 -0000 Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: On 2003-11-18, Andrew Dalke wrote: > While I, when writing Perl code, also NEVER had a problem. I > ignored just about all of its variations > if ($cond) {$a++} > $a++ if $cond; > $a++ unless !($cond); > unless (!($cond)) {$a++}; Exactly the case I was thinking of when I wrote my message. 4 ways to express an if. After getting over the neatness factor I wrote if in exactly one way. if ($cond) { block }. I found that by doing so my code was not only far more readable to other people in general it was readable by *ME* just a few weeks later. I think the same thing every time we get someone asking for do...until or do...while. We have while. If I want exactly 1 run before the condition is tested I can do that. It seems far clearer to me when I see... x = 1 while x < 2: x = foo() print "done" ...what is going on than having to deal with someone putting: do: x = foo() while x < 2: print "done" ...or having to deal with people who will read my code and tell me "Ya know, you should use a do...while here." "Why? It's just another form of while." "Well, yeah, but it guarentees the loop performs once." "So? Initilizing your variables does that, too." > I did this not because it was the most expressive but because I wanted to > write code that others could follow, and indeed one of the praises I got was > "wow! It's Perl code I can actually understand!" Same here. The latest compliment was that upon seeing an example of Python and PHP code that did the same thing that my code was "concise and clear". It is because I code with consistent structure, not with expressive structure. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From SEE_AT_THE_END at hotmail.com Mon Nov 10 17:17:38 2003 From: SEE_AT_THE_END at hotmail.com (Georgy Pruss) Date: Mon, 10 Nov 2003 22:17:38 GMT Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> <%RNrb.1200$hV.35775@news2.tin.it> Message-ID: <68Urb.78568$v82.4381201@twister.southeast.rr.com> Thank you! G-: "Alex Martelli" wrote in message news:%RNrb.1200$hV.35775 at news2.tin.it... | From peter at engcorp.com Thu Nov 20 09:18:02 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Nov 2003 09:18:02 -0500 Subject: Defining functions References: <20031120002109.28583.00000621@mb-m11.aol.com> Message-ID: <3FBCCD1A.C7216E7@engcorp.com> Jimith87 wrote: > > I'm a newby to python, and have been learning it for a little while, but I > have a problem. I can't grasp the concept of functions..... If someone could > explain that in lamers tearms that would be appreciated. One more question, can > python be applied to manipulate things in Windows? Like maybe restart my > computer through python, or record keystrokes??? Planning to write some viruses? ;-) -Peter From val at vtek.com Mon Nov 24 17:25:10 2003 From: val at vtek.com (val) Date: Mon, 24 Nov 2003 17:25:10 -0500 Subject: Adding new methods at runtime to a class References: Message-ID: "Roy Smith" wrote in message news:roy-A5FC3C.16223824112003 at reader2.panix.com... > In article , > "Delaney, Timothy C (Timothy)" wrote: > > > > From: Fernando Rodriguez > > > > > > How can I add new methods at runtime to a class? > > > > Before we send you into what most would consider black magic in Python, you > > should explain why you want to. > > > > In most cases, this is *not* what you want to do - there are better, more > > elegant and much more Pythonic ways of doing it. > > > > Tim Delaney > > > > Why is it unpythonic to add methods at runtime? That's the nature of a > dynamic language. If foo.bar doesn't have to exist until the moment > it's evaluated, why should foo.bar() have to? Or maybe a better way to > ask it is why should foo.bar have to be callable at any other time than > when you evaluate foo.bar()? > > I would say that the fact that all of a class's methods have to be > declared at once is itself somewhat unpythonic. Tim, Yes and No. In the *real-world* programming, including embedded systems and environment-driven systems, often you have no idea what may happen next, and you don't have a luxury to design and build your program ahead. You still can analyze the current (run-time) situation and build your response on-the-fly, dynamically. That's where the power of dynamic languages comes in, and my simple understanding is that the reality gets more and more dynamic. To me, it does not sound crazy that the compiled languages/programs will be forced to die out gradually. Python is kind of half-compiled (extensions) and half-interpreted with the interpretation 'half' in control. However, the coming reality with lots of indirect, revealed-at-run-time relationships and inputs will require even more dynamic (than Python) languages. And 'dynamic' means the code being built on-the-fly with lots of inputs from environment. Some recent developments such HP's Dynamo, Transmeta's Crusoe (with Linus Torvalds?), Sun's MAJC indicate these kind of trends. And the reason for this trend is performance and dynamics, the performance being the number of *right* (million) instructions per second, not *any* MIPS, coz you want the *right* result, not just a result fast. In fact, the heart of any computer is an interpereter - an instruction decoder that decodes/executes (always at run-time) a program counter controlled instruction which is either available in memory, or gets built dynamically. Remember the very simple von Neumann's dynamic re-addressing; it still rules the computer world. So, i guess the point is the *level* of the instruction and the power of the decoder (computer interpreter). Python might be a *directly interpreted* language like many other languages since the 60s. To me, Roy sounds convincing. Correct me coz i'm used to be wrong... val From newsgroups at jhrothjr.com Thu Nov 6 15:49:51 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 6 Nov 2003 15:49:51 -0500 Subject: prePEP: Decimal data type References: Message-ID: "Aahz" wrote in message news:boebf0$ird$1 at panix1.panix.com... > In article , > John Roth wrote: > > > >AFAICS, there are only two solutions: > > > >.add(, []) > > > >and > > > >.add(, ) > > Both are too inconvenient for casual users. I think that for the Money > subclass, it'll probably make sense to require users to specify an > explicit Context before the first operation (raising an exception if not > initialized). For Decimal, using the same defaults as Rexx will > probably work just fine. The trouble is that most of the difficulty that's being discussed is not for casual users. It's for professional users that have to adhere to legal, regulatory and other requirements that have no inherent underlying order that makes them amenable to a nice, neat and trivially understandable solution. If coming up with something that is understandable to novices is a rock bottom requirement, then I most respectfully suggest that the rest of the discussion is a waste of time. The part of my response which you didn't quote said something about my not being able to find an expression syntax that would handle these essentially arbitrary and capricious regulations. If you would suggest one, I'd be delighted. Of course, I do have a suggestion for an infix notation that would work. I predict that it will be absolutely unacceptable to all parties. [+, ] In the spirit (if not the letter) of PEP 225. Notice that it simply distributes the pieces of the expression differently. John Roth > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > "It is easier to optimize correct code than to correct optimized code." > --Bill Harlan From no at spam.invalid Mon Nov 3 20:04:26 2003 From: no at spam.invalid (Russell E. Owen) Date: Mon, 03 Nov 2003 17:04:26 -0800 Subject: Tkinter event question Message-ID: I've found a quirk in Tkinter and am wondering if anyone knows a workaround. I've got some widgets that generate events. Sometimes the widgets are not displayed, but they may still want to generate these events. The problem is, if a widget has never been displayed, event_generate appears to be ignored. If I display the widget and then hide it again, event_generate works fine. But...I've got many widgets that are normally hidden and don't really want the screen flashing with stuff being displayed and hidden again right away as the application starts up. Here is a minimal and unrealistic script that shows the problem. Push the button to generate a <> event. The event is actually only generated if the label that generates it is shown (you can then hide it again and the events are still generated). Note that the label *is* initially gridded, but it's taken hidden again before the window manager ever actually gets to display it. Suggestions? This is driving me mad, as such events could be quite useful for communication if I could only generate them reliably. -- Russell #!/usr/local/bin/python from Tkinter import * root = Tk() class myLabel(Label): def sendFoo(self): self.event_generate("<>") def gotFoo(evt): print "Got <>" root.bind("<>", gotFoo) c = myLabel(text="I Am A Label") b = Button(root, text="Send <>", command=c.sendFoo) c.grid(row=0, column=0) c.grid_remove() b.grid(row=1, column=0) showVar = IntVar() def showFoo(): if showVar.get(): c.grid() else: c.grid_remove() showC = Checkbutton(root, text="Show Label", variable=showVar, command=showFoo) showC.grid(row=2, column=0) root.mainloop() From bnet at ifrance.com Fri Nov 14 14:07:54 2003 From: bnet at ifrance.com (Benoit Dejean) Date: Fri, 14 Nov 2003 20:07:54 +0100 Subject: C API : setting the message of an exception Message-ID: (sorry for my english) when an excpetion is raised (like Overflow), before i return NULL, i'd like to modify the message held by the exception. I use PyErr_SetString, but i don't know how to retreive the current message excaption is raised -> extending error message -> raising exception thank you From a.schmolck at gmx.net Sat Nov 15 15:43:57 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 15 Nov 2003 20:43:57 +0000 Subject: +/-infinity in Python? References: Message-ID: Andreas Neudecker writes: > Hi. > > Is there anything like +infinity and -infinity available in Python, and can it > be used in comparisons together with int or float numbers? The newest version of numarray and scipy should offer the functionality you want (at least for supported platforms). 'as From http Sun Nov 30 02:00:34 2003 From: http (Paul Rubin) Date: 29 Nov 2003 23:00:34 -0800 Subject: sorting dictionary keys? References: <3fc91af5$0$28610$636a55ce@news.free.fr> Message-ID: <7x65h2fii5.fsf@ruckus.brouhaha.com> "Raymond Hettinger" writes: > Py2.4 will have a classmethod called list.sorted() that accepts any > iterable as an argument and returns a new sorted list as a result. > It can be used anywhere you can use an expression (function call > arguments, lambdas, list comps, etc). Oh cool, although it means allocating more memory for the new list. From g2h5dqi002 at sneakemail.com Wed Nov 12 19:45:50 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Thu, 13 Nov 2003 13:45:50 +1300 Subject: 'while' in list comprehension? In-Reply-To: <840592e1.0310270216.47ff13cf@posting.google.com> References: <20031022175924.GA10716@jsaul.de> <20031024125923.GC27460@jsaul.de> <840592e1.0310270216.47ff13cf@posting.google.com> Message-ID: Hannu Kankaanp?? wrote: > Another variation: > > foo = [i for i in bar, break if len(i) == 0] > > This wouldn't need a new keyword. My thoughts on all this are that if you want to do something that procedural, it would be better written out as nested statements. List comprehensions are meant to be read declaratively. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From oest at soetu.eu Wed Nov 12 17:30:24 2003 From: oest at soetu.eu (Carlo v. Dango) Date: Wed, 12 Nov 2003 23:30:24 +0100 Subject: conceiling function calls.. Message-ID: It is possible to conceil access to methods using the "property()" function so method access looks like field access.. is the same possible for functions (not taking any args... ) I would like something like def f(): return tnaheusnthanstuhn class A(object): def foo(self): f.bar() as it is now I have to write class A(object): def foo(self): f().bar() -carlo -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From aleax at aleax.it Wed Nov 12 05:55:36 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 12 Nov 2003 10:55:36 GMT Subject: Which of the best choice ? References: Message-ID: SungSoo, Han wrote: > There are two coding style when python import module. > (1) import sys > (2) from import sys (or from import *) > > I prefer (1) style. Because it's easy to read, understand module in any > category . > > Which prefer ? Style (1) is generally to be preferred. "from X import *" is almost universally shunned because it fills your namespace in ways that you can't really control. There may be a few good nice ways to use 'from' (one is getting a single module from a package), but in general if you were to forget the existence of the 'from' statement, in favour of using only the 'import' statement, your Python code wouldn't suffer. Alex From lupan at zamek.gda.pl Tue Nov 25 17:36:32 2003 From: lupan at zamek.gda.pl (Lukasz Pankowski) Date: Tue, 25 Nov 2003 23:36:32 +0100 Subject: Python docs in Info format? References: <7x3ccc87ki.fsf@ruckus.brouhaha.com> Message-ID: <87k75ovzwv.fsf@psi.lupan.zamek.gda.pl> Paul Rubin writes: > Has anyone got a script to convert the Python docs (particularly the > library reference) to Info format, so they can be browsed with the > Emacs Info browser? That would be much more convenient than having > to fire up a web browser all the time. Thanks. There are Info docs on http://python.org/doc/current/download.html -- =*= Lukasz Pankowski =*= From anthony at interlink.com.au Mon Nov 17 07:47:06 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Mon, 17 Nov 2003 23:47:06 +1100 Subject: building python extensions with .net sdk compiler? Message-ID: <200311171247.hAHCl6gf004872@localhost.localdomain> I'm trying to build a binary of fastaudio (the wrapper for the PortAudio library, from http://www.freenet.org.nz/python/pyPortAudio/) for Python 2.3. There's a lot of FAQs and the like out there that give some simple directions, involving fetching the .net sdk from MSDN and distutils "should work" - however, when I follow them and try to do the setup.py build step, I get a message: error: Python was built with version 6 of Visual Studio, and extensions need to be built with the same version of the compiler, but it isn't installed. Argh. All I want is a simple way to say 'give me a binary object that I can drop into my site-packages directory'. Is there a way, or am I screwed? Anthony -- Anthony Baxter It's never too late to have a happy childhood. From mwh at python.net Wed Nov 5 12:46:42 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 5 Nov 2003 17:46:42 GMT Subject: dictionary keys, __hash__, __cmp__ References: <7h3fzh3hsb7.fsf@pc150.maths.bris.ac.uk> <7h3sml2hpoz.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h3oevqhfto.fsf@pc150.maths.bris.ac.uk> Jan-Erik Meyer-L?tgens writes: > Michael Hudson wrote: > > Jan-Erik Meyer-L?tgens writes: > >>Michael Hudson wrote: > >>>Jan-Erik Meyer-L?tgens writes: > >>> > >>>> 3. "If a class does not define a __cmp__() method it > >>>> should not define a __hash__() operation either." > >>>> > >> > >>Ok, let me ask the following question: What is the reason > >>for that rule? > > Well, the idea is that dictionary lookup is done by equality. If you > > don't define __cmp__ then equality is in fact identity (well, that's > > very nearly true...) so the default implementation of __hash__ (based > > ...and the full truth is? :-) Oh, something to do with __coerce__ and instances of old-style classes (well, I didn't mention __eq__ either, but I assume you know about that). > > on the pointer address) is as good as it can get (you have hash > > equality iff you have object equality). > > I think. > > > > So, this rule is a hint, only. It could break performance, > not functionality, if I define my own hash function, right? > > > To make things totally clear, I repeat my question: > > The only thing to be aware of when working with keys (besides > of object immutability) seems the following: > > Keys are equivalent (in the sense of: a key inserted under > key1 can be retrieved with key2), if this is valid: > > hash(key1) == hash(key2) and key1 == key2 > > Is this guaranteed? Yes. > In future implementations? One can't predict the entire future of course -- hey, maybe dicts will be splay trees or something one day -- but *I* would be happy depending on it. Cheers, mwh -- 42. You can measure a programmer's perspective by noting his attitude on the continuing vitality of FORTRAN. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From jepler at unpythonic.net Sat Nov 8 15:34:26 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 8 Nov 2003 14:34:26 -0600 Subject: mmap file won't open properly with Linux In-Reply-To: References: Message-ID: <20031108203425.GA29763@unpythonic.net> Read the documentation more carefully. The "0 means length of file" trick only works on windows, apparently. You can use os.fstat(fd).st_size to get the current size of an open file, or os.stat(filename).st_size to get the current size of a file by name. Jeff From unread_spamaddddress at spam0339.trash.pinguin.uni.cc Fri Nov 14 16:08:09 2003 From: unread_spamaddddress at spam0339.trash.pinguin.uni.cc (Al Bogner) Date: Fri, 14 Nov 2003 22:08:09 +0100 Subject: Tutorial for DB-Frontend with GUI Message-ID: <2560581.qn5EVrxEmu@usenet.pinguin.uni.cc> Since weeks I am searching the net from time to time how to build a small MYSQL-Frontend for a simple small database. The last decision ist not made, but it looks like, that I will learn Python. The (non-commercial) DB-frontend should run on a Linux-system only and it would be nice, but not necessary, if the program could be ported to Mac or Windows later for free. I found a lot of interesting links like http://wxpython.org/ http://boa-constructor.sourceforge.net/ http://www.die-offenbachs.de/detlev/eric3.html http://doc.trolltech.com/3.2/designer-manual-8.html http://doc.trolltech.com/3.2/sql.html http://vtcl.sourceforge.net/ http://starship.python.net/crew/mike/src/Spectix/Spectix.html http://pythoncard.sourceforge.net/ It's hard to decide, which one is the easiest way for for a python-beginner. How reliable is boa-constructor? 0.2.3-alpha seems to be not very stable. So, does anyone know a tutorial/howto/link or whatever how to build a database client with a GUI? Is there a sample database-fronted built with python in the web, where one can see what is possible? All recommendations are welcome! Al From __peter__ at web.de Mon Nov 10 12:56:30 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 Nov 2003 18:56:30 +0100 Subject: Am I the only one who would love these extentions? - Python 3.0 proposals (long) References: Message-ID: Georgy Pruss wrote: > I would like to propose some extentions to the language, probably ... > 5) Enum type. Introduces global (module-level) constants of > number or string values. The numeric values can be assigned > automatically like in the C language. If the enum declaration > has a name, this name defines "a namespace" and it must be > specified for referring to the values. > > # defines constants AXIS.X=0, AXIS.Y=1, AXIS.Z=2 > enum AXIS: X, Y, Z > > # defines color.red, color.green, color.blue > enum color > red = '#FF0000', green = '#00FF00', blue = '#0000FF' > > # defines consts A=0, B=1, C=2, D=10, E=11, F=12 > enum > A, B, C > D = 10, E > F > > # the same as above > enum: A; B, C, D=10; E, F # ';' and ',' are the same here. enum WhosAfraidOf: red yellow blue for color in WhosAfraidOf: barnetPaintsItIn(color) >>> len(WhosAfraidOf) 3 I would like something along these lines. I think you omitted the most important benefit, getting the names rather than the values, which I'm looking forward to, so I will shamelessly copy from a recent conversation on Python-Dev: [quote] > > I would love it if what happened really was something like: > > > >>>> from socket import * > >>>> print AF_UNIX > > socket.AF_UNIX > >>>> from errno import * > >>>> print EEXIST > > errno.EEXIST > > I've had this idea too. I like it, I think. The signal module could > use it too... Yes, that would be cool for many enums. [end quote] (I do not follow the list closely, but I think there was no talking of a new syntax for enums, though) > 6) The colon is optional after for,if,try,enum etc. if it is > followed by a new line. Although it's mandatory if there are > statements on the same line. So it's like ';' -- you MUST > use it when it's needed. You CAN still use it if you like it, > like now you can put a semicolon after each statement > as well. > > def abs(x) > if x < 0 > return -x > else > return x While I forget the colon more often than I'd like to, this is mostly a non-issue as it is caught by the compiler and does no runtime harm. Also, the colon would make the above example slightly more readable. > 11) Unconditional loop. Yes, I'm from the camp that > finds 'while 1' ugly. Besides, sometimes we don't need > a loop variable, just a repetition. > > loop [] > Not sure. Maybe while: repeatThisForever() > 16) Depreciated/obsolete items: > > -- No `...` as short form of repr(); > -- No '\' for continuation lines -- you can always use parenthesis; Yes, away with these! > -- No else for while,for,try etc -- they sound very unnatural; I'm just starting to use else in try ... except, so my resistance to the extra else clauses is not as strong as it used to be... > -- Ellipsis -- it looks like an alien in the language. What the heck is this? The Nutshell index does not have it, and I couldn't make any sense of the section in the language reference. Peter From theller at python.net Thu Nov 20 15:29:52 2003 From: theller at python.net (Thomas Heller) Date: Thu, 20 Nov 2003 21:29:52 +0100 Subject: "python exe" and "py plugins" References: <7k1uhl3k.fsf@python.net> Message-ID: Thomas Heller writes: > Ahmad Baitalmal writes: > >> Thomas Heller wrote: >>>>That works fine in linux or uncompiled on windows, but with py2exe, it >>>>can't find the "services" folder. >>> You should be a bit more specific here - what do you mean by "it >>> can't >>> find the services folder" ? >>> >> I figured out that's what is happening. py2exe used to package my >> "services" package because it was imported normally. But now I do a >> folder lookup to find all subfolders in my sys.executable + >> '/services' folder and >> exec("import %s" % foldername ) >> each subfolder. That's why py2exe can't package those packages when >> its building. >> >> And I'm doing it that way because the set of plugins are not known >> ofcourse, that's why I do this dynamic discovery at runtime. >> >> >> This will work, but it feels a bit patchy to me, is there a way in >> python to say "here is the path to folder x, recursevily import all >> packages you find in there"? py, pyc, pyd also? > > No, but it's easy to do that yourself. That wasn't a good answer, you already discovered that. But, you may want to organize your plugins somewhat differently. Maybe you can create a plugin package (a directory plugin, which contains an __init__.py file). And then you (or your users) write the plugins as modules contained in this directory. Or someting like that. It may be useful to look into sources which do something like this, PIL comes to mind, but there are most certainly more. Thomas From rm at rm.net Thu Nov 20 12:48:01 2003 From: rm at rm.net (Roel Mathys) Date: Thu, 20 Nov 2003 17:48:01 GMT Subject: trouble with regex with escaped metachars (URGENT please O:-) In-Reply-To: <7msprv0vf7sk2sue0cor2vkrph9mr5vhtl@4ax.com> References: <3amprvo6n734ovhg5ekatp0539q738809t@4ax.com> <7msprv0vf7sk2sue0cor2vkrph9mr5vhtl@4ax.com> Message-ID: Fernando Rodriguez wrote: > On Thu, 20 Nov 2003 16:13:19 GMT, Roel Mathys wrote: > > > >>>I get this error: >>>Traceback (most recent call last): >>> File "", line 1, in -toplevel- >>> pat.sub(s,cts) >>> File "C:\ARCHIV~1\python23\Lib\sre.py", line 257, in _subx >>> template = _compile_repl(template, pattern) >>> File "C:\ARCHIV~1\python23\Lib\sre.py", line 244, in _compile_repl >>> raise error, v # invalid expression >>>error: bogus escape (end of line) >>> >>>What on earth is this? O:-) >> >>it's the value of "value" that gives trouble (ending with a "bogus" \ >>followed by an (invisible) end-of-line. >>This little patch will do the trick, and apparantly > > > But the final backslash is escaped, it shouldn't be a problem... :-( > > like I said, don't know even stranger, with this value it does work => value = "c:\\apps\\whatever\\\\" but like I showed in the previous post, you don't really need a regex for this. eg: def substitute2( name , value , cts ) : ucts = cts.upper() uname = name.upper() parts = ucts.split( r'$<' + uname + '>' ) if len( parts ) != 2 : raise 'Something' return value.join( [ cts[:len(parts[0])] , cts[-len(parts[1]):]]) will do the job just as fine bye, rm From jjl at pobox.com Mon Nov 10 19:55:47 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Nov 2003 00:55:47 +0000 Subject: submitting a jpeg to a web site? References: Message-ID: <87d6bzd8q4.fsf@pobox.com> "Georgy Pruss" writes: > "Steven D.Arnold" wrote in message news:mailman.594.1068457889.702.python-list at python.org... > | Hi, > | > | I am curious how one might submit a JPEG to a web site using Python. > | I've tried urllib.urlopen, passing a dictionary that contained a key > | pointing to a string that contains the bytes of the JPEG, but that > | didn't apparently work. No -- you need to give urllib (or urllib2, better) the raw data to be posted, which should be MIME multipart/form-data encoded (which involves adding those funny lines starting with '--'). You also need appropriate HTTP headers. > | I did use the urllib.urlencode function on the > | dict before calling urlopen. It seems on the face of it that urlopen > | is not the ordained way to do what I want here. URL encoding is for the other way of uploading form data (application/x-www-form-urlencoded -- no peculiar MIME encoding in that case, just foo=bar&spam=eggs). multipart/form-data was invented because it would be clunky to try to shoehorn both ordinary form control data and large uploaded, possibly binary, files into the URL-encoded format. > | The
tag of the page I'm submitting to looks like this: > | > | | method="POST" enctype="multipart/form-data" accept-charset="US-ASCII"> 1. web-sig mailing list archives has a few functions for generating the appropriate data to pass to urlopen. You then just have to have the appropriate HTTP headers (I forget, but I think just Content-Type). 2. ClientForm (assuming you don't mind urlopening the web page with the form each time you want to submit it -- alternatively, keep the web page or just the form in a string or local file and use ClientForm.ParseFile, or pickle the HTMLForm objects, or whatever): http://wwwsearch.sf.net/ClientForm/ r = urllib2.urlopen("http://www.example.com/form.html") forms = ClientForm.ParseResponse(r) r.close() form = forms[0] f = open("data.dat") form.add_file(f, "text/plain", "data.dat") request = form.click() r2 = urllib2.urlopen(request) f.close() print r2.read() r2.close() [...] > It's not a "product version", but it works at my site (Windows XP, [...] > print "Content type: text/html" > print [...] Georgy, Steve was asking about about the client side. An easy mistake to make, I know... John From jroznfgre at jngpugbjreQBGbet.cy Wed Nov 26 06:30:50 2003 From: jroznfgre at jngpugbjreQBGbet.cy (JZ) Date: Wed, 26 Nov 2003 12:30:50 +0100 Subject: libmysqld.dll - any working example? Message-ID: Does anybody know any working example of using embedded MySQL library for Win32 (libmysqld.dll)? That example from MySQL manual does not work for me. I am looking for Python API to libmysqld.dll... -- JZ From andrew-wants-no-spam at fabbro.org Mon Nov 24 15:35:51 2003 From: andrew-wants-no-spam at fabbro.org (Andrew Fabbro) Date: 24 Nov 2003 12:35:51 -0800 Subject: DBI trace? References: Message-ID: Skip Montanaro wrote: > I don't know. What is DBI->trace? If you describe what you're looking for, > perhaps someone will have some ideas about whether or not it exists > currently or might be fairly easily implemented. I guess that would help, eh? Sorry ;0 DBI->trace allows you dump the entire conversation between perl and the database to a file. It's sort of like running your database calls with a "-v" to see everything that the call is doing. There are various levels of verbosity, depending on how deep you want to get. It's very helpful for seeing exactly what the parameters passed to your database are after interpolation, if your program is saying to the database what you think it is saying, if the database is giving more error output than you are seeing from perl, etc. You can do this within the DB - for example, in postgres you can change the logging levels in the postgresql.conf and bounce the DB. But obviously, you don't want to have to bounce the DB every time you want to debug. Here's an example (specifically, this was done with DBI->trace(1,'/tmp/dbi.log') in perl): -> DBI->connect(dbi:Pg:dbname=SANDBOX, andrew, ****, HASH(0x834e070)) pg_db_login <- connect('dbname=SANDBOX' 'andrew' ...)= DBI::db=HASH(0x8136970) at DBI.pm line 582 dbd_db_STORE <- STORE('PrintError' 1)= 1 at DBI.pm line 622 dbd_db_STORE <- STORE('AutoCommit' 1)= 1 at DBI.pm line 622 dbd_db_STORE <- STORE('Username' 'andrew')= 1 at DBI.pm line 625 <- connect= DBI::db=HASH(0x8136970) dbd_db_STORE <- STORE('dbi_connect_closure' CODE(0x8366194))= 1 at DBI.pm line 639 dbd_st_prepare: statement = > SELECT * FROM gl WHERE transaction_date >= ? AND transaction_date < ? AND ( account_credit = ? OR account_debit = ? )< dbd_st_preparse: statement = > SELECT * FROM gl WHERE transaction_date >= ? AND transaction_date < ? AND ( account_credit = ? OR account_debit = ? )< <- prepare(' SELECT * FROM gl WHERE transaction_date >= ? AND transaction_date < ? AND ( account_credit = ? OR account_debit = ? )')= DBI::st=HASH(0x834de48) at Accounting_Utils.pm line 367 dbd_bind_ph dbd_st_rebind dbd_bind_ph dbd_st_rebind dbd_bind_ph dbd_st_rebind dbd_bind_ph dbd_st_rebind dbd_st_execute <- execute('2003-10-01' '2003-09-01' ...)= '0E0' at Accounting_Utils.pm line 372 dbd_st_FETCH 1 <- FETCH('NAME')= [ 'glid' 'account_debit' 'amount' 'account_credit' 'transaction_date' 'reconciled' 'ref' 'note' 'last_modified' 'modified_by' ] at Accounting_Utils.pm line 376 dbd_st_fetch 1 <- fetch= undef row-1 at Accounting_Utils.pm line 376 <- fetchrow_hashref= undef row-1 at Accounting_Utils.pm line 376 <- finish= 1 at Accounting_Utils.pm line 383 dbd_db_disconnect <- disconnect= 1 at Accounting_Utils.pm line 384 dbd_st_destroy <- DESTROY= undef at index.cgi line 195 dbd_db_destroy <- DESTROY= undef at index.cgi line 195 dbd_st_FETCH 1 <- FETCH('NAME')= [ 'monthyear' 'account_number' 'amount' ] at index.cgi line 190 dbd_st_fetch dbd_st_FETCH 1 <- FETCH('NAME')= [ 'monthyear' 'account_number' 'amount' ] at index.cgi line 190 dbd_st_fetch dbd_st_FETCH 1 <- FETCH('NAME')= [ 'monthyear' 'account_number' 'amount' ] at index.cgi line 190 dbd_st_fetch dbd_st_FETCH 1 <- FETCH('NAME')= [ 'monthyear' 'account_number' 'amount' ] at index.cgi line 190 dbd_st_fetch dbd_st_FETCH 1 <- FETCH('NAME')= [ 'monthyear' 'account_number' 'amount' ] at index.cgi line 190 dbd_st_fetch dbd_st_FETCH 1 <- FETCH('NAME')= [ 'monthyear' 'account_number' 'amount' ] at index.cgi line 190 dbd_st_fetch dbd_st_FETCH 1 <- FETCH('NAME')= [ 'monthyear' 'account_number' 'amount' ] at index.cgi line 190 dbd_st_fetch dbd_st_FETCH 1 <- FETCH('NAME')= [ 'monthyear' 'account_number' 'amount' ] at index.cgi line 190 dbd_st_fetch dbd_st_FETCH 1 <- FETCH('NAME')= [ 'monthyear' 'account_number' 'amount' ] at index.cgi line 190 dbd_st_fetch dbd_st_FETCH 1 <- FETCH('NAME')= [ 'monthyear' 'account_number' 'amount' ] at index.cgi line 190 dbd_st_fetch dbd_st_FETCH 1 <- FETCH('NAME')= [ 'monthyear' 'account_number' 'amount' ] at index.cgi line 190 dbd_st_fetch (etc.) From pclinch at internet-glue.co.uk Sun Nov 23 12:30:32 2003 From: pclinch at internet-glue.co.uk (Paul Clinch) Date: 23 Nov 2003 09:30:32 -0800 Subject: Help with script with performance problems References: <6250403b.0311230213.124d969@posting.google.com> Message-ID: <8cf2994e.0311230930.2995f4af@posting.google.com> mikit at zoran.co.il (Miki Tebeka) wrote in message news:<6250403b.0311230213.124d969 at posting.google.com>... > Hello Dennis, > > A general note: Use the "hotshot" module to find where you spend most of your time. > > > splitline = string.split(line) > My guess is that if you'll use the "re" module things will be much faster. > > import re > ws_split = re.compile("\s+").split > ... > splitline = split(line) > ... > > HTH. > > Miki An alternative in python 2.3 is the timeit module, the following extracted from doc.s:- import timeit timer1 = timeit.Timer('unicode("abc")') timer2 = timeit.Timer('"abc" + u""') # Run three trials print timer1.repeat(repeat=3, number=100000) print timer2.repeat(repeat=3, number=100000) # On my laptop this outputs: # [0.36831796169281006, 0.37441694736480713, 0.35304892063140869] # [0.17574405670166016, 0.18193507194519043, 0.17565798759460449] Regards Paul Clinch From wade at lightlink.com Sat Nov 15 10:36:18 2003 From: wade at lightlink.com (Wade Leftwich) Date: 15 Nov 2003 07:36:18 -0800 Subject: A vote for re scanner References: <5b4785ee.0311100714.1445cdfb@posting.google.com> <698f09f8.0311101455.41f8706a@posting.google.com> <5b4785ee.0311121304.25e41857@posting.google.com> Message-ID: <5b4785ee.0311150736.48aef621@posting.google.com> Alex Martelli wrote: > Wade Leftwich wrote: > ... > > A scanner is constructed from a regex object and a string to be > > scanned. Each call to the scanner's search() method returns the next > > match object of the regex on the string. So to work on a string that > > has multiple matches, it's the bee's roller skates. > > ...if that method's name was 'next' (and an appropriate __iter__ > also present) it might be even cooler, though... > > > Alex Indeed: >>> class CoolerScanner(object): ... def __init__(self, regex, s): ... self.scanner = regex.scanner(s) ... def next(self): ... m = self.scanner.search() ... if m: ... return m ... else: ... raise StopIteration ... def __iter__(self): ... while 1: ... yield self.next() ... >>> regex = re.compile(r'(?P.)a(?P.)') >>> s = '1ab2ac3ad' >>> for m in CoolerScanner(regex, s): ... print m.group('before'), m.group('after') ... 1 b 2 c 3 d >>> -- Wade From jeff at cowz.com Tue Nov 11 14:58:36 2003 From: jeff at cowz.com (Jeff Sykes) Date: 11 Nov 2003 11:58:36 -0800 Subject: module import performance question References: <729b56c7.0311102210.4869d4f6@posting.google.com> Message-ID: <729b56c7.0311111158.3602e7d5@posting.google.com> Thanks, Emile, that's a good idea. I found another issue, too. See my response to another poster below: >> I think there was a different culprit, though. After some more >> dilligent logging, I realized that immediately after import I >> called upon an attribute of the imported module that wouldn't >> _necessarily_ be present. When the attribute was not present, >> it raised an exception, which I caught. This exception handling >> was a real performance anchor! I now check hasattr() before I >> execute this block of code, and this has helped performance >> significantly. >> >> Here's a snip of the block that occured right after import: >> >> try: >> # next line was not there before >> if hasattr(dyn_blocks[key], "BUFFER_ON"): >> context.setBufferFlag(dyn_blocks[key].BUFFER_ON) >> except: >> Log.stacktrace(Log.ERROR) >> >> I guess the lesson I learned is don't use exception handling >> unnecessarily. Which I know not to do anyway. Sigh. Back to >> school for me. "Emile van Sebille" wrote in message news:... > "Jeff Sykes" wrote in message > news:729b56c7.0311102210.4869d4f6 at posting.google.com... > > I have a cgi script that imports modules based on a user config > file. > > I am suffering some performance problems when I import these > modules. > > Some logging revealed that it seems to be taking about 1.3 seconds > to > > import these modules. This is running on a Windows 2000 box with a > > Pentium II 400 processor, Python 2.1, Apache 1.3.19 as the web > server. > > I don't need screaming performance numbers, but this time is > > excessive. Is it me, or does that number seem kind of slow? > > How many modules are being imported? > > > Any code > > optimizations or recommendations? > > Don't append to sys.path. Try sys.path.insert(0,addlpath). Then the > import will get an immediate hit and always the right module rather > than stepping through all the preceeding directories. > > HTH, > > > Emile van Sebille > emile at fenx.com From dberlin at dberlin.org Sun Nov 23 13:32:17 2003 From: dberlin at dberlin.org (Daniel Berlin) Date: Sun, 23 Nov 2003 13:32:17 -0500 Subject: Use of GPLed Python extension modules In-Reply-To: <653b7547.0311230804.760628f5@posting.google.com> References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> <7xwu9svyny.fsf@ruckus.brouhaha.com> <653b7547.0311230804.760628f5@posting.google.com> Message-ID: <5DB68594-1DE3-11D8-9A1C-000A95DA505C@dberlin.org> On Nov 23, 2003, at 11:04 AM, Patrick Maupin wrote: > Daniel Berlin wrote >> On Nov 22, 2003, at 5:33 PM, Rainer Deyke wrote: >> ... >>> Either you are misinterpreting the FSF, or the FSF is wrong. >> >> Sigh. >> Can't we simply leave legal questions to lawyers and judges? > > Sure. That's what democracy is all about :) > > Or the less flippant answer is: there are several areas of the > law in which laymen can have a legitimate interest and something > to say. This is true about any subject. > >> The FSF is entitled to their view, and one could argue it and expect >> some chance of success. > > Yes, where "some chance" is an extremely small number. > >> One could argue the other way, and expect some chance of sucess. >> This is because there simply is no settled law, precedent, etc, >> on the subject. > > Repeating this mantra, as you and several others on this thread > have done, simply does not make it true. Like most canards, this > has a kernel of truth, namely that the FSF itself has not been > in litigation over this issue. But if you think that this issue > has never been litigated, you have not boiled it down to its > most basic elements and then looked for case law. Actually, I have. On both Lexis, and Westlaw. Sorry, no caselaw. > > As I understand it, the abstract version of the case would boil > down to this: > > - A company notices that program A is a useful tool for other > programs to use, and produces program B, which contains no > code from program A, but which invokes and uses program A > at runtime. > - When this company distributes program B, the makers of program > A sue the company for copyright violation. (They do not sue > the users who actually combine the two programs together, because > a) those users probably have a license to do this, and b) > that would be bad for business.) > > This issue has come up repeatedly and has been litigated extensively, Cases and citations please. > by companies with big budgets and good lawyers. I do not personally > know of any cases where the producer of program A has prevailed (absent > literal copying of program A), but I _do_ know of more than one case > where the maker of program B has prevailed (see Sega vs. Accolade for > a start). Note that in these cases, the producer of program B > has usually copied program A in the process of reverse-engineering > it (which would not even need to happen to use a GPLed program), > and this copying has been ruled to be fair use. > > I didn't even take copyright law, and I'm sure that either a) you are > deliberately being unreasonably pedantic, Given. > or b) you are exceedingly > dense. If you were to read the OP in the full context of the thread, > you would find that what he was really saying was that if party X > generates a pile of new code all by himself, the fact that the FSF > has some OTHER copyrighted code (and in the context, I'm sure the OP > means either owns or somehow controls this other code) does not > give the FSF any right to restrict what party X does with his own > code, It may or may not. It depends on the code. If it's the same code as the copyrighted code, they would have such a right. > so party X is free to give his own code to whomever he cares > to, under whatever terms he chooses (but under some circumstances, > party X can certainly be enjoined from distributing the FSF's own code > alongside party X's own code). This is true EVEN IF party X's code > has the ability to make use of the FSF's code. In my opinion, the > OP made this point clearly and succinctly, and I'm sure that everybody > except you understood him perfectly. > Blah blah. More personal attacks for no reason. >> In addition, DMCA grants them the right to prevent distribution of >> certain other types of code (code that circumvents effective access >> controls). > > Umm, yeah. I'm thinking real hard here to try to come up with a > license that is _less_ compatible with DMCA-style "access controls" > than the GPL. I'm drawing a blank here. Can anyone help me out? > > (Hint: The GPL is the "anti-DMCA". Only use it on code you want > to insure is available to anybody, at any time, in any place.) > More of you being an ass for no reason. >> >>> Whether the code may be linked to GPL code at runtime >>> or not is irrelevant. >> This may or may not be true. >> Stating your opinion as fact is not helping. > > Yes, I find your deliberate misunderstanding of the OP _so_ much > more helpful. Throwing in that DMCA red herring was a nice touch > as well. > > Pat > -- > http://mail.python.org/mailman/listinfo/python-list From reply.in.the.newsgroup at my.address.is.invalid Sat Nov 22 04:30:09 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 22 Nov 2003 10:30:09 +0100 Subject: Database bind variables? References: Message-ID: <2faurv8aqutrign6330vsb2ovotr2pc7l8@4ax.com> Andrew Fabbro: >Python + Postgres. Finding good documentation on working with >databases in python is proving more challenging than writing the code After scanning this newsgroup and other sources I decided to use the pyPgSQL database driver, instead of PyGreSQL in the PostgreSQL distribution (DaMn CaPS). It appears to be better maintained. http://pypgsql.sourceforge.net/ It supports DBAPI. http://www.python.org/peps/pep-0249.html With some additional notes in the README: http://pypgsql.sourceforge.net/README.html This is all the documentation I've needed so far. [parameters] >I haven't found a way to do this yet with pygresql With pyPgSQL / DB-API it works like this. from pyPgSQL import PgSQL assert PgSQL.paramstyle == "pyformat" db = PgSQL.connect(host=DB_HOST, database=DB_DATABASE, user=DB_USERNAME, password=DB_PASSWORD, # Enable Unicode support, which you may not need. client_encoding="utf-8", unicode_results=1) cursor.execute("set client_encoding to unicode") get_cities = db.cursor() def getCitiesInCountry(language, country): get_cities.execute("select name, name_in_url, index " "from location " "where location.country = %(country)s and " "location.location_type = 'cities' and " "location.language = %(language)s " "order by location.index", {'language': language, 'country': country} ) # [...] -- Ren? Pijlman From john_bradbury at skipthistalk21.com Thu Nov 13 12:10:23 2003 From: john_bradbury at skipthistalk21.com (John Bradbury) Date: Thu, 13 Nov 2003 17:10:23 +0000 (UTC) Subject: GUI - Qt Designer References: Message-ID: Peter Kropf wrote: > Take a look at PyQt (http://www.riverbankcomputing.co.uk/pyqt/index.php). > It has a pyuic component that will compile the .ui files into .py. > > - Peter Thanks, this is just what I am after. John > > >> -----Original Message----- >> From: John Bradbury [mailto:john_bradbury at skiptalk21.com] >> Sent: Wednesday, November 12, 2003 10:05 AM >> To: python-list at python.org >> Subject: GUI - Qt Designer >> >> >> Is there any way to take the output produced by Qt designer >> (or any other >> GUI designer) and use it in Python to create a screen? There >> must be a >> better way of creating screens than having to use the TkInter >> routnes and >> add every widget one by one in the program. >> >> John Bradbury >> -- >> http://mail.python.org/mailman/listinfo/python-list >> From janeaustine50 at hotmail.com Mon Nov 17 20:46:36 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 17 Nov 2003 17:46:36 -0800 Subject: Memory exception with Tkinter root.quit Message-ID: >>> from Tkinter import * >>> r=Tk() >>> b=Button(r,text='Quit',command=r.quit) >>> b.pack() >>> r.mainloop() And when I press the "Quit" button the mainloop exits. After that, if I finish the python shell, a memory exception occurs. This is Windows XP machine with Python 2.3. Can anyone see the problem? Jane From project5 at redrival.net Tue Nov 18 17:14:25 2003 From: project5 at redrival.net (Andrei) Date: Tue, 18 Nov 2003 23:14:25 +0100 Subject: Looking for code References: Message-ID: <4u6g3y13v5nc$.lm82dipragti$.dlg@40tude.net> Andy Koch wrote on Tue, 18 Nov 2003 21:15:33 GMT: > Hello. I am new to Python and for the most part new to programming. The > best way to learn to write is to read, so I have been looking for a > website that has the code of programs written in Python. If anyone knows > of a good place to find something like this, I would be very grateful if > you could respond. > Thanks! The obvious place to look for relatively simple snippets is http://uselesspython.com. But Vaults of Parnassus is nice too. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From news at u-schramme.de Thu Nov 13 04:38:23 2003 From: news at u-schramme.de (Ulrich Schramme) Date: Thu, 13 Nov 2003 10:38:23 +0100 Subject: Palindrome In-Reply-To: References: <20031112223135.29045.00000109@mb-m12.aol.com> Message-ID: Andrew Dalke wrote: > Ulrich Schramme: > >>I?m not very experienced with Python but I think you could do it in a >>more simple way. > > > Looks good to me. And it shows that I'm no longer able to help out > beginning programmers since my solution is along the lines of > > inp = raw_input('Enter a string: ') > > punctuation = '%$!*.,-:? ;()\'\"\\' > foldcase = [chr(i) for i in range(256)] > for upper, lower in zip(string.ascii_uppercase, string.ascii_lowercase): > foldcase[ord(upper)] = lower > foldcase = "".join(foldcase) > > t = inp.translate(foldcase, punctuation) > if t != t[::-1]: > print '"' + inp + '" ' + 'is a palindrome.' > else: > print '"' + inp + '" ' + 'is not a palindrome.' > > Faster, but with a startup cost and a high learning curve. > It's what I would use for my own code. > > A slightly easier to understand and slower version is > > inp = raw_input('Enter a string: ') > punctuation = '%$!*.,-:? ;()\'\"\\' > identity = "".join([chr(i) for i in range(256)]) > > t = inp.translate(identity, punctuation).lower() > if t != t[::-1]: > ... > > Yours is definitely easiest to understand so best for > the OP. > > Cheers, > Andrew > dalke at dalkescientific.com > > Thanks Andrew, there might be a million ways to solve the palindrome problem. I think that another good way would be the use of regular expressions. I?m a software developer by profession but quite new to Python. So I tried to find an easy way that fits my limited knowledge of the Python syntax. My first impression of Python is that it is a well - designed and interesting language. I also like this newsgroup. People here seem to be more helpful than in some other groups I know... Hopefully taking part in discussions here will improve my English as well as my Python :-) -- -- Ulli www.u-schramme.de From wester at ilt.fraunhofer.de Fri Nov 21 03:52:14 2003 From: wester at ilt.fraunhofer.de (Rolf Wester) Date: Fri, 21 Nov 2003 09:52:14 +0100 Subject: httplib and Proxy In-Reply-To: References: Message-ID: Rolf Wester wrote: > Hi, > > I want to fetch some web-pages via http. I know how to do this without a > proxy server in between but unfortunately we can only access the > internet via a proxy. I would be very appriciative if anybody could tell > me how to do this. > > Thanks in advance > > Rolf Wester > > P.S.: I would not mind to use sockets directly > Hi, thank you all for your help. I tried urllib, httplib and sockets. With urllib: f = urllib.urlopen("http://www.python.org/index.html") I get: ... invalid proxy for http: 'cache.ilt.fhg.de:81' httplib works: conn = httplib.HTTPConnection("cache.ilt.fhg.de", 81) conn.request("GET", "http://www.python.org/index.html") r = conn.getresponse() print r.status, r.reason print r.msg while 1: data = r.read(1024) if len(data) < 1024: break print data and so do sockets: HOST = 'cache.ilt.fhg.de' PORT = 81 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send('GET http://www.python.org/index.html HTTP/1.1\r\nAccept: text/plain\r\n\r\n') while 1: data = s.recv(1024) print data if len(data) < 1024: break s.close() Thanks again Rolf Wester From akineko at pacbell.net Thu Nov 13 12:28:09 2003 From: akineko at pacbell.net (Aki Niimura) Date: 13 Nov 2003 09:28:09 -0800 Subject: Reversing an iterator with older version of Python References: Message-ID: "A.M. Kuchling" wrote in message > Convert it to a list and then reverse the list: > > L = list(iterator) > L.reverse() It did the job for me. Now my python program is working as I intended. Hope I can move to a newer version of Python soon so that I can use an iterator much like a list. Thank you! Aki Niimura From jcb at iteris.com Sat Nov 15 20:34:00 2003 From: jcb at iteris.com (MetalOne) Date: 15 Nov 2003 17:34:00 -0800 Subject: Is RAII possible in Python? References: <4_utb.21936$IK2.1678737@news20.bellglobal.com> Message-ID: <92c59a2c.0311151734.5d05d8c8@posting.google.com> You need to use the try/finally statement or see PEP 310. http://www.python.org/peps/pep-0310.html From john at rygannon.com Tue Nov 4 18:29:38 2003 From: john at rygannon.com (John Dean) Date: Tue, 4 Nov 2003 23:29:38 GMT Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0310312008.ce341ea@posting.google.com> <87r80sdyb1.fsf@pobox.com> <7xn0bg6njb.fsf@ruckus.brouhaha.com> <7x7k2jpti9.fsf@ruckus.brouhaha.com> <3fa6a66a$0$12690$fa0fcedb@lovejoy.zen.co.uk> <3fa78ee1$0$12706$fa0fcedb@lovejoy.zen.co.uk> <7xbrrrrdze.fsf@ruckus.brouhaha.com> Message-ID: <3fa8363e$0$12687$fa0fcedb@lovejoy.zen.co.uk> I meant to reply to you privately but. Anyway I take your point and I guess that is what we will do BTW Didn't we meet once at a Perl User Group meeting when I was still working for MySQL? Monty and David were giving a talk if I remember -- Best Regards John From klapotec at chello.at Tue Nov 25 01:14:20 2003 From: klapotec at chello.at (Christopher Koppler) Date: Tue, 25 Nov 2003 06:14:20 GMT Subject: sleep() function, perhaps. References: Message-ID: On Tue, 25 Nov 2003 05:26:25 GMT, Ryan Spencer wrote: > >Hello Everyone, > > I want to have a row of periods, separated by small, say, .5 second >intervals between each other. Thus, for example, making it have the >appearance of a progress "bar". > >[code] >import time > >sleep(.5) >print "." >sleep(.5) >print "." >[end code] > >But, it would (with those .5 second intervals) >print out much like the following. > >. >(pause) >. >(pause) > >I would rather those periods be on a single line, not printing on a new >line each time. > >Any suggestions? Try print with added comma or sys.stdout.write, like so: >>> import time >>> for i in range(10): ... print '\b.', ... time.sleep(1.5) ... .......... >>> import sys >>> for i in range(10): ... sys.stdout.write('.') ... time.sleep(0.5) ... .......... -- Christopher From guy at NOSPAM.r-e-d.co.nz Sun Nov 30 03:21:23 2003 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Sun, 30 Nov 2003 21:21:23 +1300 Subject: problem capturing output from dos program Message-ID: Hello, This works and correctly outputs the file out2.dwf import os test = os.popen("rewrite.exe test.dwf out2.dwf /a") for L in test.readlines(): print L this prints the statistics from the translation. The things is I want to capture the output file for further processing. I tried this: infile = 'test.dwf' outfile = 'out3.dwf' os.spawnl(os.P_WAIT,'rewrite.exe',infile,outfile,'/a') And it doesn't work, is not spawnl correct method. What am I doing wrong? The dos box disappears too quickly to see what the error is and ideally I don't want to see a dos box anyway. Regards, Guy From simonb at webone.com.au Mon Nov 10 20:30:50 2003 From: simonb at webone.com.au (Simon Burton) Date: Tue, 11 Nov 2003 12:30:50 +1100 Subject: What do you think of this Python logo? References: Message-ID: On Mon, 10 Nov 2003 14:16:38 -0800, Brandon J. Van Every wrote: > What do you think of this Python logo? > http://pythonology.org/logos > Good, bad, indifferent, love it, hate it? Very nice! I like it. Simon. From hokiegal99 at hotmail.com Fri Nov 21 16:55:20 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Fri, 21 Nov 2003 16:55:20 -0500 Subject: os.walk help Message-ID: This script is not recursive... in order to make it recursive, I have to call it several times (my kludge... hey, it works). I thought os.walk's sole purpose was to recursively walk a directory structure, no? Also,it generates the below error during the os.renames section, but the odd thing is that it actually renames the files before saying it can't find them. Any ideas are welcomed. If I'm doing something *really* wrong here, just let me know. #-------------- ERROR Message ----------------------# File "/home/rbt/fix-names-1.1.py", line 29, in ? clean_names(setpath) File "/home/rbt/fix-names-1.1.py", line 27, in clean_names os.renames(oldpath, newpath) File "/usr/local/lib/python2.3/os.py", line 196, in renames rename(old, new) OSError: [Errno 2] No such file or directory #------------- Code -------------------------# setpath = raw_input("Path to the Directory: ") bad = re.compile(r'[*?<>/\|\\]') for root, dirs, files in os.walk(setpath): for dname in dirs: badchars = bad.findall(dname) for badchar in badchars: newdname = dname.replace(badchar,'-') if newdname != dname: newpath = os.path.join(root, newdname) oldpath = os.path.join(root, dname) os.renames(oldpath, newpath) From bokr at oz.net Sun Nov 2 19:13:58 2003 From: bokr at oz.net (Bengt Richter) Date: 3 Nov 2003 00:13:58 GMT Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <87d6cjope5.fsf@pobox.com> <87he1vsopi.fsf@pobox.com> <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> <2259b0e2.0311012219.73aa445f@posting.google.com> Message-ID: On 1 Nov 2003 22:19:11 -0800, mis6 at pitt.edu (Michele Simionato) wrote: >Stephen Horne wrote in message news:... [...] >> The evidence suggests that conscious minds exist >> within the universe as an arrangement of matter subject to the same >> laws as any other arrangement of matter. If there is some "stuff" whose state can eventually be shown to have 1:1 relationship with the state of a particular individual's conscious experience, this would seem to imply that senses and brains etc. are effectively transducers between reality and our experiencing-stuff. Does the "experiencing-stuff" itself have matter-nature or field-nature? >From the fact that my consciousness goes out like a light almost every night, I speculate that that what persists day to day (brains, synaptic connections, proteins, etc) is not the _essential_ basis of my experience, but rather, those persistent things somehow _shape_ the medium through whose state-changes my conscious experience arises. What are the limitations on the states of the experience-medium? It seems that e.g., damaged brains create changes in the possible range of experiences, both creating new possibilities and removing others, but this would not seem to be a limitiation of the experience-medium itself, but rather of the reality-transducer. Besides physical brain changes, drugs can also apparently change how the reality-transducer works or does not work (e.g., psychedelics or anaesthetics). But what of the (hypothetical at this point) medium itself? Could it be capable of other states if it were conditioned by another transducer? (How would the experiencer know that was happening, BTW?) E.g., are the limitations on temperature and electrical gradients etc. of the brain effectively limitiations on the range of possible conscious experience, that might not limit experience conditioned through another "transducer?" Now consider the experience of being "convinced" that a theory "is true." What does that mean? Does our experience-medium get shaped repeatedly through layers and layers of abstraction and re-representation to where some bit of memory is sensed to have a comfortable stability w.r.t. sensations derived from a series of experiemnts, and we are satisfied by some pleasure-connect with this state of brain? Is it pain and pleasure at bottom, tied to subtle internal state sensations? Do we form theories like patterns of sand form on a vibrating membrane at quiescent spots for a given mode of vibration? Do internal cognitive dissonances drive the "sand" away from untenable positions in patterns of theory? Is our conscious experience-medium passive in being shaped by the transducer, or does it have its own properties? E.g., is our sense of connected-ness of a broken line in our visual conscious experience due to shaping of a field? I.e., due to our very experience medium having field-nature and naturally taking some form across gaps between features due to its own properties? >I think that mind is a an arrangement of matter, too; nevertheless, >I strongly doubt that we will ever be able to understand it. Incidentally, I think we will find out a lot yet. Beautiful, subtle stuff ;-) Too bad we are wasting so much on ugly, dumb stuff ;-/ >I am also quite skeptical about IA claims. Yes, but AI doesn't have to be all that "I" to have a huge economic and social impact. The trend is towards private concentrated control and ownership of super-productive capital equipment (temporarily simulated as necessary by Asian cheap labor), and AI IMO will play an evolving role. The question is how the increasingly large fraction of people who will not be needed for producing anything will be able to play the role of customer, unless we figure out some new social machinery to go along with the other kind. ... Maybe a UN-member-funded humanitarian consortium should buy Google before it becomes conscious as someone's private genie ;-) Well, as you say, [...] >That's life, but it is more interesting this way ;) Yes, and we could be working on global renaissance if we could globally figure out how to spend $500bn/year (>15kUSD/second!) on good stuff instead of miserable conflict. I would like to see leaders elected who re-affirm at every news/media event the goal of eliminating this global stupidity, and see the ability to kill fellow humans (at least) as aberrant instead of just another notch on the scale of dirty-play competition that they are willing to engage in themselves -- unable to recognize their own aberration through the thinnest delusory veils of justification (never mind through the filters of a raging polarized mindset). Sorry, I get a little upset with the waste and consequent unnecessary suffering ;-/ Regards, Bengt Richter From bnet at ifrance.com Sat Nov 1 19:16:36 2003 From: bnet at ifrance.com (Benoit Dejean) Date: Sun, 02 Nov 2003 01:16:36 +0100 Subject: another dictionary q References: Message-ID: Le Sat, 01 Nov 2003 23:03:24 -0800, ruari mactaggart a ?crit?: > can this be tidied up ? > >>>>verb={} >>>>verb[infinitive]=[['','','','','',''],['','','','','',''],['','','','','' > ,''],['','','','','',''],['','','','','',''],['','','','','','']] verb[infinitive]=[['']*6]*6 From domma at procoders.net Mon Nov 3 15:41:37 2003 From: domma at procoders.net (Achim Domma) Date: Mon, 3 Nov 2003 21:41:37 +0100 Subject: SMTP Authentication Message-ID: Hi, I try to authenticate via script to my mail server. I found some hints via google, that SMTP authentication is a problem, but no solution. Using set_debuglevel(1), I can see something like that: send: 'ehlo [10.0.0.35]\r\n' reply: '250-essen115.server4free.de Hello p50837A3A.dip.t-dialin.net [80.131.122 .58], pleased to meet you\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' [...] reply: '250-AUTH PLAIN LOGIN DIGEST-MD5 CRAM-MD5\r\n' [...] reply: retcode (250); Msg: essen115.server4free.de Hello p50837A3A.dip.t-dialin. net [80.131.122.58], pleased to meet you [...] AUTH PLAIN LOGIN DIGEST-MD5 CRAM-MD5 [...] send: 'AUTH CRAM-MD5\r\n' reply: '334 PDM0NDE5NDYxMzAuMTA5MjcxNDFAZXNzZW4xMTUuc2VydmVyNGZyZWUuZGU+\r\n' reply: retcode (334); Msg: PDM0NDE5NDYxMzAuMTA5MjcxNDFAZXNzZW4xMTUuc2VydmVyNGZyZ WUuZGU+ send: 'd2ViMXAxIDk1Yzk5ZDM3ZWI1MDMxZmI4YjFmNjJhNmY2MjUzMGYy\r\n' reply: '535 5.7.0 authentication failed\r\n' reply: retcode (535); Msg: 5.7.0 authentication failed Traceback (most recent call last): File "C:\scripts\wg_plan.py", line 41, in ? server.login('my_login',pwd) File "C:\Python23\lib\smtplib.py", line 583, in login raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, '5.7.0 authentication failed') Can somebody give me a hint on how to encode the pwd? Or another way to send mail, if the server requires authentication? regards, Achim From tr at jotsite.com Wed Nov 5 16:21:49 2003 From: tr at jotsite.com (Hoang) Date: Wed, 05 Nov 2003 21:21:49 GMT Subject: dump table and data with mysqldb References: <99dce321.0311050726.3e369dcf@posting.google.com> Message-ID: Thanks David for the little code snippets. They help in figuring out the table structures. Now if I can get the output of: "SELECT * FROM database INTO OUTFILE file" to redirect to across the network rather than the local file-system. mysqldump also puts it into the local FS. There might be no recourse other than having to recreate the INSERT statements in your own code. Hoang Do From mwh at python.net Tue Nov 18 09:54:40 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 18 Nov 2003 14:54:40 GMT Subject: pyc / pyo architecture independent? References: Message-ID: Terry Hancock writes: > This question was brought up by packagers trying to set > policy for including Python modules in Debian Gnu/Linux: > > Are the .pyc / .pyo files safely architecture independent? > (I.e. are they now, and are they likely or even guaranteed > to remain so?). Yes. .pycs are marshalled code objects (mostly) so the notes in http://www.python.org/doc/current/lib/module-marshal.html apply. Cheers, mwh -- CLiki pages can be edited by anybody at any time. Imagine the most fearsomely comprehensive legal disclaimer you have ever seen, and double it -- http://ww.telent.net/cliki/index From fumanchu at amor.org Fri Nov 7 00:48:45 2003 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 6 Nov 2003 21:48:45 -0800 Subject: Creating a random integer.... Message-ID: Your first stop should be the Library Reference: http://www.python.org/doc/2.2.3/lib/lib.html You'll find the random module in section 5.6. Robert Brewer MIS Amor Ministries > -----Original Message----- > From: Code_Dark [mailto:rooting_j00 at hotmail.com] > Sent: Thursday, November 06, 2003 9:41 PM > To: python-list at python.org > Subject: Creating a random integer.... > > > Hi, sorry to bore you with my newbie questions, but I _am_ a newbie > so.. right. Anyway, I was working out a "number guessing game", which > works fine, except I wanted to make the number a random number so it's > different every time... can you please tell me what to do to get > python to create a random number? > > Thanks, > > - Code Dark > -- > http://mail.python.org/mailman/listinfo/python-list > From google.com.112139 at satilla.com Fri Nov 21 01:31:47 2003 From: google.com.112139 at satilla.com (Eric Baker) Date: Fri, 21 Nov 2003 01:31:47 -0500 Subject: MP3-Player in Python? References: Message-ID: "Thorsten Pferdek?mper" schrieb im Newsbeitrag news:bpg2l7$d9v$1 at news1.wdf.sap-ag.de... > Hi, > I am currently trying to code a little MP3-Player in Python. I do not try to > do all the decoding stuff in Python, I am just looking for a (more or > less...) platform independent way to play MP3s. I also want to display > information like these stored in the ID3-tag and information like the length > in seconds, the scan frequency etc. > So far, I have found the following solutions, but I am not really happy with > all of them: > > 1. pygame.mixer.music: > Pros: Seems to be very platform independent > Cons: I was not able to get the length in seconds etc. > > 2. tksnack > Pros: Lots of functionality. Really cool. > Cons: Needs Tkinter to run. (I would like to run this without X in > Linux.) > > 3. popen mplayer or something like this > Pros: ? > Cons: Don't know how to control volume, position etc. > Dont' know how to close mplayer in Windows... > > So far for the MP3 playing stuff. > > Concerning the ID3 tags, I have found the id3-py package > (id3-py.sourceforge.net). It worked, but I dislike the automatic saving of > changes on deconstruction. It also causes problems with german umlauts... > It also seems not to support ID3v2. > > I also know mmpython, but I do not know how to run this with Windows XP. (It > works fine with Linux...) > > So, what do you think? > > Regards, > Thorsten I tried this under windows, it worked quite well. It will play the files, you will need other modules for tags and such things. http://audiere.sourceforge.net/home.php Audiere is a high-level audio API. It can play Ogg Vorbis, MP3, FLAC, uncompressed WAV, AIFF, MOD, S3M, XM, and IT files. For audio output, Audiere supports DirectSound or WinMM in Windows, OSS on Linux and Cygwin, and SGI AL on IRIX. Eric From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Thu Nov 6 03:58:51 2003 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Thu, 6 Nov 2003 09:58:51 +0100 Subject: Listing computers of a WinNT-Domain References: Message-ID: Hi ! Windows pb, not Python. This domain : - is with AD ? - same protocol ? - same rights ? - connected like Administrator ? - some services are disactived ? - have you try with WMI ? - have you try on the server primary server domain ? - etc. - etc. Good courage... @-salutations an *sorry for my bad english* -- Michel Claveau From aleax at aleax.it Mon Nov 10 05:20:46 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 10 Nov 2003 10:20:46 GMT Subject: Newbie - 1st Program References: Message-ID: <2EJrb.120425$e5.4356705@news1.tin.it> Mark Smith wrote: ... > It seems to work - great - but how would you make this more 'elegant' - > I'm sure it's horrible to an experienced hacker... Not half bad, actually! I would suggest one improvement: avoid floating point when you don't need it. In this case: > totalPorts = float(inputPorts) + float(outputPorts) ... > crossConnects = (totalPorts / 2) * (totalPorts - 1) you probably inserted the float() calls when you found out that the crossConnects computation got truncated when totalPorts was an odd integer. But that's just because you're specifying the computations in the wrong order there. Try, instead: totalPorts = inputPorts + outputPorts crossConnects = (totalPorts * (totalPorts - 1)) / 2 The product "totalPorts * (totalPorts - 1)" is guaranteed to be even for any integer totalPorts, therefore you don't need to worry about truncation when you divide it by two. Incidentally, I'm not sure about your "connection routes" count -- it seems to include the possibility of connecting two output ports to each other, etc. I guess that may or may not make sense, electrically and logically, depending on your setup. When a valid "connect" is just between one output port and one input port, of course, the number of possible connects is inputPorts*outputPorts. But this isn't really about Python programming (or any other kind of programming), of course -- except in that it reminds us that no matter how well we code, first and foremost we must ensure we're computing what we really WANT to compute -- and that comments exist to reassure readers and maintainers of the code that we have taken this into account (e.g., some note in the leading comment about the possibility of connecting two "egress ports" directly to each other would have reassured me, as a reader of the code, that the computation being performed is indeed correct). Alex From tanner at rogers.com Fri Nov 21 02:51:34 2003 From: tanner at rogers.com (tanner at rogers.com) Date: Fri, 21 Nov 2003 07:51:34 GMT Subject: Initializing forms in PyQT Message-ID: I'm new to Python & PyQT so please bear with me. I have a collection of QT Designer generated .ui files that will comprise the app interface. These are compiled using pyuic under Eric3. My problem is that these .ui files are still evolving, and that my mods to the the forms' code get clobbered whenever I regenerate the .ui files. Is there a method to embed python code in the actual .ui files themselves? Or is there an accepted method of having a form either manually or automatically initialize itself by calling a seperate file? (The source code of Eric3 generally seems to organize related .ui files into subdirectories, each of which contains an __init__.py file. I'm not sure of the mechanics of how/when this file is handled.) QT Designer generates stubs for SLOTS in it's code. I wish to over-ride replace the SLOTS fuctions through the use of my seperate file. Any help or comments is appreciated. -- Please remove to reply directly. From eddieNOSPAM at eddiecentral.net Fri Nov 21 18:03:16 2003 From: eddieNOSPAM at eddiecentral.net (eddieNOSPAM at eddiecentral.net) Date: Fri, 21 Nov 2003 23:03:16 GMT Subject: python regular expression Message-ID: I am trying to edit a bunch of files that are similar. I want to remove all the ASP code that appears before the tag. Can some one help me with a regex that can replace everything before the tag with nothing? From aleax at aleax.it Sat Nov 1 05:42:11 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 01 Nov 2003 10:42:11 GMT Subject: HTMLParser problems. References: <873cd9m6mo.fsf@pobox.com> Message-ID: <76Mob.76910$e5.2856611@news1.tin.it> Terry Reedy wrote: >> > Back in the day in pascal you could do stuff like >> > "with self begin do_stuff(member_variable); end;" >> > which was extremely useful for large 'records.' > > There have been proposals something like that, but they do not seem to > fit Python too well. No, but, for the record: just last week in python-dev Guido rejected a syntax proposal using a leading dot to strop a variablename in some circumstances (writing '.var' rather than 'var' in those cases) for the stated reason that, and I quote: "I want to reserve .var for the "with" statement (a la VB)." So, something like "with self: dostuff(.member_variable)" MIGHT be in Python's future (the leading dot, like in VB, at least does make things more explicit than leaving it implied like Pascal does). >> mv = self.member_variable >> do_stuff(mv) > > In case you think this a hack, it is not. Copying things into the > local variable space (from builtins, globals, attributes) is a fairly > common idiom. When a value is used repeatedly (like in a loop), the > copying is paid for by faster repeated access. Sure, good point. It _is_ a hack by some definitions of the word, but that's not necessarily a bad thing. A quibble: the optimization may be worth it when the NAME is used repeatedly -- repeated uses of the VALUE, e.g. within the body of do_stuff, accessing the value through another name [e.g. the parametername for do_stuff] do not count, because what you're optimizing is specifically name lookup. E.g., one silly example: [alex at lancelot bo]$ timeit.py -c -s'x=range(999)' 'for i in range(999): x[i]=id(x[i])' 1000 loops, best of 3: 590 usec per loop [alex at lancelot bo]$ timeit.py -c -s'x=range(999)' -s'lid=id' 'for i in range(999): x[i]=lid(x[i])' 1000 loops, best of 3: 490 usec per loop the repeated lookups of builtin name 'id' in the first case accounted for almost 17% of the CPU time, so the simple optimization leading to the second case may be worth it if this code is in a bottleneck. In a way, this is a special case of the general principle that Python does NOT get into the thorny business of hosting constant subexpressions (requiring it to prove that something IS constant...), so, when you're looking at a major bottleneck, you have to consider doing such hoisting yourself manually. Name lookup for anything but local bare names IS "a subexpression", so if you KNOW it's a constant subex. in some case where every cycle matter, you can hoist it. (Or, you can use psyco, which among many other things can do the hoisting on your behalf...: [alex at lancelot bo]$ timeit.py -c -s'x=range(999)' -s'import psyco; psyco.full()' 'for i in range(999): x[i]=id(x[i])' 10000 loops, best of 3: 43 usec per loop [alex at lancelot bo]$ timeit.py -c -s'x=range(999); lid=id' -s'import psyco; psyco.full()' 'for i in range(999): x[i]=lid(x[i])' 10000 loops, best of 3: 43 usec per loop as you can see, with psyco, this manual hoisting gives no further benefit -- so you can use whatever construct you find clearer and not worry about performance effects, just enjoying the order-of- magnitude speedup that psyco achieves in this case either way:-). Alex From jfranz at neurokode.com Tue Nov 25 20:24:13 2003 From: jfranz at neurokode.com (Jon Franz) Date: Tue, 25 Nov 2003 20:24:13 -0500 Subject: Database connect / PDO References: <3FC248D1.3090603@ghaering.de> <030d01c3b2d9$4220a970$7401a8c0@voidmk9> <3FC3323A.3050209@egenix.com> <046d01c3b37e$f74fd000$7401a8c0@voidmk9> <3FC3BACB.9090705@egenix.com> Message-ID: <04ca01c3b3bc$00f7a8c0$7401a8c0@voidmk9> > Can you present a use case ? display_size is predefined statically in > ODBC: > > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odappdpr_28.asp > > I can't think of any use case for internal size... Variable length character (or binary) fields... I've written many a piece of code over the years that has had to create dynamic edit forms for a database. Variable length character fields are common place, and I've always found that enforcing the limit at edit time, rather than letting an error be raised or data be silently truncated, is a good practice. > Good catch :-) I'll fix that. It was true for mxODBC 1.x. No worries. > > If this is why the documentation says nearly, then your interpretation > > of what 100% would mean is different from mine. 100% compliant > > would, in my mind, be supporting all required interfaces. I wouldn't > > think optional interfaces are needed for compliance, and supporting > > them, although good, wouldn't come into the percentage... unless you > > wanted to say you were 105% compliant :) .Just my two cents. > > Hmm, I am the editor of the DB API 2.0 spec... > > A database package can be 100% compliant without implementing > all optional features. The DB API spec was designed to allow > this since otherwise some modules would never be able to > call themselves compatible. That's exactly what I thought, and as my statement said, I was only trying to figure out why 'nearly' was used, and then argue against the use if all of the required features were already present. A typo/slip-up makes much more sense anyway. :) cheers. ~Jon Franz NeuroKode Labs, LLC From news.collectivize at scandaroon.com Tue Nov 4 16:58:46 2003 From: news.collectivize at scandaroon.com (John Baxter) Date: Tue, 04 Nov 2003 13:58:46 -0800 Subject: round off References: Message-ID: In article , "W. Vanweersch" wrote: > Hello, > > The following looks strange to me in Python: > 7/-3 gives -3 > > It looks like Python rounds off -2.33333 to -3! is this correct?? > Isn't it -2? If you like, but not here. (It's really truncation, not rounding.) It can be unexpected. It keeps this sort of thing working: >>> (-7 / 3)* 3 + (-7 % 3) -7 Truncate / toward - infinity. If it truncated toward zero, then you have to mess with the sign of the result of %, and other odd things happen. --John -- Email to above address discarded by provider's server. Don't bother sending. From steve at ninereeds.fsnet.co.uk Sun Nov 2 03:43:28 2003 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sun, 02 Nov 2003 08:43:28 +0000 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> Message-ID: On Sat, 01 Nov 2003 18:55:18 GMT, GrayGeek wrote: >Weather (3D fluid dynamics) is chaotic both here on Earth and on Jupiter. >As Dr. Lorenz established when he tried to model Earth's weather, prediction >of future events based on past behavior (deterministic modeling) is not >possible with chaotic events. Current weather models predicting global or >regional temperatures 50 years from now obtain those results by careful >choices of initial conditions and assumptions. In a chaotic system >changing the inputs by even a small fractional amount causes wild swings in >the output, but for deterministic models fractional changes on the input >produce predictable outputs. Very true for predicting weather, but the 50 years hence models are predicting climate. That is a different layer of abstraction, and not necessarily chaotic (at least on the same timescales) as shown by the fact that the real world climate only changes relatively slowly - despite some quite random inputs such as sunspot activity which have nothing to do with chaos in the climate model. Whether these models are actually accurate (or rather which, if any) is, of course, a whole other question. I guess we'll find out in 50 years time ;-) >>> So "objectively" science gains more knowledge, but >>> relatively speaking (seeing it as a percentage of that what is >>> currently known to be not known, but knowable in principle) science is >>> loosing ground fast. Also an even greater area of the universe is >>> supposed to exist that we will not even have a chance *ever* to know >>> anything about. > >Exactly. Even worse, the various peripherals of Physics and Math are >getting so esoteric that scholars in those areas are losing their ability >to communicate to each other. It is almost like casting chicken entrails. There are just too many too abstract fields to be studied, I guess - at some point, we'll need more specialists than the entire human population! Better start working on them AI systems ;-) -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From anton at vredegoor.doge.nl Sat Nov 8 09:13:00 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 08 Nov 2003 15:13:00 +0100 Subject: reduce()--what is it good for? References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> Message-ID: anton at vredegoor.doge.nl (Anton Vredegoor) wrote: > def factorial(x): > b = _Memo.biggest > if x > b: return reduce(mymul, xrange(b+1,x+1), b) > return _Memo.facdict[x] Sorry, this part should be: def factorial(x): b = _Memo.biggest if x > b: start = _Memo.facdict[b] return reduce(mymul, xrange(b+1,x+1), start) return _Memo.facdict[x] From johnny.geling_removethis_ at chello.be Sat Nov 15 17:47:03 2003 From: johnny.geling_removethis_ at chello.be (Johnny Geling) Date: Sat, 15 Nov 2003 23:47:03 +0100 Subject: wxGrid (wxPYTHON) rowlabels References: <3fb408bf$0$9417$ba620e4c@reader3.news.skynet.be> Message-ID: Brian wrote: > Johnny Geling wrote in message news: >> I looked at the example but the rowlabels are not changed. The stay 1, 2, >> 3,etc. > > Take a look at GridDragable.py, in your wxPython demo directory. It > is called from the main demo, and it demonstrates custom rowlabels, > among other things. I downloaded the demo tar file but no file as you indicated above. Where can I find it? Johnny From bignose-hates-spam at and-benfinney-does-too.id.au Wed Nov 5 22:51:59 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 6 Nov 2003 14:41:59 +1050 Subject: Why does changing 1 list affect the other? References: <8ufjqvc24b7o1v0c32p2cpv7us32gtsdic@4ax.com> Message-ID: On Thu, 06 Nov 2003 16:36:08 +1300, oom wrote: >>>> firstlist=['item1','item2','item2'] Creates a list object, containing three string objects, and binds the name 'firstlist' to the list object. >>>> secondlist=firstlist Binds the name 'secondlist' to the same list object. >>>> print (firstlist,secondlist) > (['item1', 'item2', 'item2'], ['item1', 'item2', 'item2']) Outputs the same list object twice, since it is bound to both 'firstlist' and 'secondlist'. >>>> firstlist[0]='strangeness' Alters the list object. >>>> print (firstlist,secondlist) > (['strangeness', 'item2', 'item2'], ['strangeness', 'item2', 'item2']) Outputs the same list object twice, since it is bound to both 'firstlist' and 'secondlist'. > why does altering one list affect the other list ? it is driving me > insane! Because there's only one list, with two different names. This is a result of 'secondlist = firstlist'. What you probably want os to take a *copy* of the list object, and bind 'secondlist' to that new object. This occurs automatically for some types (e.g. scalars) but not lists or dicts or other structured types. >>> import copy >>> firstlist = [ 'item1', 'item2', 'item3' ] >>> secondlist = copy.copy( firstlist ) >>> print( firstlist, secondlist ) (['item1', 'item2', 'item3'], ['item1', 'item2', 'item3']) >>> firstlist[0] = 'no_strangeness' >>> print( firstlist, secondlist ) (['no_strangeness', 'item2', 'item3'], ['item1', 'item2', 'item3']) >>> -- \ "It is hard to believe that a man is telling the truth when you | `\ know that you would lie if you were in his place." -- Henry L. | _o__) Mencken | Ben Finney From james.kew at btinternet.com Mon Nov 3 17:51:42 2003 From: james.kew at btinternet.com (James Kew) Date: Mon, 3 Nov 2003 22:51:42 -0000 Subject: ActivePython or Python2.2.3+win32? References: <9i0bqvs4ir5963iiiv5bpukejvirga6gm1@4ax.com> <87ekwq74y0.fsf@pobox.com> Message-ID: "John J. Lee" wrote in message news:87ekwq74y0.fsf at pobox.com... > JZ writes: > > > Who can explain me what is the advantage of ActivePython over (1) > > standard Python 2.3.2 instalation (from www.python.org) > > plus (2) the latest win32? (I am using win32 box, of course). > [...] > > Convenience (win32all as standard, package system for modules not part > of the base ActivePython distribution) ActivePython 2.3.2 seems to have quietly dropped any mention of the PPM package system. Is it no longer supported? The single install and the integrated documentation -- one single searchable .chm -- are the advantages for me. James From FBatista at uniFON.com.ar Fri Nov 7 10:13:19 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 7 Nov 2003 12:13:19 -0300 Subject: How to read lines only at the end of file? Message-ID: Alex Martelli wrote: #- Yes: f.readlines() does read all of the file. #- #- You can use f.seek to position yourself at some distance #- from the _end_ (in bytes, though) and .readlines() from there -- #- but if the last N lines are abnormally long you're still not #- guaranteed to be able to give the last N lines without reading #- all of the file, worst case. Maybe the best solution is, from the end of the file (with f.seek()), start counting the end-of-lines backwards. When you reach the n-th end-of-line, from there to the end of the file you have what you want. Of course, it'll best to read chunk of 512 bytes or something. Or, you can go and study the code of "tail" (open sources gives you freedom, :) . Facundo From aleax at aleax.it Fri Nov 7 12:21:54 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 07 Nov 2003 17:21:54 GMT Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> Message-ID: Georgy Pruss wrote: > seq=[1,3,4,7] > map( int.__sub__, seq[1:], seq[:-1] ) # nearly twice faster than > ....zip.... for long arrays If this is a race, then let's measure things properly and consider a few more alternatives, shall we...? [alex at lancelot xine-lib-1-rc2]$ python a.py reduce: 100 loops, best of 3: 13.8 msec per loop zip: 100 loops, best of 3: 18 msec per loop izip: 100 loops, best of 3: 7.6 msec per loop w2: 100 loops, best of 3: 7.1 msec per loop wib: 100 loops, best of 3: 12.7 msec per loop loop: 100 loops, best of 3: 8.9 msec per loop map: 100 loops, best of 3: 7.6 msec per loop itertools.w2 is an experimental addition to itertools which I doubt I'll be allowed to put in (gaining less than 10% wrt the more general izip is hardly worth a new itertool, sigh). But, apart from that, map and izip are head to head, and the plain good old Python-coded loop is next best...! reduce is slowest. My code...: if __name__ != '__main__': def difs_reduce(seq): differences = [] def neighborDifference(left, right, accum=differences.append): accum(right - left) return right reduce(neighborDifference, seq) return differences def difs_zip(seq): return [ b-a for a, b in zip(seq,seq[1:]) ] import itertools def difs_izip(seq): return [ b-a for a, b in itertools.izip(seq,seq[1:]) ] def difs_w2(seq, wib=itertools.w2): return [ b-a for a, b in wib(seq) ] def window_by_two(iterable): it = iter(iterable) last = it.next() for elem in it: yield last, elem last = elem def difs_wib(seq, wib=window_by_two): return [ b-a for a, b in wib(seq) ] def difs_loop(seq): differences = [] it = iter(seq) a = it.next() for b in it: differences.append(b-a) a = b return differences def difs_map(seq): return map(int.__sub__, seq[1:], seq[:-1]) if __name__ == '__main__': import timeit bargs = ['-c', '-simport a', '-sx=range(9999)'] funs = 'reduce zip izip w2 wib loop map'.split() for fun in funs: args = bargs + ['a.difs_%s(x)' % fun] print '%8s:' % fun, timeit.main(args) Alex From fluxent at yahoo.com Thu Nov 13 12:12:32 2003 From: fluxent at yahoo.com (Bill Seitz) Date: Thu, 13 Nov 2003 09:12:32 -0800 (PST) Subject: NYC fulltime/perm Zope/Python job Message-ID: <20031113171232.18538.qmail@web14107.mail.yahoo.com> I'm running the tech for a startup in NYC. My intention is to grow a team. For the moment I plan to hire just 1 fulltime dev, outsourcing sysadmin-type stuff for now; the team will grow later. http://webseitz.fluxent.com/wiki/LivingIndependently If you are already living in the NYC area and have experience with Zope, Python, and SQL, please contact me immediately. thx Bill Seitz fluxent at yahoo.com __________________________________ Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard http://antispam.yahoo.com/whatsnewfree From pf_moore at yahoo.co.uk Sat Nov 29 05:54:49 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Sat, 29 Nov 2003 10:54:49 +0000 Subject: Graph algorithms - DFS, generators callbacks, and optimisation Message-ID: I'm trying to check a graph (represented in the usual Python adjacency list format) for loops. This is dead simple - you use a depth-first search, and look out for "back edges" (edges from a vertex "back" to one you've already seen). I already have a DFS algorithm which generates each edge in turn. It's great for what it does, but it ignores back edges. def DFS(graph, start, seen = None): if not seen: seen = {start: 1} for v in graph[start]: if v not in seen: seen[v] = 1 yield start, v if v in graph: for e in DFS(graph, v, seen): yield e I could code a variation on this, just for this one problem, but that sort of cut and paste coding offends me (and DFS is *just* fiddly enough that I'm not confident of getting it right each time I reimplement it). So what I'd rather do is enhance my existing code to be a bit more general. I have a C++ reference which implements a highly general DFS algorithm, using the visitor pattern (pass a visitor object to the function, and various callback methods are called at points in the algorithm - there are discover_vertex, discover_edge, back_edge, etc callbacks). I could code something like this (the pseudocode for the algorithm is almost executable in Python!) but it doesn't feel particularly "pythonic". Having to write a visitor class for each use case feels unwieldy (as well as being perceptibly slower than the generator implementation). Having the various callbacks as arguments (pass a callable or None) isn't much faster or cleaner. Can anybody think of a good way of making the DFS code above a little more generic, without losing the efficient and simple (from the caller's POV) approach of the current version? Paul. -- This signature intentionally left blank From des.small at bristol.ac.uk Wed Nov 26 12:06:53 2003 From: des.small at bristol.ac.uk (Des Small) Date: Wed, 26 Nov 2003 17:06:53 GMT Subject: invert dictionary with list &c Message-ID: Lately I have found myself using a pattern to make new dictionaries quite often, by which I mean twice: def invert(d): nd = {} [nd.setdefault(val, []).append(key) for k, v in d] return nd def count(l): d = {} [d.setdefault(w, 0) += 1 for w in l] return d Is this the pythonic way to do such things? Ideally I'd like to write them as one liners, but I can't see how. Des -- "[T]he structural trend in linguistics which took root with the International Congresses of the twenties and early thirties [...] had close and effective connections with phenomenology in its Husserlian and Hegelian versions." -- Roman Jakobson From aleax at aleax.it Thu Nov 13 12:38:54 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Nov 2003 17:38:54 GMT Subject: a python book hint References: Message-ID: Nick Vargish wrote: > Alex Martelli is too modest about his own book, so let me tout it > here... Heh, first time I've ever been accused of _THAT_ defect -- modesty! I appreciate the kudos, and I _have_ heard from several people who actually taught themselves Python with the "Nutshell", but my opinion is that those people are _pretty smart_ ones (as well, probably, as experienced). Beginners were _not_ the target audience for "Python in a Nutshell". Of course, sufficiently smart people can and do teach themselves subjects from reference books (particularly books that are reasonably clear and well-structured), even subjects more arcane than Python, which, after all, IS a language designed to be simple to learn. However, I suspect they're a minority. Fortunately is IS quite easy to check: e.g. you can visit safari.oreily.com, subscribe, and read Python in a Nutshell (and/or many, MANY other books) online for 2 weeks; be sure to cancel the subscription within 14 days, though, unless you appreciate the Safari site enough to pay for it -- only the first 2 weeks are free! Still, 2 weeks should be plenty for you to determine if the Nutshell (or any other book you're considering) is in fact going to be helpful to you personally -- browsing in a store has the advantage of letting you check the physical layout &c, but most stores would complain if you kept browsing for 2 weeks!-) > The Python Cookbook (which Alex edited and contributed to) is still my > favorite Python book. It's chock-full of useful real-world > recipes. Many of them are quite mind-expanding, and demonstrate in > concrete ways how to get the most out of Python. Again, thanks. The Cookbook is on Safari, too, by the way -- so you don't need to purchase it "blindly" based on favourable reviews, either; you can check it out for yourself. Alex From costanza at web.de Mon Nov 3 08:47:37 2003 From: costanza at web.de (Pascal Costanza) Date: Mon, 03 Nov 2003 14:47:37 +0100 Subject: Python from Wise Guy's Viewpoint In-Reply-To: <3fa65759$1@news.unimelb.edu.au> References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> <3638acfd.0310232246.64fa09ed@posting.google.com> <65fn61-b61.ln1@ID-7776.user.dfncis.de> <0Izmb.25575$Fm2.12537@attbi_s04> <3fa630f6$1@news.unimelb.edu.au> <3fa65759$1@news.unimelb.edu.au> Message-ID: Fergus Henderson wrote: > Fergus Henderson writes: > > >>Anyway, regarding how to write this example in a statically typed >>language: you can do this in a quite straight-forward manner, >>by just keeping a separate table of employees. >>For example, here it is in Java. > > > And in case you didn't like the type declarations and downcast that you > need in Java, here it is in Mercury. Thanks for the variations on this theme. However, your abstraction is still leaking. > print("employed: " ++ (if !.Employees `contains` Joe ^^^^^^^^^^^^^^^^^^^^^^ > then "yes" else "no")), nl, > print("company: " ++ > !.Employees^det_elem(Joe)^company), nl, ^^^^^^^^^^^^^^^^^^^^^^^^^ > print("salary: "), > print(!.Employees^det_elem(Joe)^salary), nl, ^^^^^^^^^^^^^^^^^^^^^^^^^ Pascal From andy47 at halfcooked.com Mon Nov 10 07:57:13 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Mon, 10 Nov 2003 12:57:13 +0000 Subject: [OT] Editing Python code using VIM In-Reply-To: <3FABC170.5090203@bu.edu> References: <3FABC170.5090203@bu.edu> Message-ID: Shu-Hsien Sheu wrote: > Hi, > > SciTE, which is based on Scintilla is very nice. I settled down with it > after 3+months of trying around. I tried emacs and VI at first, but the > customization in emacs was confusing (to me) and some of vi's behavior > isn't what I used to (in Win32), and it lacks code foding. > > -shuhsien > [snip] Its nothing to do with the original post, but you *can* fold code in VIM; http://www.halfcooked.com/mt/archives/000485.html Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From http Thu Nov 20 22:32:23 2003 From: http (Paul Rubin) Date: 20 Nov 2003 19:32:23 -0800 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <7xad6sb7cd.fsf@ruckus.brouhaha.com> <87smkjw55g.fsf@pobox.com> <7xy8ubdl1f.fsf@ruckus.brouhaha.com> <87smkitutw.fsf@pobox.com> Message-ID: <7xn0aq8khk.fsf@ruckus.brouhaha.com> jjl at pobox.com (John J. Lee) writes: > > > Second, if you have to have the key around anyway (true for some > > > applications), it really doesn't matter how secure the algorithm is. > Arguably XOR comes appreciably lower down the PITA > scale, since the decryption algorithm is trivial: it may, for example, > be implemented with an editor macro. You're talking about using rotor in a protocol where the key is included with the ciphertext. In that case, you can decrypt without even bothering to write an editor macro--you can just use the existing rotor module. > In fact though, I'm really *not interested* in whether this argument > is correct -- the mere fact that it's a valid way of thinking > suggested to me that it was odd to deprecate the module, after > (presumably) having put it in for this very purpose (obfuscation) in > the first place. To my mind deprecating it is a way of recognizing that it was a mistake to include it in the first place. Maybe in some farfetched situation (Hollywood special effect movie) it makes sense to put an explosive self-destruct charge into a car. That doesn't make it anything other than insane to include a self-destruct charge in every car that rolls off an assembly line, triggered by a button on the dashboard that you might press while trying to adjust the CD player. Rotor should never have been shipped with Python. If some application programmer actually has a sensible use for it (I doubt this), then the programmer should download the module from somewhere and ship it with that specific app. > However, if you're right in suspecting that anti-crypto legistlation > is always (or even usually) applied without exception or waiver even > to broken algorithms, then I agree it's pointless -- after all, AES > would serve just the same purpose! I'm going to have to catch up with the python-dev traffic about the legislation issue but I think it's silly to leave crypto out of the library because some regime somewhere doesn't permit its use. Apache 2.0 now ships with SSL by default, and I don't think its popularity or useability has been impaired. From h.b.furuseth at usit.uio.no Mon Nov 10 02:20:55 2003 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 10 Nov 2003 08:20:55 +0100 Subject: What does "#!/usr/bin/env python" do? References: <_eGrb.358699$9l5.109956@pd7tw2no> Message-ID: Parzival wrote: > I am a now immigrant to Linux from (the old country) > Can someone explain what the line: > > #!/usr/bin/env python > > at the start of a python script does? All my reading of > bash and env manpages would lead me to believe that > > #!python > > is equivalent to the first line, but not speaking well the > language am I, so here the question am I asking. At least on the operating systems I have checked, #! must be followed by the full pathname of a program. It does not search $PATH for it. '/usr/bin/env python' searches $PATH for python and runs it. (Usually env is used to set some environment variables for a program, e.g. 'env PYTHONPATH=whatever python', but one need not specify any environment variables.) Since env is (almost?) always in /usr/bin, while python can be installed God-knows-where, that is more portable than writing #!/local/bin/python or #!/usr/bin/python or whatever. -- Hallvard From aleax at aleax.it Thu Nov 13 12:43:04 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Nov 2003 17:43:04 GMT Subject: a python book hint References: Message-ID: Cameron Laird wrote: ... >>Hetland's "Practical Python" is a good book, particularly if you like ... >>Most other books are unfortunately a bit dated, but these two do cover ... > David's book is as current as any, but lacks the > GUI-for-Windows emphasis the original poster ap- > parently wishes. > > David Mertz, that is, not David Ascher. If this > were a voice posting it'd be obvious. True -- silly me; David Mertz's "Text Processing in Python" is indeed current (and also readable online). I don't think of it as suitable for beginners, but it IS actually possible to teach yourself Python from David's Appendix A, at least in theory (it _is_ a bit "short and impressionistic" for that, as its title suggests, but still...). Alex From __peter__ at web.de Sat Nov 1 14:49:56 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 01 Nov 2003 20:49:56 +0100 Subject: Shelve operations are very slow and create huge files References: Message-ID: Eric Wichterich wrote: > Hello Pythonistas, > > I use Python shelves to store results from MySQL-Queries (using Python > for web scripting). > One script searches the MySQL-database and stores the result, the next > script reads the shelve again and processes the result. But there is a > problem: if the second script is called too early, the error "(11, > 'Resource temporarily unavailable') " occurs. > So I took a closer look at the file that is generated by the shelf: The > result-list from MySQL-Query contains 14.600 rows with 7 columns. But, > the saved file is over 3 MB large and contains over 230.000 lines (!), > which seems way too much! Let's see: >>> 3*2**20/14600/7 30.780117416829746 >>> Are thirty bytes per field, including administrative data, that much? By the way, don't bother counting the lines in a file containing pickled data; the pickle protocol inserts a newline after each attribute, unless you specify the binary mode, e. g.: shelve.open(filename, binary=True) > Following statements are used: > dbase = shelve.open(filename) > if dbase.has_key(key): #overwrite objects stored with same key > del dbase[key] > dbase[key] = object > dbase.close() I've never used the shelve module so far, but the rule of least surprise would suggest that if dbase.has_key(key): del dbase[key] dbase[key] = data is the same as dbase[key] = data > Any ideas? Try to omit the shelve completely, preferably by moving the second script's operations into the first. If you want to keep two scripts, don't invoke them independently, make a little batch file or shell script instead. If you need an intermediate step with a preprocessed snapshot of the MySQL table, and you have sufficient rights, use a MySQL table for the temporary data. Peter From news at u-schramme.de Thu Nov 13 02:21:30 2003 From: news at u-schramme.de (Ulrich Schramme) Date: Thu, 13 Nov 2003 08:21:30 +0100 Subject: Palindrome In-Reply-To: <20031112223135.29045.00000109@mb-m12.aol.com> References: <20031112223135.29045.00000109@mb-m12.aol.com> Message-ID: Runic911 wrote: > Does anyone know how i can fix my Palindrome program? > > s = raw_input('Enter a String: ') > punctuation = '%$!*.,-:? ;()\'\"\\' > i = 0 > h = 0 > t = 0 > p = '' > z = 0 > while s!= ' ': > while i <= len(s) - 1: > punct = s[i] > if punctuation.find(punct) == -1: > p = p + punct > i = i + 1 > t = p.lower() > t[h] == t[len(t)-1-h] I?m not very experienced with Python but I think you could do it in a more simple way. inp = raw_input('Enter a string: ') pal = [] rev = [] for c in inp: if c.isalnum(): pal.append(c.upper()) rev.append(c.upper()) rev.reverse() if pal == rev: print '"' + inp + '" ' + 'is a palindrome.' else: print '"' + inp + '" ' + 'is no palindrome.' -- -- Ulli www.u-schramme.de From 3seasA at Tthreeseas.DOT.not Mon Nov 10 15:30:21 2003 From: 3seasA at Tthreeseas.DOT.not (3seas) Date: Mon, 10 Nov 2003 20:30:21 GMT Subject: Matrix - Metaphors, Analogies and the REAL References: <3FAFE026.7EF6F2F5@engcorp.com> <3FAFF339.E499F960@engcorp.com> Message-ID: Its in python code http://threeseas.net/vic/vic/ -- 3 S.E.A.S -- Virtual Interaction Configuration (VIC) Changing how we preceive and use computers email @ translate not to net, remove capitol letters, one . web @ http://threeseas.net From eppstein at ics.uci.edu Sun Nov 9 14:13:51 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 09 Nov 2003 11:13:51 -0800 Subject: More user feedback on Sets.py References: <1hSqb.1167$bQ3.696@nwrdny03.gnilink.net> Message-ID: In article , "Raymond Hettinger" wrote: > I have added some backwards compatability code so that Sets.py will run > Python 2.2. Please give it a test drive: > > http://cvs.sourceforge.net/viewcvs.py/*checkout*/python/python/dist/src/Lib/se > ts.py?content-type=text%2Fplain&rev=1.44.8.4 Thanks! Doesn't quite work out of the box, though... Python 2.2 (#1, 07/14/02, 23:25:09) [GCC Apple cpp-precomp 6.14] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sets Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/site-packages/sets.py", line 79, in ? class BaseSet(object): File "/usr/lib/python2.2/site-packages/sets.py", line 109, in BaseSet def _repr(self, sorted=False): NameError: name 'False' is not defined >>> Here's a patch: *** sets.py Sun Nov 9 09:48:47 2003 --- /usr/lib/python2.2/site-packages/sets.py Sun Nov 9 11:09:35 2003 *************** *** 74,79 **** --- 74,83 ---- if not predicate(x): yield x + if 'True' not in globals(): + globals()['True'] = not None + globals()['False'] = not True + __all__ = ['BaseSet', 'Set', 'ImmutableSet'] class BaseSet(object): -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From talon2lm at yahoo.com Thu Nov 20 23:06:18 2003 From: talon2lm at yahoo.com (Rob) Date: Thu, 20 Nov 2003 21:06:18 -0700 Subject: TKinter Destroy Question References: Message-ID: Thanks for the help! I got it so that it will withdraw the current window as i open a new one. That's exactly what i needed. I've got a pretty complicated window maze system going now that works perfectly. You guys led me right on track! Next Problem....I'm trying to have the user input a number (money) in a window and then use the number to process some information/file data. Is the .get() the best way to do this? Again, Ive just started tinkering (or is it Tkintering?...hehehe) with the GUI stuff so I hope my questions aren't too simplistic. I've only started to research this since I'm still trying to get all my menus looking right and located on the right windows for ease of use. It seems that I might have to go buy a book since online TKinter info is not real complete, at least for my level of understanding. Thanks Again! Rob From duane at franz.com Sun Nov 2 05:01:58 2003 From: duane at franz.com (Duane Rettig) Date: 02 Nov 2003 02:01:58 -0800 Subject: Paging Mr. Rettig [ws Re: Explanation of macros; Haskell macros] References: <87brs2tjut.fsf@memetrics.com> Message-ID: <4wuaj84x5.fsf@franz.com> Kenny Tilton writes: > Peter Seibel wrote: > > Joachim Durchholz writes: > > > > >>Peter Seibel wrote: > >> > >> > >>>Joachim Durchholz writes: > >>and I not just suspect but know that macros have some very serious > >>disadvantages (such as bad debugger interaction, a potential for > >>really ugly hairballs, and a constant temptation for stopgap > >>solutions that "work well enough"). > > Well, of those the debugger interaction is perhaps the most serious. > > > Yet in practice (Hey Pascal, I almost said "in 99% of cases"!) it > > doesn't seem to be that much of a problem. Maybe that's because we've > > just learned to deal with the pain; maybe MACROEXPAND is all you > > really need to get your bearings. At any rate, there's no in principle > > that a Lisp implementation couldn't keep track of macro information > > along with the compiled code just the way most compiler keep track of > > line number information in order to show you the code as written in > > the debugger. (And if it was really slick to let you step through the > > macro expansion, etc.) > > Cue Duane of Franz. He mentioned over lunch at ILC2003 where John > McCarthy used my laptop for ten minutes that their Allegro Common Lisp > product was going to exactly that, including the expansion thing. I > think he also said something about expanding in steps, but I did not > quite follow. I suppose it is like stepping into a function or not, > except the question here is whether nested macros get expanded (and > you then get to step through those). Well, yes, but not for another release or so - I've got to get environments access working right first (where do you think all of this info and capability will be coming from? :-) It is indeed true that macros tend to be opaque, and experience with the best of C/C++ debuggers and those of other lanuages with macro systems will simply reinforce this fact. However, Common Lisp macros tend not to be opaque (it is one of the more useful parts of the fact that CL macros work on the same data that programs work on), and one can see what a macro doing by simply macroexpanding it - for example, try (pprint (macroexpand '(dotimes (i 10) (print i)))) in a CL listener. With this much openness, it doesn't seem unreasonable to expect a debugger to be able to use such information to make macros and the forms they expand into completely debuggable and steppable at any desired level. -- Duane Rettig duane at franz.com Franz Inc. http://www.franz.com/ 555 12th St., Suite 1450 http://www.555citycenter.com/ Oakland, Ca. 94607 Phone: (510) 452-2000; Fax: (510) 452-0182 From ville.spammehardvainio at spamtut.fi Thu Nov 27 05:05:49 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 27 Nov 2003 12:05:49 +0200 Subject: [OT] Re: Choosing the right framework References: <3F15E124.A737D1E4@engcorp.com> Message-ID: David McNab writes: > I've changed my posted email address to something I consider far more > appropriate. I don't think riaa has a user 'plenty_of_messages'... Why not try something like webmaster at riaa.org or sales at sco.com? -- Ville Vainio http://www.students.tut.fi/~vainio24 From anton at vredegoor.doge.nl Tue Nov 18 13:03:12 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 18 Nov 2003 19:03:12 +0100 Subject: Can this be written more concisely in a functional style References: <92c59a2c.0311171648.6360213d@posting.google.com> <92c59a2c.0311172340.544faac6@posting.google.com> <698f09f8.0311180259.bdd4359@posting.google.com> <2259b0e2.0311180714.4f605bab@posting.google.com> Message-ID: mis6 at pitt.edu (Michele Simionato) wrote: >def any(p, seq): > """Returns true if any element in seq satisfies predicate p.""" > for elt in itertools.ifilter(p, seq): > return True > return False > >def all(p, seq): > """Returns true if all elements in seq satisfy predicate p.""" > for elt in itertools.ifilterfalse(p, seq): > return False > return True > >Since the "else" is unnecessary, it disturbs me, I get confused, >I don't see why it is used (there is no break in the loop) and the >code becomes much harder to read, for me. OTOH I am sure 99% of >people would say "look, it is obvious, if elt is in the output >of ifilter it will return True, else False (viceversa in the >second case)". But may brain sees that the "else" is unncessary >and immediately it is disturbed by th redundance. >Am I the only one? ;) Well, don't the multiple returns disturb you? I'd suggest this but probably it's too clever: from itertools import islice,ifilter def any(predicate,seq): return bool(list(islice(ifilter(predicate,seq),1))) def test(): xs = 'abc123def456' def fun(x): print x return x == '3' print any(fun,xs) if __name__=='__main__': test() Anton From martin at v.loewis.de Mon Nov 24 17:42:59 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 24 Nov 2003 23:42:59 +0100 Subject: minidom nodes without a document? References: <8b5e42a6.0311231738.6376d486@posting.google.com> Message-ID: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) writes: > (1) hard-code a document into > the parser (meaning, basically, that each parser instance can only be > used once) I would do this, and provide a reset() operation. > I guess the latter is the way to go, but it does seem awkward that it > should be necessary. You don't *have* to do that - you could also create stand-alone node, providing __init__ parameters as necessary. In that case, you would bind yourself to a specific DOM implementation, though - and we do reserve the right to change the constructor parameters across releases (in fact, we did that in the past). Regards, Martin From fumanchu at amor.org Mon Nov 24 14:31:11 2003 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 24 Nov 2003 11:31:11 -0800 Subject: Database connectivity Message-ID: Others have made good points and pointers. Just wanted to make sure you knew that you should be able to use ADO for MSSQL connections, as well. The only serious change to your code will be using "NText" instead of "Memo" types. Subclass your existing connectors and off you go, probably within a day's coding or less. Then you can hunker down and consider the cross-platform stuff. Robert Brewer MIS Amor Ministries > -----Original Message----- > From: SectorUnknown [mailto:secun at yahoo.com] > Sent: Monday, November 24, 2003 9:16 AM > To: python-list at python.org > Subject: Database connectivity > > > I've written a database (Access mdb) front-end using > Python/wxpython/and > ADO. However, the scope of the project has changed and I need > to access > the same data on an MSSQL server. Also, the front-end needs > to be cross- > platform (Windows and Linux). > > Does anyone have any suggestions on what database > connectivity I should > use? I've looked at mxODBC and wxODBC briefly, but am not > sure what is > the best way to go. > > BTW, although I would love to move away from the MSSQL server, that's > not going to change. > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Sun Nov 9 21:29:35 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 9 Nov 2003 21:29:35 -0500 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: Message-ID: <7N6dnUz1P9CKZTOiRVn-hQ@comcast.com> "Edward K. Ream" wrote [lots of stuff about the benefits of Leo over several posts] > Edward K. Ream email: edreamleo at charter.net In response to this series, I sent you a friendly note saying a) I am considering Leo as a base for a future project and b) I think there is a problem with a couple of lines in the code you posted. In response, you sent me the ---------- You recently sent a message to me at the email address edreamleo at charter.net. To help cope with the ever increasing volume of junk e-mail, I am using ChoiceMail, a permission-based e-mail filtering tool. Your original e-mail is being held by ChoiceMail until you complete the following simple one-time process. Please click on the link [Click here to request approval] When your browser opens, fill in your name and a short reason for wanting to send e-mail to me. If your reason is acceptable, your first email and all subsequent e-mails from you will be delivered to me normally. ------------ I will not beg you to read my bug report. Such a request is *NOT* a legitimate 'anti-junk-mail' measure. Being unable to communicate directly with you makes Leo less inviting to me. If I were to adopt Leo for a project anyway, I would warn users to not email the above address. Terry J. Reedy From jtanis at charter.net Wed Nov 26 03:27:28 2003 From: jtanis at charter.net (James Tanis) Date: Wed, 26 Nov 2003 03:27:28 -0500 Subject: Newbi q: show prog In-Reply-To: <3FC46120.67B7B461@hotmail.com> References: <3FC46120.67B7B461@hotmail.com> Message-ID: <1069835248.25589.8.camel@localhost.localdomain> Not positive, but I don't believe cmd is provided in windows 98. So he'd need to use command.com. On Wed, 2003-11-26 at 03:15, Alan Kennedy wrote: > [Christoffer T] > > I have tried to write "python file.py" in run, but it just very fast > > open and close dos window. So what should I do to get to show the > > program. > > Open a command prompt window in which to execute your script. This can > be done in multiple ways: perhaps the easiest is to type "cmd.exe" > into the "run" prompt. > > When the command prompt window appears, change into the directory > containing your python source, using the "cd" command. > > C:\>cd mypythondir > > And then execute your source as you tried before. > > In order for the command prompt window to find the python interpreter, > you may need to set the environment variable PATH to point at your > python installation. For example > > C:\mypythondir>set PATH=C:\python23;%PATH% > > As a quick check that this is working, just type "python" at the > command prompt: this should bring up the interactive interpreter. Exit > this interpreter by typing ctrl-Z and pressing the return key. > > C:\mypythondir>python > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> ^Z > > Your python script should now run just fine: > > C:\mypythondir>python file.py > > > but-hey--its-windows-98--anything-could-happen-ly y'rs, > > -- > alan kennedy > ----------------------------------------------------- > check http headers here: http://xhaus.com/headers > email alan: http://xhaus.com/mailto/alan -- James Tanis jtanis at charter.net From mikit at zoran.co.il Wed Nov 5 02:34:38 2003 From: mikit at zoran.co.il (Miki Tebeka) Date: 4 Nov 2003 23:34:38 -0800 Subject: Testing & stdout References: <6250403b.0311040151.32fd4754@posting.google.com> <3FA7A9B1.D09ED381@engcorp.com> <3FA7C976.7AF9749D@engcorp.com> Message-ID: <6250403b.0311042334.7cf5a8ce@posting.google.com> Hello John, > > Ah, reading John's reply I think I figured out what you meant. > > You mean some of the code being called is using a saved reference > > to sys.stdout, and so it won't dynamically pick your changed version > > of that name. Yes. Sorry I wasn't clear the 1'st time. > > I encountered the same problem once, and found no solution. :-( > Good point. If he's using unittest, it's a problem in only one case: > where the cached reference is at the module level. Otherwise, > each unit test starts fresh. To eliminate this problem you can always find the problematic module and do a "reload" at the TestCase "setUp" function. However this requiers you to track down all offending modules, which is error prone. > If it's at the module level, then the unit test suite has to do something > different. I'd fix the offending module, but possibly he isn't using > XP, so he can't do that. XP as in eXtreme Programming? What's the connection? Miki From ferrell at diablotech.com Tue Nov 18 19:38:15 2003 From: ferrell at diablotech.com (Robert Ferrell) Date: 18 Nov 2003 16:38:15 -0800 Subject: Package organization Message-ID: <73b00f0c.0311181638.49a5997d@posting.google.com> I have a question about how to organize modules in a package. I think there is something fundamental that I am missing. Say I'm creating a package, GreatPackage, which has three sub-packages, myUtilities, GoodStuff, MoreGoodStuff. The directories look like: GreatPackage | |-- myUtilities | |-- GoodStuff | |-- MoreGoodStuff What is the right way for modules in GoodStuff and MoreGoodStuff to refer to modules etc... in myUtilities? I'd like to set PYTHONPATH to just point to the directory containing GreatPackage. But, if put something like: from GreatPackage.myUtilities import aUtilityThingy in a module in GoodStuff, then the whole package gets loaded, including MoreGoodStuff. That's okay except when I'm developing and MoreGoodStuff is broken. What are guidelines for developing/deploying packages which contain pacakges? thanks, -robert From joconnor at cybermesa.com Wed Nov 12 13:36:24 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Wed, 12 Nov 2003 18:36:24 GMT Subject: STrange error importing win32gui Message-ID: <3fb27d5f.57321764@news.cybermesa.com> I'm using Python 2.3 on windows and trying to use the win32 libs. I keep getting the following error >>> import win32gui Traceback (most recent call last): File "", line 1, in -toplevel- import win32gui ImportError: DLL load failed: A device attached to the system is not functioning. I'm not sure what it means ot how to fix it. Any thoughts? From pythonguy at Hotpop.com Mon Nov 24 02:00:48 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 23 Nov 2003 23:00:48 -0800 Subject: file bug??? References: <3FBD8C08.9010002@hotmail.com> <84fc4588.0311210000.5b925947@posting.google.com> <84fc4588.0311210239.50284d19@posting.google.com> Message-ID: <84fc4588.0311232300.8846ca8@posting.google.com> I tend to be brief while posting to newsgroups. Most of the time, you get lambasted for verbosity here. Hence I tend to stick to stuff and trust pythonistas for their knowledge and intuition ;-) -Anand Andrew Bennetts wrote in message news:... > (please don't top-post) > > > > It does exist in Python 2.3, and it does take one argument (and optionally > > > others): > > > > > > http://python.org/doc/lib/os-file-dir.html#l2h-1473 > > > It does not exist in Python 2.2, AFAIK. > > It is a good idea to write code that at least works for > > one previous Python version, hence the comment. > > You should have said so in the first place -- explicit is better than > implicit :) > > -Andrew. From mis6 at pitt.edu Wed Nov 12 09:20:00 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 12 Nov 2003 06:20:00 -0800 Subject: True, False, None References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> Message-ID: <2259b0e2.0311120620.2ce4384b@posting.google.com> Alex Martelli wrote in message news:... > Michele Simionato wrote: > ... > > BTW, I would have been favorable to "Staticmethod", "Classmethod", > > "Super", etc. since they are all classes. But it is useless to protest now > > :-( > > Well, understanding is never useless. So could you please clarify why > you think of (e.g.) staticmethos as needing a different capitalization > from (e.g.) int? > > >>> type(staticmethod) > > > >>> type(int) > > > Why is staticmethod "a class" to you while int presumably isn't? Actually, I would prefer "Int" over ""int" ;) I am not sure I would like to impose the capitalization (the way Ruby does) but I would be happier with a strict standard code convention saying "classes are capitalized". Of course, I am not proposing to change anything. It is a very minor annoyance I can very well live with. > To me, personally, all of this debates only underscores yet again the > one serious "ergonomic" defect in Python's syntax -- case sensitivity. > > The desire to distinguish between uppercased "classes" and lowercased > "types" when they're becoming undistinguishable by design in the > language is (in my warped worldview) due to having case sensitivity > in the language at all. Ah well, I've basically lost that debate in > the past, already! I never understood why you advocate case insensitivity. I would expect case insensitivity to be a source of bugs: for instance, identifiers with similar names could be confused (es. myfunction vs. myFunction): one would expect them to be different (at least people coming from case insensitive languages) whereas they would be the same. Also, now I can write ONE=1 and def one(): return 1 and it is clear that the first name (ONE) refers to a constant whereas the second name (one) refers to something which is not a constant. In a case insensitive language I am sure I would risk to override constants with functions. When I learned C (coming from Basic and Pascal) I thought case sensitivity was a good idea, why you don't think so? (you are free to point me to old posts if this, as I suspect, has been debated to death already ;) Michele From __peter__ at web.de Mon Nov 10 07:41:42 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 Nov 2003 13:41:42 +0100 Subject: sharing dictionaries amongst class instances References: Message-ID: Kerry Neilson wrote: > class a: > x = 0 > y = 0 > : > > I suppose it's a c++ leftover thing, thinking i had to declare before I > init. I don't yet understand why it's different for a simple data type > than > it is for the list of dictionaries. But by taking the dict_entry{} and > my_dict[] out of the top of the class, it works without deepcopy. class A: x = 100 y = {} Here both assignments aren't declarations, but statements that are executed when the module containing them is imported. >>> A.x, A.y (100, {}) >>> So they are both stored in the class. Let's play a little: >>> a = A() >>> a.x 100 >>> a.x = 200 >>> a.x, A.x (200, 100) >>> You might suppose that a.x was initialized to A.x, but that's not the case: >>> del a.x >>> a.x 100 >>> See? The old value seems to reappear. When you say a.x and there is no instance attribute, Python looks up the class attribute with the same name. So you can use the class attribute as a kind of default value for the instance attribute. But beware, this technique bites you as soon as you try it with mutables: >>> a.y["key"] = "value" This looks the same, whether y is an instance or class attribute, and you would not complicate client code with some detection scheme. >>> A.y {'key': 'value'} >>> Oops, there was no y attribute in the instance, so we inadvertently changed y of the underlying class. By the way, for the same reason you must not use mutable values as default function arguments: def addwords(words, wordlist=[]): "Bad, don't do it" wordlist.extend(words.split()) return wordlist The default wordlist is growing every time you don't provide a second argument. The canonical Python solution is def addwords2(words, wordlist=None): if wordlist is None: wordlist = [] wordlist.extend(words.split()) return wordlist which creates a new wordlist when the second argument is omitted. Peter From peter at engcorp.com Tue Nov 18 12:59:01 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Nov 2003 12:59:01 -0500 Subject: Origin of the term "first-class object" References: <8ef9bea6.0311171335.356a7af6@posting.google.com> Message-ID: <3FBA5DE5.96E21C21@engcorp.com> Mel Wilson wrote: > > And a good thing, as you and I think. Names are > first-class in natural human languages, and look what > happens: > > "...The name of the song is called 'Haddocks' > Eyes'." > > "Oh, that's the name of the song, is it?" Alice > said, trying to feel interested. > > "No, you don't understand," the Knight said, > looking a little vexed. "That's what the name is > _called_. The name really is 'The Aged Aged Man'." > > "Then I ought to have said 'That's what the song is > called'?" Alice corrected herself. > > "No, you oughtn't! That's quite another thing! > The song is called 'Ways and Means': but that's only > what it's called, you know." > > "Well, what is the song then?" said Alice, who was > by this time completely bewildered. > > "I was coming to that," the Knight said. "The song > really is 'A-sitting on a Gate', and the tune's my > own invention." > > _Through the Looking Glass_, of course > Lewis Carroll Wow! That shows just how precise one can sometimes need to be, especially with things like "names" in Python (which we sometimes call variables, but which actually are just *bindings* ;-). -Peter From project5 at redrival.net Thu Nov 20 09:36:11 2003 From: project5 at redrival.net (Andrei) Date: Thu, 20 Nov 2003 15:36:11 +0100 Subject: best Wx editor References: <04875CB4331F0240A0AD66F9709786510113769D@paul> Message-ID: <1iaquxbd8rwur$.1fgoj9puc8neq$.dlg@40tude.net> Jason Tesser wrote on Thu, 20 Nov 2003 08:19:58 -0600: > What is the best overall ide studio that can be used to develop crossplatform apps (win,linux,mac) for python? If you want wxPython GUI painting and code development in one, Boa (http://boa-constructor.sf.net/) is probably the natural choice. Another choice would be Spe (http://spe.pycs.net), which is a wxPython editor which comes with wxGlade as plugin. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From FBatista at uniFON.com.ar Wed Nov 5 12:38:10 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 5 Nov 2003 14:38:10 -0300 Subject: penny distribution Message-ID: austin at smartobject.biz wrote: #- A similar but more general use-case arises when you have to #- distribute #- a product n ways. E.g., when we apply a tax rate r to a total bill q #- the total tax is r*q. But if we have to indicate what portion of r*q #- applies to each line item on the bill, then we require a similar sort #- of penny-distribution. Here is a function prototype: #- #- distribute_product(multiplier, *portions) #- #- This function would return a list of amounts, such that: #- #- distribute_product(m, a, b, c) ~= [m*a, m*b, m*c] _and_ #- sum(distribute_product(m, a, b, c)) = m*(a+b+c) #- #- I.e., the first equality is approximate but the second is #- strict. You #- could define Alex's divideBy method as: #- #- def divideBy(self, N): #- return distribute_product(self, *[1.0/N for i in range(N)]) #- But, also I can say that def distribute_product(multiplier, *portions): return [multiplier*portion for portion in divideBy(portions)] So, divideBy is the general case. The importance of this is that because of rounding, both approachs don't have the same results (I think)! So, which one is valid? . 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 ktilton at nyc.rr.com Sat Nov 1 23:40:55 2003 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Sun, 02 Nov 2003 04:40:55 GMT Subject: Paging Mr. Rettig [ws Re: Explanation of macros; Haskell macros] In-Reply-To: References: <87brs2tjut.fsf@memetrics.com> Message-ID: Peter Seibel wrote: > Joachim Durchholz writes: > > >>Peter Seibel wrote: >> >> >>>Joachim Durchholz writes: >>and I not just suspect but know that macros have some very serious >>disadvantages (such as bad debugger interaction, a potential for >>really ugly hairballs, and a constant temptation for stopgap >>solutions that "work well enough"). > > > Well, of those the debugger interaction is perhaps the most serious. > Yet in practice (Hey Pascal, I almost said "in 99% of cases"!) it > doesn't seem to be that much of a problem. Maybe that's because we've > just learned to deal with the pain; maybe MACROEXPAND is all you > really need to get your bearings. At any rate, there's no in principle > that a Lisp implementation couldn't keep track of macro information > along with the compiled code just the way most compiler keep track of > line number information in order to show you the code as written in > the debugger. (And if it was really slick to let you step through the > macro expansion, etc.) Cue Duane of Franz. He mentioned over lunch at ILC2003 where John McCarthy used my laptop for ten minutes that their Allegro Common Lisp product was going to exactly that, including the expansion thing. I think he also said something about expanding in steps, but I did not quite follow. I suppose it is like stepping into a function or not, except the question here is whether nested macros get expanded (and you then get to step through those). kenny -- http://tilton-technology.com Why Lisp? http://alu.cliki.net/RtL%20Highlight%20Film Your Project Here! http://alu.cliki.net/Industry%20Application From puccio_13**NOSPAM** at yahoo.it Sat Nov 15 14:25:40 2003 From: puccio_13**NOSPAM** at yahoo.it (Alessio Pace) Date: Sat, 15 Nov 2003 20:25:40 +0100 Subject: Python and SVG images Message-ID: Hi, I was wondering if there is some good library to manipulate and/or visualize SVG images with Python. Thanks Alessio Pace. From paul at boddie.net Mon Nov 24 06:20:59 2003 From: paul at boddie.net (Paul Boddie) Date: 24 Nov 2003 03:20:59 -0800 Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> <7xwu9svyny.fsf@ruckus.brouhaha.com> <7xvfpcowjt.fsf@ruckus.brouhaha.com> <653b7547.0311222346.b4d9e98@posting.google.com> <653b7547.0311231952.5abe71ab@posting.google.com> Message-ID: <23891c90.0311240320.6960d468@posting.google.com> pmaupin at speakeasy.net (Patrick Maupin) wrote in message news:<653b7547.0311231952.5abe71ab at posting.google.com>... > > My understanding is that clisp became GPL because Stallman claimed > that its use of readline forced the author to release it under the > GPL, and since the author was basically making free software anyway, > and more concerned about the software than the license, he > agreed to change the license fairly readily. Surely the Python community has been through this already with a definitive outcome. There's a readline module (whose use is optional) distributed with Python which uses an appropriate readline library present on the user's system when Python is installed. However, Python isn't distributed with the readline library itself because that would cause the resulting distribution to be available only under the GPL. I do seem to remember something about non-GPL readline equivalents which may come into play here, but I don't think that's relevant to how Python is distributed or installed today. It might also be interesting to look at the licensing of the Debian packages for Python, but then the dynamic linking aspects of GPL licensing may also be involved there, too. One wonders why the FSF doesn't have a "GPL licensing wizard" on their Web site. ;-) Paul From peter at engcorp.com Tue Nov 4 08:29:21 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 04 Nov 2003 08:29:21 -0500 Subject: Testing & stdout References: <6250403b.0311040151.32fd4754@posting.google.com> Message-ID: <3FA7A9B1.D09ED381@engcorp.com> Miki Tebeka wrote: > > In my test suite I also test some function that output messages to stdout. > Is there an easy way to temporary divert stdout to another location? > > Currently I'm using: [snip] > This works fine if no one is caching stdout somewhere. "Caching stdout"? What's that mean? Who would do such a thing? Normally issues like this would have an answer "use flush()", but with the example you gave, where you're diverting output directly to a StringIO, I can't see how that would help. I also can't see why it would be needed. If you have code which is actually holding back output which it will eventually write to stdout (is that what "caching stdout" means here?) then obviously diverting stdout to a StringIO is going to do nothing useful for you in your unit tests. I think you need to explain more or something... sorry. -Peter From jimmy at retzlaff.com Tue Nov 18 14:47:22 2003 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Tue, 18 Nov 2003 11:47:22 -0800 Subject: rotor alternative? Message-ID: Robin Becker wrote: > It seems that the rotor module is being deprecated in 2.3, but there > doesn't seem to be an obvious alternative. I'm using it just for > obfuscation. It seems we have ssl available in 2.3 for sockets, but > there seems no obvious way to use that from python code. > > Is an alternative to rotor planned? If the goal is simple obfuscation (and not encryption) then the base64 module might work: >>> import base64 >>> base64.encodestring('Can you read this?') 'Q2FuIHlvdSByZWFkIHRoaXM/\n' >>> base64.decodestring('Q2FuIHlvdSByZWFkIHRoaXM/\n') 'Can you read this?' Jimmy From aleax at aleax.it Mon Nov 3 09:34:16 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 03 Nov 2003 14:34:16 GMT Subject: running functions in parallel on multiple processors References: Message-ID: Michael Schmitt wrote: > What is the usual way for running functions in parallel on a > multiple-processor machine. Actually I want to run a single > computationally expensive function with different parameter sets. > Running the functions in different threads doesn't seem to work, because > of the global interpreter lock. > Would it help to fork processes, which run the single function with a > given parameter set? Is there any simple way, how this forked worker > process can report its result back to the controlling process? Forked processes could indeed perform whatever computations you need, and then report their results by writing them to a socket which the controlling process reads (there are many other IPC mechanisms, but sockets are often simplest where applicable). Alex From mis6 at pitt.edu Wed Nov 5 11:22:40 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 5 Nov 2003 08:22:40 -0800 Subject: New to Python - Compiled Language? References: Message-ID: <2259b0e2.0311050822.6c114cb9@posting.google.com> "Michael Geary" wrote in message news:... > Python compiles to bytecode, not to machine code. But that doesn't mean the > end user needs to install a Python interpreter. Actually it does; py2exe and similar programs ship the interpreter bundled with the code, so you don't install the interpreter directly, but indirectly you do. The disadvantage is that a ten line script requires megabites of space in order to be made executable. This may be an issue if you plan to distribute your program via the net and your customers have slow connection. Also, it may be an issue for embedded systems. Finally, it is somewhat disturbing that a ten line script cannot fit in good old 3.5' floppy :-( Michele From see_signature__ at hotmail.com Tue Nov 18 16:35:14 2003 From: see_signature__ at hotmail.com (Georgy Pruss) Date: Tue, 18 Nov 2003 21:35:14 GMT Subject: for what are for/while else clauses References: <1069091155.3fb909533f7c8@mcherm.com> Message-ID: "Fredrik Lundh" wrote in message news:mailman.835.1069171329.702.python-list at python.org... | <...> | Or maybe this quote from a popular python book might help: | | "Both the while and for statement may optionally have a trailing | else clause. The statement or statements after the else execute | when the loop terminates naturally (at the end of the for iterator | or when the while loop condition becomes false), but not when | the loop terminates prematurely (via break, return, or an exception). | | (the author seems to have rebooted since he wrote that, though.) | | The 'else' part of for/while is VERY useful and this is of course a big plus for Python. But the name 'else' is VERY misleading and useless and is probable even worse than 'static' in C++. That's exectly why every week somebody asks this question here again and again. I'm sure, even something like 'on_nornal_exit' would be much much better. -- Georgy Pruss E~mail: 'ZDAwMTEyMHQwMzMwQGhvdG1haWwuY29t\n'.decode('base64') From mhammond at skippinet.com.au Fri Nov 21 19:28:13 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 22 Nov 2003 11:28:13 +1100 Subject: COM makepy broken in ActivePython 2.3.2? In-Reply-To: <3fbe51ff.47726500@news.t-online.de> References: <3fbe51ff.47726500@news.t-online.de> Message-ID: Gerson Kurz wrote: > I have problems getting "COM makepy" working in ActivePython 2.3.2. > This is what happens when I start "COM makepy" from the Pythonwin > Menu: > > PythonWin 2.3.2 (#49, Nov 6 2003, 10:18:20) [MSC v.1200 32 bit > (Intel)] on win32. > Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) > - see 'Help/About PythonWin' for further copyright information. > >>>>Failed to execute command: > > from win32com.client import makepy;makepy.main() > Traceback (most recent call last): > File > "C:\Python23\Lib\site-packages\Pythonwin\pywin\framework\toolmenu.py", > line 103, in HandleToolCommand > exec "%s\n" % pyCmd > File "", line 1, in ? > File "C:\Python23\Lib\site-packages\win32com\client\__init__.py", > line 12, in ? > import dynamic, gencache, pythoncom > File "C:\Python23\Lib\site-packages\win32com\client\gencache.py", > line 623, in ? > __init__() > File "C:\Python23\Lib\site-packages\win32com\client\gencache.py", > line 52, in __init__ > Rebuild() > File "C:\Python23\Lib\site-packages\win32com\client\gencache.py", > line 610, in Rebuild > _SaveDicts() > File "C:\Python23\Lib\site-packages\win32com\client\gencache.py", > line 57, in _SaveDicts > raise RuntimeError, "Trying to write to a readonly gencache > ('%s')!" \ > RuntimeError: Trying to write to a readonly gencache > ('C:\TEMP\gen_py\2.3')! > --------------------------------------------------- > > OK, so I figure it wants to write to C:\TEMP\gen_py (why? IIRC this > used to be buried somewhere along the site-packages). I create the > directory & import a class. This is what happens: > > Generating to > C:\TEMP\gen_py\2.3\08EF934A-521D-4E29-A92F-0FDE92DDE9D6x0x1x0.py > Failed to execute command: > from win32com.client import makepy;makepy.main() > Traceback (most recent call last): > File > "C:\Python23\Lib\site-packages\Pythonwin\pywin\framework\toolmenu.py", > line 103, in HandleToolCommand > exec "%s\n" % pyCmd > File "", line 1, in ? > File "C:\Python23\Lib\site-packages\win32com\client\makepy.py", line > 362, in main > GenerateFromTypeLibSpec(arg, f, verboseLevel = verboseLevel, > bForDemand = bForDemand, bBuildHidden = hiddenSpec) > File "C:\Python23\Lib\site-packages\win32com\client\makepy.py", line > 273, in GenerateFromTypeLibSpec > gencache.AddModuleToCache(info.clsid, info.lcid, info.major, > info.minor) > File "C:\Python23\Lib\site-packages\win32com\client\gencache.py", > line 514, in AddModuleToCache > mod = _GetModule(fname) > File "C:\Python23\Lib\site-packages\win32com\client\gencache.py", > line 590, in _GetModule > mod = __import__(mod_name) > File > "C:\TEMP\gen_py\2.3\08EF934A-521D-4E29-A92F-0FDE92DDE9D6x0x1x0.py", > line 12, in ? > from win32com.client import Dispatch > ImportError: cannot import name Dispatch > --------------------------------------------------- > > Now when I try this: > > import win32com.client > instance = win32com.client.Dispatch("...") > > it tells me that Dispatch is not found ???? I restart pythonwin & > python2.3.2 & win32all "out of the box" before and didn't have any of > these problems. So, is "COM makepy" broken in AP232? Try creating a "gen_py" directory under the installed win32com directory. The directory need only exist, not contain anything. This should make it start working. I'm not sure if the recent APy update fixed that... Mark. From http Sat Nov 1 18:16:26 2003 From: http (Paul Rubin) Date: 01 Nov 2003 15:16:26 -0800 Subject: Removing Unicode from Python? References: <3fa43b28$0$58698$e4fe514c@news.xs4all.nl> Message-ID: <7xbrrvptmd.fsf@ruckus.brouhaha.com> Irmen de Jong writes: > While I think I am reasonably aware of things like Unicode, > character encodings, and assorted related stuff, I still found that > article highly interesting. Thanks for the link! Actually I think the Wikipedia article on unicode is much better. http://www.wikipedia.org/wiki/unicode From martin at v.loewis.de Mon Nov 17 17:32:26 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 17 Nov 2003 23:32:26 +0100 Subject: PEP263 and execfile() References: Message-ID: Roman Suzi writes: > in one place (preferably at execfile() call)? You should call warnings.filterwarning. Regards, Martin From ryntatqwest.net Mon Nov 17 10:16:26 2003 From: ryntatqwest.net (R Baumann) Date: Mon, 17 Nov 2003 07:16:26 -0800 Subject: Help with Kinterbasdb SQL Error -206 Column unknown References: <7876a8ea.0311142227.175e6315@posting.google.com> Message-ID: <2s-dnRqVndjDeyWiRVn-vA@comcast.com> "David Rushby" wrote in message news:7876a8ea.0311142227.175e6315 at posting.google.com... > "R Baumann" wrote in message news:... > > I'm a newbie with Python, and trying to connect to the Interbase/Firebird > > 'EMPLOYEE.GDB' file to play with it. > [but] > > OperationalError: (-206, 'Unable to determine field precison from system > > tables: Dynamic SQL Error. SQL error code = -206. Column unknown. > > FIELD_SPEC.RDB$FIELD_PRECISION. At line 1, column 19.. ') > > Here: > http://sourceforge.net/forum/message.php?msg_id=2287846 Thanks David! Will look into updating to latest & greatest Firebird and working with the same versions/data etc., on both home and work computers. Might make all the difference in the world. :-) Ruben From a.schmolck at gmx.net Thu Nov 20 07:34:00 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 20 Nov 2003 12:34:00 +0000 Subject: beeping under linux References: Message-ID: Ben Finney writes: > On 19 Nov 2003 19:41:28 +0000, Alexander Schmolck wrote: > > This is only partly a python question, but what is the easiest way to > > get python to (reliably) beep under linux? By reliably I mean that > > ``print "\b"`` won't do because it depends on the terminal settings > > Assuming you mean 'print "\a"' (ASCII BEL) rather than 'print "\b"' > (ASCII BS), this is the most portable way to sound the terminal bell. Anything that works under a normal linux box will do. > Most responses have been talking about /dev/audio, which is unrelated to > the terminal bell and is not portable -- many systems, especially > headless ones, do not have any sound card. Yep -- and although mine does have a soundcard it has no speakers. > The correct way to do this is to send the ASCII BEL ("\a") character to > the terminal. If the terminal's bell has been disabled somehow, it's > not the job of your program to revert that decision. Well, I happen to see myself as the ultimate authority on what my program's job (especially when I'm the sole user) and I also fail to discern an obvious relationship between my user-preference for visible/audible bells when working with (i.e. in front of) a certain terminal and my desire to receive some notification when a long-running process finishes that doesn't force me to constantly monitor the monitor (because chances are I might be reading a paper). I could live with a solution that requires me to change comint's (viz Emacs's py-shell's) and kterm's beeping behavior before and after my program runs, but I have no idea to get either of them to beep audibly (kterms bell settings e.g. don't seem much of a help). The best reason I can see for trying to find a way to make '\a' work is that it would be desirable to have beeping behavior also for remotely running processes (so directly writing to /dev/* or some such wouldn't be ideal). 'as From tchur at optushome.com.au Fri Nov 21 20:43:42 2003 From: tchur at optushome.com.au (Tim Churches) Date: Sat, 22 Nov 2003 12:43:42 +1100 Subject: Use of GPLed Python extension modules Message-ID: <200311220143.hAM1hgl20050@mail010.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From martin at v.loewis.de Mon Nov 24 17:37:55 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 24 Nov 2003 23:37:55 +0100 Subject: Problems sending list/tuple to a C extension. References: Message-ID: seberino at spawar.navy.mil (Christian Seberino) writes: > I think you misunderstood my question. My invocation of PyArg_ParseTuple > was flawless EXCEPT for checking return value. > > ALL I did was check return value and then code worked fine!!! > > *This* is what was exceedingly strange. When you say "It worked fine", you mean "It raises an exception", right? Because you did not, actually, pass a tuple to the call. If you had passed a tuple to the call, instead of passing an integer, it would have worked even without the check for an error return. It was only because you made an error *in Python* that the failure to check for errors in C made any difference. Or are you asking "Why do I need to check for errors in Python code if the Python code does have errors?" I couldn't quite imagine why you would ask this question: How else could Python possibly communicate the error to the Python code, except by returning an error???? Regards, Martin From aleax at aleax.it Fri Nov 14 10:24:59 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Nov 2003 15:24:59 GMT Subject: program surgery vs. type safety References: <9a6d7d9d.0311120822.553cd347@posting.google.com> <698f09f8.0311140417.567393b9@posting.google.com> Message-ID: Jeremy Fincher wrote: > Alex Martelli wrote in message > news:... >> Sure, >> "tests can only show the _presence_ of errors, not their >> _absence_". But so can static, compiler-enforced typing -- it >> can show the presence of some errors, but never the absence of >> others ("oops I meant a+b, not a-b"! and the like...). > > But it *does* show the absence of type errors, and almost any > invariant can be coded into the Hindley-Milner typesystem. Writing to How do most _typical_ invariants of application programs, such as "x > y", get coded e.g. in Haskell's HM typesystem? I don't think "almost any invariant" makes any real sense here. When I'm doing geometry I need to ensure that any side of a triangle is always less than the sum of the other two; when I'm computing a payroll I need to ensure that the amount of tax to pay does not exceed the gross on which it is to be paid; etc, etc. Simple inequalities of this sort _are_ "most invariants" in many programs. Others include "there exists at least one x in xs and at least one y in ys such that f(x,y) holds" and other such combinations of simple propositional logic with quantifiers. > a file opened for reading, multiplying matrices with improper > dimensions, etc. are both (among others) valid for encoding in the > typesystem. Too many dynamic typing advocates look at a typesystem > and see only a jail (or a padded room ;)) to restrict them. A good And (IMHO) too many static typing advocates have a hammer (a static typesystem) and look at the world as a collection of nails (the very restricted kinds of invariants they actually can have that system check at compile-time), conveniently ignoring (most likely in good faith) the vast collection of non-nails which happen to fill, by far, most of the real world. > static typesystem isn't a jail, but the raw material for building > compiler-enforced invariants into your code. Think DBC that the > compiler won't compile unless it can *prove* the contract is never > violated. What I want is actually a DBC which will let me state invariants I "know" should hold even when it's not able to check them *at run time*, NOT one that is the very contrary -- so restrictive that it won't let me even state things that would easily be checkable at run time, just because it can't check them at _compile_ time. If I state "function f when called with parameter x will terminate and return a result r such that pred(r,x) holds", it may well be that even the first part can't be proven or checked without solving the Halting Problem. I don't care, I'd like to STATE it explicitly anyway in certain cases, perhaps have some part of the compiler insert a comment about what it's not been able to prove (maybe it IS able to prove that _IF_ f terminates _THEN_ pred(r, x) holds, that's fine, it might be helpful to a maintainer to read the (very hypothetical) computer-generated comment about having proven that but not having been able to prove the antecedent. But I'm not going to be willing to pay very much for this kind of neat features -- either in terms of money (or equivalents thereof, such as time) or convenience and comfort. I would no doubt feel otherwise, if the kinds of applications I code and the environments in which I work were vastly different. But they aren't, haven't been for the > 1/4 century I've been programming, and aren't at all likely to change drastically any time soon. So, I see static typing as a theoretically-interesting field of no real applicability to my work. If I felt otherwise about it, I would most likely be coding in Haskell or some kind of ML, of course -- nobody's come and FORCED me to choose a dynamically-typed language, you know? > The main point, however, you made yourself: tests can only show the > *presence* of errors, whereas static typing can prove their absence. Static typing *cannot* "prove the absence of errors": it can prove the absence of "static typing errors", just like a compilation phase can prove the absence of "syntax errors", and the tests can equally well prove the absence of the EQUALLY SPECIFIC errors they're testing for. NONE of these techniques can "prove the absence of errors". CS theoreticians have been touting theorem-proving techniques that IN THEORY should be able to do so for the last, what, 40+ years? So far, the difference from theory and practice in practice has proven larger than the difference between practice and theory in theory. Incidentally, at least as much of this theoretical work has been done with such dynamic-typing languages as Scheme as with such static-typing languages as ML. Static typing doesn't seem to be particularly necessary for THAT purpose, either. >> In my >> experience, the errors that static type-checking reliably catches >> are a subset of those caught by systematic tests, particularly >> with test-driven design. > > But does the compiler write the tests for you? At the very least, one > could argue that static typing saves the programmer from having to > write a significant number of tests. One could, and one would be dead wrong. That is not just my own real-life experience -- check out Robert Martin's blog for much more of the same, for example. Good unit tests are not type tests: they are _functionality_ tests, and types get exercised as a side effect. (This might break down in a weakly-typed language, such as Forth or BCPL: I don't have enough practical experience using TDD with such weakly-typed -- as opposed to dynamically strongly-typed -- languages to know, and as I'm not particularly interested in switching over to any such language at the moment, that's pretty academic to me now). >> But systematic use of tests also >> catches quite a few other kinds of errors, so, it gives me MORE >> confidence than static type-checking would; and the "added >> value" of static type-checking _given_ that I'll have good >> batteries of tests anyway is too small for me to yearn to go >> back to statically checked languages. > > You make it seem like static typing and tests are mutually exclusive. No: the fact that the added value is too small does not mean it's zero, i.e., that it would necessarly be "irrational" to use both if the costs were so tiny as to be even smaller than the added value. Say that I'm typing in some mathematical formulas from one handbook and checking them on a second one; it's not necessarily _irrational_ to triple check on a third handbook just in case both of the first should happen to have the same error never noticed before -- it's just such a tiny added value that you have to be valuing your time pretty low, compared to the tiny probability of errors slipping by otherwise, to make this a rational strategy. There may be cases of extremely costly errors and/or extremely low-paid workforce in which it could be so (e.g., if the N-uple checking was fully automated and thus only cost dirt-cheap computer-time, NO human time at all, then, why not). In practice, I see test-driven design practiced much more widely by users of dynamically typed languages (Smalltalk, Python, Ruby, &c), maybe in part because of the psychological effect you mention...: > Obviously, they're not, though admittedly when I programmed in O'Caml > I felt far less *need* for tests because I saw far fewer bugs. ...but also, no doubt, because for most people using dynamically typed languages is so much faster and more productive, that TDD is a breeze. The scarcity of TDD in (e.g.) O'Caml then in turn produces: > Good thing, too -- the testing libraries available for O'Caml (like > most everything else for that language) are pretty nasty :) ...this kind of effect further discouraging sound testing practices. (There are exceptions -- for reasons that escape me, many Java shops appear to have decent testing practices, compared to C++ shops -- I don't know of any FP-based shop on which to compare, though). Alex From __peter__ at web.de Fri Nov 28 05:14:40 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Nov 2003 11:14:40 +0100 Subject: newb comment request References: <3fc55fbc_3@news.bluewin.ch> <3fc61708_3@news.bluewin.ch> Message-ID: Alexandre wrote: [Peter] >> Object oriented programming is about programming against interfaces, so >> exessive type checking is a strong hint to design errors. [Alexandre] > I'm not sure i understand... well, let's put it that way : i'm sure i > don't understand :) I guess i'll have to read about OO design... this is > my first program, although i think i understand what OO means, i'm not > abble to write OO yet :/ Type checking is generally best avoided, e. g. if you test for isinstance(mystream, file) this may fail on mystream objects that have all the methods needed to replace a file in subsequent code and you thus unnecessarily limit its usage. As your script is explicitly in the "type checking business", my remark was a bit off, though. >> Where is valuesD introduced? > Not sure i understand the question... i used this variable name "ValuesD" > (meaning Values from Data) not to conflict with the other variable named > "values" in the same function. I spotted an error where there was none - nothing to understand here :-( >> Module level code is habitually wrapped like so: >> >> if __name__ == "__main__": >> infile = open('cached-objects-Python-pickled-sample', 'rb') >> _data = pickle.load(infile) >> infile.close() >> # process _data... >> >> That way, you can import the module as well as use it as a standalone >> script. > > Oh ? but, i can use it as standalone script ?! > If i type myScriptName.py in my dos prompt the script is working ! Yes, but you can *only* use it as a standalone script. If you import it into another module, it will try to read the pickled data from the hard-coded file before you can do anything else. Peter From kdahlhaus at yahoo.com Tue Nov 18 10:46:14 2003 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 18 Nov 2003 07:46:14 -0800 Subject: OO design, Python, and GUIs References: <0bc1371b047abbb6ab299bf1c1f167ae@news.teranews.com> Message-ID: <283adf56.0311180746.275b9764@posting.google.com> > I'm creating a home-library management program with Python 2.2, PyGTK, and > Glade. While I've been many little programs before, this is my first large > application in Python. My question is how I should organise the OO design > of such a program. One solution is to use a layered architeture: .---------------. | Presentation | '------+--------' | .---------------. | Application | '------+--------' | .---------------. | Persistence | '---------------' Each layer would be a python package (or multiple packages if your app is large). The presentation layer contains your gui classes. The application layer contains classes that implement the behavior of the application. The persistence layer handles storage of your domain objects. Some people would add a 'domain layer' between the application and the persistence layer. I suppose that depends on the size of your project, but for something small it's overkill and your domain objects are very likely generated by an oo-rdb mapper tool anyway. People have differing opinions over whether or not your gui classes should directly make use of the domain classes. Technically, layers in this architecture should not know about layers other than the immediate one above or below. Java people like to create structures to pass data between layers. I think it's not a very good use of time and prefer to use the domain objects - the domain should be one thing not changing that much (a book's a book, right)? A decent discussion of this architecture is at: http://www.therationaledge.com/content/oct_01/t_layeringStrategies_pe.html The best thing to pull from this is to keep the gui stuff in its own package python package and put a little effort into keeping the gui out of your main application code. This will give you more options in the future - perhaps you'll find you'd like a web version of the library, or that FLTK is a sharper looking gui, or you'd like have a text reader read the list. From deets_noospaam at web.de Tue Nov 25 16:54:13 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Tue, 25 Nov 2003 22:54:13 +0100 Subject: Treestructure in SQL References: Message-ID: > Now I need either a SQL-statement compatible with SQLite or some code > snippet that will give me : > > Games > Games, Counter-strike > Games, Boardgames > Programming > Programming, Python > Programming, Python, Web > Programming, XML > > Any clues or hints?? Its not possible in a generic way. what would be possible is to create one for a certain number of levels: select lv0.Name, lv1.Name from category lv0, category lv1 where lv0.cat_id = lv1.parent_id You can extend this to every level you want. The reason is that for every parent-child relation, the database needs a cross-product between the two sets the relation is build upon. On the cross-product (which will contain _all_ possible relation, e.g (Games,Python), the filtering criteria is applied. I'm currently not sure what happens if you look for three levels, but look at a two-level branch. Maybe outer joins help you there, but I'd have to play around with that - and for that I'd have to setup a database right here :) Regards, Diez From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Nov 1 13:26:01 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 01 Nov 2003 19:26:01 +0100 Subject: simple echo server In-Reply-To: References: Message-ID: <3fa3fab9$0$58702$e4fe514c@news.xs4all.nl> Haris Bogdanovic wrote: > When client is trying to connect to the server everything works fine but > when server tries to echo what it receieved from client I get access > denied error. > Why is that happening ? Because the server has no access? No really-- you have to give much more detailed information. Preferrably the exact code fragment and exact error message that you're getting. --Irmen From __peter__ at web.de Tue Nov 4 19:09:49 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Nov 2003 01:09:49 +0100 Subject: XORing long strings opimization? References: <3ISpb.24447$BD3.4566933@juliett.dax.net> Message-ID: Francis Avila wrote: > "Noen" wrote in message > news:ieUpb.24457$BD3.4567875 at juliett.dax.net... >> nope, thought the Argument check would do it, but I used and opeartor >> instead of or. Well, here is XOR v.0.3b :P Any comments how to make it >> faster? > > How about using the struct module? > Caveat: I don't know if struct limits the repeat count. > > import struct > def XOR(data, key): > if len(data) != len(key): > raise ValueError, "data and key not of equal length" > ldata = struct.unpack('=%sb' % len(data), data) > lkey = struct.unpack('=%sb' % len(key), key) > lxored = [d^k for d,k in zip(ldata, lkey)] > xored = struct.pack('=%sb' % len(lxored), *lxored) > return xored > > Just an idea. > -- > Francis Avila Nope. Both your and my approach make it worse. Only Alex Martelli did it right: import itertools, array, struct def xor_noen(s1,s2): """ XOR string s1 with s2 """ output = "" for i in range(len(s1)): output += chr(ord(s1[i]) ^ ord(s2[i])) return output def xor_po(s1, s2): return "".join([chr(ord(c1) ^ ord(c2)) for c1, c2 in itertools.izip(s1, s2)]) def xor_am(s1, s2): x = array.array("b", s2) for i, v in enumerate(array.array("b", s1)): x[i] ^= v return x.tostring() def xor_fa(data, key): ldata = struct.unpack('=%sb' % len(data), data) lkey = struct.unpack('=%sb' % len(key), key) lxored = [d^k for d,k in zip(ldata, lkey)] xored = struct.pack('=%sb' % len(lxored), *lxored) return xored # 35 usec def pro_noen(): return xor_noen("sgnirts ni sreffid eziS", "Size differs in strings") # 40 usec def pro_po(): return xor_po("sgnirts ni sreffid eziS", "Size differs in strings") # 23 usec def pro_am(): return xor_am("sgnirts ni sreffid eziS", "Size differs in strings") # 46 usec def pro_fa(): return xor_fa("sgnirts ni sreffid eziS", "Size differs in strings") assert pro_po() == pro_am() == pro_fa() == pro_noen() I was surprised how good pro_noen() does, but that might change for large strings. By the way, results varied significantly (several usecs) in various test runs. Peter From pf_moore at yahoo.co.uk Sat Nov 1 10:55:43 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Sat, 01 Nov 2003 15:55:43 +0000 Subject: prePEP: Decimal data type References: Message-ID: <3cd884n4.fsf@yahoo.co.uk> "John Roth" writes: >> The idea is to have a Decimal data type, for every use where decimals are >> needed but floating point is too inexact. >> >> The Decimal data type should support the Python standard functions and >> operations and must comply the decimal arithmetic ANSI standard >> X3.274-1996. > > Why is ANSI 274 significant? The reason I ask this is that this is > a ***floating point*** standard, and I don't think that we particularly > care for decimal floating point. To be honest, I have little if any practical experience with numeric representation issues, but it seems sensible to me to implement a pre-existing, and presumably well thought out, standard, rather than inventing something ad-hoc. Of course, if the need is for something other than what ANSI 274 standardises, which seems to be what you are implying, then fair enough. But what do you require? Infinite-precision decimal arithmetic? If so, can you explain how you'd handle something like 1/3? (I'm not being deliberately awkward here - my impression is that representation issues are *hard*, and there are a lot of traps you can fall into by oversimplifying. That's why I prefer the idea of a pre-existing standard: it implies that *someone* has thought about the hard stuff). > Floating point presumes limited precision. In other words, if the actual > number (exclusive of the location of the decimal point) gets too large, > the least significant part is ... thrown away. I don't want that. > > Since we've got infinite precision integer arithmetic, going to > limited precision decimal arithmetic is, IMNSHO, a step backwards. Even infinite precision integers throw away information, in some sense. Witness: >>> 1L//3L 0L >> When passing floating point to the constructor, what should happen? >> >> j. ``Decimal(1.1) == Decimal('1.1')`` >> k. ``Decimal(1.1) == >> Decimal('110000000000000008881784197001252...e-51')`` > > Clearly, j is the correct answer. It's not all that hard to do, either. No way. Consider: >>> 1.1 1.1000000000000001 >>> 1.1==1.1000000000000001 True So what should Decimal(1.1000000000000001) evaluate to? It can't be Decimal('1.1'), as that contradicts your statement that j "clearly" applies. But it *also* can't be Decimal('1.1000000000000001'), as then we have the *same number* converting to two *different* Decimal values. As I say, it's hard. I'd probably support Decimal(float) giving an exception, on the basis that if you're doing this, you probably don't know what you're getting into :-) Having a special method, say Decimal.round_float(f, digits), is probably OK, though... Paul. -- This signature intentionally left blank From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Nov 6 15:37:55 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 06 Nov 2003 21:37:55 +0100 Subject: stop program In-Reply-To: References: Message-ID: <3faab121$0$58705$e4fe514c@news.xs4all.nl> Alberto Vera wrote: > Is it possible to stop a program like an executable using Python? Unix: take a look at os.kill other platforms: I have no idea. --Irmen From j557302 at yahoo.com.tw Sat Nov 15 07:42:26 2003 From: j557302 at yahoo.com.tw (=?big5?q?jeff?=) Date: Sat, 15 Nov 2003 20:42:26 +0800 (CST) Subject: win32com with basic authentication Message-ID: <20031115124226.90196.qmail@web16607.mail.tpe.yahoo.com> does anyone can help me with following situation. I use win32com.client to dispatch IE for a URL browing. However, the URL I am going require a HTTP basic authentication login. When IE starts to brow,the Login window pop up. I was trying to enter the right password for it, but IE wouldn't take it. it just keep poping up login window. How do I write auto login method to send user/password with COM method to bypass pop window for login. Or you might also help me how to dispatch for Netscape browser. How do I dispatch it with a opening brower? I know how to do it for IE, but don't know how to get Info for netscape. thanks for help. Jeff ----------------------------------------------------------------- ??? Yahoo!?? ?????????????????????? http://tw.promo.yahoo.com/mail_premium/stationery.html From mis6 at pitt.edu Sun Nov 16 09:10:04 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 16 Nov 2003 06:10:04 -0800 Subject: html renderer Message-ID: <2259b0e2.0311160610.1bc0a636@posting.google.com> I am looking for a textual html renderer (such as lynx) to be called from a Python program. The only needed functionality is the following: passing to it a string it should show the html file at the first match of the string (it does not seem obvious to do it with lynx, please correct me if I am wrong). Essentially, I want to be able to to browse rapidly over a bunch of html files. Fancy graphics is not important, easy of use is very important. Portable solutions are better, but a Linux only solution would be good enough. Any pointer? TIA, Michele From pclinch at internet-glue.co.uk Mon Nov 17 15:32:12 2003 From: pclinch at internet-glue.co.uk (Paul Clinch) Date: 17 Nov 2003 12:32:12 -0800 Subject: Books I'd like to see References: Message-ID: <8cf2994e.0311171232.2ae95a7a@posting.google.com> One more for your list:- Python Essential reference _Updated to Python 2.3_ by David Beazley Regards, Paul Clinch From j at submersion.com Tue Nov 11 15:31:46 2003 From: j at submersion.com (Jeff Davey) Date: Tue, 11 Nov 2003 20:31:46 GMT Subject: Python 2.3.2 & Netware References: Message-ID: Well, I've gotten a little bit further, Basically, in the pyconfig.h I changed #define WITH_PYMALLOC to #undef WITH_PYMALLOC. There was something about PyObject_Malloc that returns improper memory with Netware. The new abend I'm getting is a General Protection Fault :), tracking that one down right now. Will let you know when I figure it out. Jeff From rudy.schockaert at pandoraSTOPSPAM.be Thu Nov 6 13:30:04 2003 From: rudy.schockaert at pandoraSTOPSPAM.be (Rudy Schockaert) Date: Thu, 06 Nov 2003 18:30:04 GMT Subject: Strange problems with encoding In-Reply-To: References: <3faa53fe$0$40212$39cecf19@news.twtelecom.net> Message-ID: >>P.S. I really need some weeks off so I can read all the available >>documentation ;-) > > > it shouldn't take you more than 15-20 minutes to learn enough > about Unicode to be able to write Python code that processes > non-ASCII text in a reliable and portable way: > > short version: > http://effbot.org/zone/unicode-objects.htm > > long version: > http://www.joelonsoftware.com/articles/Unicode.html > > I wasn't referring to Unicode ;-) but to the existance of site.py . There still is so much I have to learn about python that I will need those weeks badly. I only got halfway in Alex' Python in a Nutshell (splendid book btw) which I already have since Europython :-( From mbabcock at fibrespeed.net Wed Nov 5 08:42:36 2003 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Wed, 05 Nov 2003 08:42:36 -0500 Subject: variable assignment within a loop In-Reply-To: <20031104144049.6880.qmail@svensson.org> References: <20031104144049.6880.qmail@svensson.org> Message-ID: <3FA8FE4C.5080403@fibrespeed.net> paul at svensson.org wrote: >take a deep breath, then repeat ten times: > >"I will test my examples before posting" > > /Paul > > $ python2 Python 2.3 (#1, Sep 15 2003, 12:45:41) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = "" >>> for x in "abc": ... a = x ... print a ... a b c >>> print a c -- Michael T. Babcock C.T.O., FibreSpeed Ltd. http://www.fibrespeed.net/~mbabcock From BoteDesSchattens at web.de Thu Nov 20 16:14:42 2003 From: BoteDesSchattens at web.de (Tobias Pfeiffer) Date: 20 Nov 2003 21:14:42 GMT Subject: Defining functions References: <20031120002109.28583.00000621@mb-m11.aol.com> <3FBCCD1A.C7216E7@engcorp.com> Message-ID: Hi! On 20 Nov 2003, Peter Hansen wrote: >> One more question, can python be applied to manipulate >> things in Windows? Like maybe restart my computer through python, >> or record keystrokes??? > > Planning to write some viruses? ;-) "Hi, I am a virus. For me to work properly, please install the Python interpreter found at www.python.org first" *lol* I think there's an O'Reilly book, "Win32 Programming with Python"; if it is possible, it is probably described there. Bye Tobias From r_olson at sandiego.edu Wed Nov 19 15:51:10 2003 From: r_olson at sandiego.edu (Rick Olson) Date: 19 Nov 2003 12:51:10 -0800 Subject: Trouble Importing Tkinter in embedded C program References: Message-ID: David Boddie wrote in message news:... > > Can someone guide me in the right direction to allow calls to Tkinter > > through the embedded python? I know there are ways of using Tk/Tcl > > through C, but I'm not familiar enough with Tk/Tcl to try that. > > If you are able to change the conditions under which the C program is > built (paths, libraries, etc.) then you may want to link against the > _tkinter.so library in the /usr/lib/python2.2/lib-dynload directory. > > That's just a guess, however. Maybe this is answered in an FAQ somewhere. Thanks for the suggestion. I tried to check the FAQ and newsgroup, but was unsuccessful. I may well have missed it. I'm not a serious programmer and am frequently unclear on exactly how to compile, link... Nevertheless, I tried linking _tkinter.so by changing the makefile a few different ways all of which amount to the makefile below. FWIW if I drop the definition of DLL this makefile will compile and run the examples in Extending and Embedding the Python Interpreter. Thanks again-- Rick CC = gcc PY = /usr/include/python2.2 PYLIB = /usr/lib/python2.2/config/libpython2.2.a PYINC = -I/usr/include/python2.2 -I/usr/include # Compiler flags OPT= -g CFLAGS= $(OPT) LIBS= -L/usr/lib \ -L/usr/X11R6/lib \ -ltk8.4 -ltcl8.4 -lnsl -lX11 -ldl -lreadline -lieee -lpthread -lutil LDFLAGS=-Xlinker -export-dynamic SYSLIBS=-lm DLLS= /usr/lib/python2.2/lib-dynload/-tkinter.so ALLLIBS=$(PYLIB) $(LIBS) $(SYSLIBS) testtk: testtk.o $(CC) $(LDFLAGS) testtk.o $(DLLS) $(ALLLIBS) $(OPT) -o testtk testtk.o: testtk.c $(CC) testtk.c -c $(OPT) $(PYINC) From http Thu Nov 27 15:40:07 2003 From: http (Paul Rubin) Date: 27 Nov 2003 12:40:07 -0800 Subject: Python bug report on SF, what now? References: <3fc660c2$0$1492$e4fe514c@news.xs4all.nl> Message-ID: <7xptfdtujc.fsf@ruckus.brouhaha.com> Irmen de Jong writes: > Should I have assigned it to somebody, or will > it be noticed 'automagically'...? Neither. One of the maintainers will assign it manually. From rtheiss at yahoo.com Thu Nov 6 14:38:10 2003 From: rtheiss at yahoo.com (rtheiss) Date: Thu, 06 Nov 2003 19:38:10 -0000 Subject: Available System Memory Message-ID: Hi Folks, This is hopefully an easy question. I would like to be able to check available system memory on a WinXP machine from within python. I've checked the docs in the win32 modules, read the Python Cookbook, and tried the Python Essential Reference. No luck. Any ideas? Many Thanks. Bob P.S. using v2.2 From aleax at aleax.it Fri Nov 14 05:08:54 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Nov 2003 10:08:54 GMT Subject: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <653b7547.0311121826.65b6b2d4@posting.google.com> Message-ID: Terry Reedy wrote: ... >> personally argued that reduce() should be removed from the language, >> but I do agree that it does not have to be part of "core" Python, >> and could easily be relegated to a module.) > > If the builtins are reduced in 3.0, as I generally would like, I would > be fine with moving apply, map, filter, and a repaired version of > reduce to a 'fun'ctional or hof module. But the argument of some > seems to be that this batteries-included language should specifically > exclude even that. A functional module would be neat. A great way to enhance the chance that there will be one would be starting one today (e.g. on sourceforge), ideally with both pure-Python and C-helped (or pyrex, etc) implementations, and get it reasonably-widely used, debugged, optimized. There's plenty of such ideas around, but gathering a group of people particularly keen and knowledgeable about functional programming and hashing out the "best" design for such a module would seem to be a productive endeavour. Also, I advocate that 3.0 should have a module or package (call it "legacy" for example) such that, if you started your program with some statement such as: from legacy import * compatibility with Python 2.4 or thereabouts would be repaired as much as feasible, to ease running legacy code, and to the expense of performance, 'neatness' and all such other great things if needed (e.g., no "repaired" versions or anything -- just compatibility). One reasonably popular counterproposal to that was to have it as from __past__ import * by analogy with today's "from __future__". I'd also like to make it easy to get this functionality with a commandline switch, like is the case today with -Q specifically for _division_ legacy issues. But mostly, each time I mention that on python-dev, I'm rebuffed with remarks about such issues being way premature today. Somebody's proposed starting a new list specifically about 3.0, to make sure remarks and suggestions for it made today are not lost about more day-to-day python-dev traffic, but I don't think anything's been done about that yet. Alex From igor at tyumbit.ru Wed Nov 12 02:55:12 2003 From: igor at tyumbit.ru (Igor Prischepoff) Date: Wed, 12 Nov 2003 12:55:12 +0500 Subject: python + MySQLDB distibution on Win .How? Message-ID: <909018477.20031112125512@tyumbit.ru> Hi, Is someone have an expierience in distributing python app with mysqldb module on Win platforms? I'd like to know, how you packaged and delivered your solution. Which tool to use, how to install ? In source or binary form? -- Igor. From buzzard at urubu.freeserve.co.uk Sat Nov 29 09:50:30 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 29 Nov 2003 14:50:30 -0000 Subject: GMPY compare warning References: <20031129001740.25982.00001230@mb-m05.aol.com> Message-ID: "Mensanator" wrote in message news:20031129001740.25982.00001230 at mb-m05.aol.com... > In the program that follows, I get the following warning message: > > collatz_.py:37: RuntimeWarning: tp_compare didn't return -1, 0 or 1 > while b>1: > > In this case, b is a gmpy.mpz number. The program operates as it should, > which I guess is why it's a warning. Is there some reason why I shouldn't > use gmpy numbers with relational operators? Is this warning something > that can safely be ignored? > http://sourceforge.net/tracker/index.php?func=detail&aid=472523&group_id=547 0&atid=305470 might help? Duncan From edreamleo at charter.net Sat Nov 8 16:49:58 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Sat, 8 Nov 2003 15:49:58 -0600 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: Message-ID: > Thanx so much for your thought-provoking, stimulating and clarifying ideas/comments. You are welcome. This is an exciting time for me. > Say, in a model building environment, first you dream about some fuzzy things... I'm glad you mentioned this. It's so important to be able to explore _easily_ while still being confused about what it is one is trying to do. On Leo's SF Forum I described how I ended up creating the script-find and script-change commands. I'll repeat it here, because it illustrates something crucial about executing Python scripts in Leo. [quote] As late as yesterday I wasn't sure how this would work, or if these new options were even necessary. Here is a summary of what I did yesterday. 1. As usual, just being able to begin this project was very important. It turned out that the ability to execute test scripts rapidly without leaving Leo was crucial. I was able to run through many ideas quickly so that no intellectual momentum got wasted. 2. I was quite confused about what was needed. After all, there are already a lot of find/change scripts in scripts/leoFindScript.py. But these scripts are not interactive. I wanted to see if I could write an interactive find script without using Leo's Find panel. If I could, I might simplify the entire process: no changes required to Leo's find/change code. I soon discovered, however, exactly why Leo's Find panel is necessary. The problem is that interactive scripts need a _nonmodal_ dialog always present so that the user can choose "yes", "no" or "cancel". However, interacting with that non-modal dialog would be quite a problem for the script. Rather than reinventing the wheel, it is _so_ much easier just to use the Find panel that already exists. And of course, it makes sense to do this. 3. So ok, we do, in fact, need Script Search and Script Change options in Leo's Find panel. The next big big question was: how to do this? Always present in my awareness was the fact the present find/change code is complex. A few experiments with hacking into this code made me leery of messing with this code. For one thing, the code is all Tk based. 4. I messed around with some more test scripts. Don't remember how it happened, but finally a huge Aha happened: the Find/Change scripts in the Find panel don't need any help at all from Leo! They can essentially do everything on their own! Here is how I entered this Aha in my diary: - Leo doesn't clear app.searchDict. However, a _script_ can a) init itself and b) bring up the find window (Eureka!) - The find script is responsible for traversing the tree. - The find script is responsible for highlighting the found text or otherwise indicating to the change script what the found text was. For example, the re find script can set app.searchDict["m"] to the match object. - The find script must communicate with the change script. Leo does nothing. - The change script must change the text, usually by using v.setBodyStringOrPane. BTW, the first Eureka seems almost irrelevant now, but somehow it was really important at the time. Anyway, you can see that these notes clearly indicate that Leo need not get intimately involved in "managing" the search/change scripts. This basic principle is the real Aha, and it made the rest of the work routine. 5. With this clear vision in mind, it became routine to add support for find/change scripts. What I did: a) Added support for new c.pattern_match_flag and c.pattern_search_flag ivars. There was a digression until a fixed a config bug that was blocking initing of these ivars. b) Changed the top-level find/change code so that it simply calls code to execute the scripts in the find/change text area if the corresponding ivars were set. That's all!! [end quote] The point is this: I did _not_ have a clear picture of how script-find and script-change would work when I started, and moreover what picture I had was confused and wrong. Yet somehow it was easy to noodle around until the creative unconscious created an initial Aha. After that, it was smooth sailing. > Biology and bioinformatics (among many other domains) might gain a lot using the Leo/Python great combo. I've thought so too. One thing I didn't mention in my "seven reasons" is that Leo's outlines are isomorphic to dags (directed acyclic graphs). Dags are much _more_ powerful than completely general graphs. Indeed, the transitive closure of a general graph is just the entire graph again, so Leo's clones would not be possible (would not be well-defined) in a general graph. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From zunbeltz at wm.lc.ehu.es.XXX Fri Nov 7 07:46:49 2003 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 07 Nov 2003 13:46:49 +0100 Subject: Inter-Process comunication Message-ID: Hi I'm writting a program to get data from a machine. I'm using wxPython to build the GUI. I've a mehtod in a class that get the data, something like this: data = [] def Measure(self): do somehting... while ... point = getdatapoint() data.aapend(point) do something... I want to plot the data in a "canvas", but i want to replot each time a point is added to data. I don't watn to insert the code to plotting inside the Measure (becose this code is GUI dependent). The code for plotting is in another function DrawPlOt() I want something like to send a signal each time the data is changed to execute DrawPlot(). I'm no proffesional programmer and i don't know wich technique is the best, signals, theread, anothero one ... Any sugestions? TIA Zunbeltz Izaola -- Remove XXX from email: zunbeltz at wm.lc.ehu.esXXX From martin at v.loewis.de Thu Nov 6 01:19:40 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 06 Nov 2003 07:19:40 +0100 Subject: Unicode and Zipfile problems References: <3fa8d5ee.304218@news.t-online.de> <3fa8fdaf.10480921@news.t-online.de> <3fa95db2.3932921@news.t-online.de> Message-ID: Peter Otten <__peter__ at web.de> writes: > I'm not aware if there has been a discussion before, but I think it would be > worth the overhead if every string were aware of its encoding, so that > together with the -*- comment in the script you'd never again have to > explicitly go through the decode/encode routine *and* could avoid those > funny filenames - or two-character umlauts that accidentally made it into > your ISO-8859-1 files. Bill Janssen first suggested that a before Unicode was introduced. I believe it won't help much, as, in many cases, Python can't know what encoding a byte string is, e.g. if you read from a file, or a socket. In some cases, you have binary data proper. Regards, Martin From dave-au_member at newsguy.com Tue Nov 11 20:44:36 2003 From: dave-au_member at newsguy.com (dave-au) Date: 11 Nov 2003 17:44:36 -0800 Subject: python 2.3.2 source code problem Message-ID: Hi: i downloaded python-2.3.2 souce code from python.org and it just keeps givning me error message: .... x Python-2.3.2/Mac/OSXResources/app/Resources/English.lproj/Documentation/ide/IDE.gif, 10249 bytes, 21 tape blocks tar: directory checksum error i tried other software (ftp.gnu.org) they were fine. does anyone here have the same problem? dave From dave at pythonapocrypha.com Tue Nov 11 13:59:38 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 11 Nov 2003 11:59:38 -0700 Subject: Python's simplicity philosophy References: <3fbqb.97878$e5.3584611@news1.tin.it><3FAB8399.687F2021@alcyone.com><1pQqb.432528$R32.14304849@news2.tin.it><3FAC19F0.284DCB03@alcyone.com> Message-ID: <012801c3a885$f55dfc80$891e140a@YODA> > >> > Part of the problem here is that just saying "only one way to do > >> > it" is a horrible misquote, and one that unfortunately misses IMO > >> > some of the most important parts of that "mantra": > > >> Well, perhaps anything like "only one way to do it" should be removed > >> from the mantra altogether, since people keep misquoting it in order > >> to support their position of removing beautiful features like reduce() > >> from the language. > > > You're joking, right? It is one of the key aspects of Python that makes the > > language such a good fit for me. Changing the philosophy because a *few* > > people don't "get it" or because they are apt to misquote it seems crazy. > > Of course I am not joking. I see no good coming from the mantra, when > the mantra should be instead what I said it should be: Nah, I don't really like your version. Also, the "only one way to do it" misquote has been singled out when it really should be considered in the context of the other items in that list - for whatever reason (maybe to contrast with Perl, I don't know) it's been given a lot of weight in c.l.py discussion threads. > "small, clean, simple, powerful, general, elegant" It's really a matter of taste - both "versions" mean about the same to me (and to me both mean "get rid of reduce()" ;-) ). > To me, there is never *one* obviously "right way" to do anything Never? I doubt this very much. When you want to add two numbers in a programming language, what's your first impulse? Most likely it is to write "a + b". The same is true of a lot of other, even much more complex, things. And IMO that's where this principle of an obvious way to do things comes into play, and it's tightly coupled with the principle of least surprise. In both cases they are of course just guiding principles or ideals to shoot for, so there will always be exceptions (not to mention the fact that what is obvious to one person isn't universal, in the same way that "common sense" is rarely common). Having said that though, part of the appeal of Python is that it hits the nail on the head surprisingly often: if you don't know (from prior experience) how to do something in Python, your first guess is very often correct. Correspondingly, when you read someone else's Python code that uses some feature you're not familiar with, odds are in your favor that you'll correctly guess what that feature actually does. And that is why I wouldn't be sad if reduce() were to disappear - I don't use reduce() and _anytime_ I see reduce() in someone's code I have to slow way down and sort of rehearse in my mind what it's supposed to do and see if I can successfully interpret its meaning (and, when nobody's looking, I might even replace it with a for-loop!). Of course that would be different if I had a history of using functional programming languages, which I don't. That's the line Guido walks: trying to find just the right combination of different-but-better and intuitive-for-most-people, and the aforementioned items from the Zen of Python are a way of expressing that. -Dave From invalid at faser.net Wed Nov 12 18:54:37 2003 From: invalid at faser.net (Faser) Date: Wed, 12 Nov 2003 23:54:37 GMT Subject: ZSI & Python newbie References: <3fb251d3.21252950@News.CIS.DFN.DE> Message-ID: <3fb2c34a.3907929@News.CIS.DFN.DE> On Wed, 12 Nov 2003 16:16:53 GMT, Alex Martelli wrote: >Are you using the Python time module, and the time tuples documented in >it? You surely don't seem to be: I used the time module too, but I always got some kind of errors. >> import datetime > ... >> nascita = datetime.date(1950,12,22) >> soapNascita = TC.gDate(nascita) > >Now, if you passed nascita.timetuple(), THAT might help -- at least >it could be said to place you in compliance with the doc you quote. > >However, from the traceback you quote it doesn't seem like that...: > > >> File "D:\MySoft\Python\codicefiscale\cf.py", line 16, in ? >> soapNascita = TC.gDate(nascita) >> File "C:\PROGRA~1\Python23\Lib\site-packages\ZSI\TC.py", line 65, in >> __init__ >> i = self.pname.find(':') >> AttributeError: 'datetime.date' object has no attribute 'find' > >Indeed it does, and neither does a timetuple. What this code in >TC.py is doing is trying to parse a string by finding a colon in it. >So, maybe, a string is what you need to pass...? That parameter IS >called 'name' in the docs you quote, after all -- even though to >think of a 'name' as something containing a colon seems strange to me. I tried to pass this: nascita = datetime.date(1950,12,22).timetuple()[:9] and the error change in: File "D:\MySoft\Python\codicefiscale\cf.py", line 24, in ? cf = codiceFiscale('Rossi','Marco','M','Milano','MI',nascita) File "D:\MySoft\Python\codicefiscale\cf.py", line 14, in codiceFiscale soapNascita = TC.gDate(nascita) File "C:\PROGRA~1\Python23\Lib\site-packages\ZSI\TC.py", line 59, in __init__ self.nspname, self.pname = pname ValueError: unpack tuple of wrong size I think I will give up. Thank you very much for your help. Faser -- FABIO SERRA *Questo testo deve essere valutato secondo il senso della RFC-3* Per rispondere in e-mail sostituire "invalid" con "faser" -------------------- From pushcold at hotpop.foo Wed Nov 19 17:42:52 2003 From: pushcold at hotpop.foo (Thomas) Date: Wed, 19 Nov 2003 23:42:52 +0100 Subject: Tkinter / Unicode and UTF-8 Message-ID: I was used to pass Unicode strings to Tk widgets. IIRC, Tcl/Tk expects UTF-8 encoded strings, but Tkinter took care of that. This worked, as long as I was using Python/Tk on Red Hat 9 Linux (and on earlier versions). Now I switched to Fedora Core 1 Linux (where Python/Tk does not work without fixing it - but I described that in another thread) and I have to pass UTF-8 encoded strings to Tk widgets (i.e. I cannot directly pass Unicode strings any more). Now I have some questions: - Was Tkinter changed to behave like that? - Will it stay like that in the future? - Isn't it strange, that you have to pass UTF-8 encoded strings to Tk widgets, but that the widgets will return Unicode strings? (My versions: Python 2.2.3, Tkinter 2.2.3, Tcl/Tk 8.3.5) Thanks in advance for any comments and hints; I have to change a lot of code if passing UTF-8 encoded strings to Tk widgets is now the only way to do it. And before doing that, I would really like to know what the 'correct' way is. -- mailto: pushcold at hotpop.foo (where: foo = com) From try_vanevery_at_mycompanyname at yahoo.com Fri Nov 14 21:20:56 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Fri, 14 Nov 2003 18:20:56 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <857b782c.0311141450.64916aea@posting.google.com> Message-ID: Christopher Mahan wrote: > > I think also that when people get paid per hour, the longer the > project, the more they make. > > Subconsiously I think, people don't necessarily want computer > languages that are written fast. > > Now, if you're a consultant and bill "for the job" then in fact it is > in your best interest to use a language that can be written quickly to > do a particular set of tasks. Or a business owner. I want more productivity because when I write my games, it's *my* money I'm losing. Also as a consultant I think better tools is a way to manage project risk. You've got so many other ways for a client to waste your time, to put you behind schedule, you'd like to have your tools not be an additional way for the project to blow up in your face. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA Brandon's Law (after Godwin's Law): "As a Usenet discussion grows longer, the probability of a person being called a troll approaches one RAPIDLY." From frr at easyjob.net Thu Nov 20 10:21:53 2003 From: frr at easyjob.net (Fernando Rodriguez) Date: Thu, 20 Nov 2003 16:21:53 +0100 Subject: trouble with regex with escaped metachars (URGENT please O:-) Message-ID: <3amprvo6n734ovhg5ekatp0539q738809t@4ax.com> Hi, I have a filewhose contents looks like this: Compression=bzip/9 OutputBaseFilename=$ OutputDir=$ LicenseFile=Z:\apps\easyjob\main\I18N\US\res\license.txt The tokens $<...> must be susbtituted by some user-provided string. The problem is that those user-provided strings might contain metacharacters, so I escape them. And that's where I get into trouble. Here's the code I'm using: def substitute(name, value, cts): """ Finds all the occs in cts of $ and replaces them with value """ pat = re.compile("\$<" + name + ">", re.IGNORECASE) return pat.sub(val, cts) # this line causes the error (see below) def escapeMetachars( s ): """ All metacharacters in the user provided substitution must be escaped """ meta = r'\.^$+*?{[|()' esc = '' for c in s: if c in meta: esc += '\\' + c else: esc += c return esc cts = """Compression=bzip/9 OutputBaseFilename=$ OutputDir=$ LicenseFile=Z:\apps\easyjob\main\I18N\US\res\license.txt""" name = 'OutputDir' value = "c:\\apps\\whatever\\" # contains the backslash metachar print substitute( escapeMetachars(name), value, cts) I get this error: Traceback (most recent call last): File "", line 1, in -toplevel- pat.sub(s,cts) File "C:\ARCHIV~1\python23\Lib\sre.py", line 257, in _subx template = _compile_repl(template, pattern) File "C:\ARCHIV~1\python23\Lib\sre.py", line 244, in _compile_repl raise error, v # invalid expression error: bogus escape (end of line) What on earth is this? O:-) PS: I can't use string.replace() for the susbtitution,because it must be case-insensitive: the user might enter OUTPUTDIR, and it should still work. From danb_83 at yahoo.com Thu Nov 27 06:10:45 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 27 Nov 2003 03:10:45 -0800 Subject: Simple instructions on how to programmatically download an image from a web page? References: Message-ID: jarrodhroberson at yahoo.com (Y2KYZFR1) wrote in message news:... > I have search the group and not found a working example on how to > simply download a .gif from a url. > > something as simple as > http://groups.google.com/images/threadview_logo.gif should be pretty > easy, guess not? > > I don't need to know about using a browser, I need to know how to do > it programmatically from Python. > > Anyone know how to get it done? Try the urllib.urlopen function. From google_mail at aristoweb.net Tue Nov 18 02:41:31 2003 From: google_mail at aristoweb.net (Corey Lubin) Date: 17 Nov 2003 23:41:31 -0800 Subject: Overriding variables used by base classes References: <8ef9bea6.0311150153.213d6de2@posting.google.com> Message-ID: [grr, had trouble posting via my own newsserver: "Done. Waiting for confirmation"] hungjunglu at yahoo.com (Hung Jung Lu) wrote in news:8ef9bea6.0311150153.213d6de2 at posting.google.com: > Use > > [tainted.py] > import original > original.someGlobal=2 > > class Tainted(original.Original): > pass > [/tainted.py] > > ------------------------- I discarded this idea very early on for a couple of reasons, one of which may not be very important and another which might not have been valid after all. First of all, I wanted my tainted module to completely mimic the interface of the original module. Importing in the style that you have would not do so, as all names other than "Tainted" would have to be prefixed by "original". I don't blame you for that, as my simplified example only mentioned the class "Original" and didn't make it clear that there may be other names in the original interface. Furthermore, in this particular case, there probably /aren't/ any other names that I would want to have carried over into my tainted module. My second reason for not following that path was that I had the impression that a particular module can only be imported once; any further imports of the same module would just be implemented by binding new names to the first copy of that module. When you import "original" in the code above, does "tainted" get it's own copy of the "original" module, or would other imports of the module be referring to the same thing? If the answer is the former, then my concerns over this approach were not valid. If the answer is the latter, then this approach isn't acceptable. To further expand upon my concerns raised in the last paragraph, I want to have the choice to use either or both of tainted.Tainted and original.Original; and when I use them I want them to have distinct behaviour. The way I understand things, the "original.someGlobal=2" line in your suggestion would forever scar the "original" module in the memory of the python interpreter instance running that code. Ok, the "forever" wasn't necessary, but I believe my point was made: we would no longer just be making changes to "tainted", but also to "original", which other user code may depend upon to act in it's original way. In actuality this may not be an issue and I may only need to use the modified version, but I tend to think in terms of principles rather than whether something happens to work out in a particular instance. Just incase there is any ambiguity over my intentions, I've provided code below: [user.py] import tainted t = tainted.Tainted() t.foo() # should behave in the altered/tainted way import original o = original.Original o.foo() # should behave in the original way tainted.someGlobal # should exist (not as important or hard to fix) tainted.original.someGlobal # as opposed to this; AND... tainted.someGlobal == original.someGlobal # should be false [/user.py] > (a) Python's namespace mechanism is hard to understand for newcomers. > It is a fact, no matter how hard people try to deny it: your question > has been asked a few hundred times before. But once you understand > that assignment in Python is name binding and is very different from > assignment in other languages like C/C++, you'll get used to it. Same > with import and from ... import ... statements. > > Namespace mechanism is the heart and soul of Python. When you have > more time, try to read more and understand it. Otherwise you'll run > into surprises in many places. When writing each line of Python code, > you need to keep in mind what namespaces you are dealing with: an > object's namespace? local dictionary? global dictionary? built-in? Thanks for understanding my perspective, rather than working around it or trying to change it. I'm taking your advice and have already [re]read the related sections in the official Python tutorial and the language reference. > (b) Stay with your present approach. There is still no need for exec. > Python is powerful enough to allow you to tweak many aspects of > existing modules/classes/functions/methods without needing to evaluate > code strings. What you are doing is called "patching". You are making > a patch for existing module/class. If the changes are like adding > attributes, surround a method with some around codes, those can be > done easily with inheritance. If you need to override a foreign class > method because you want to change the code in some spots inside the > method, and the foreign class is used by other foreign > classes/modules, you can write your code in your own module/class and > replace the foreign implementation. Look into the documentation for > the "new" module. In short, there are many ways to dynamically modify > Python modules/classes/functions/methods. You may or may not completely get my drift -- in that I'd like to preserve the behaviour of the original code -- but this is all, nonetheless, relevant and helpful. > (c) More generally, what you want to do falls into the arena of > Aspect-Oriented Programming. No need to understand it, now. But keep > it in mind. Will do. Thanks, Corey Lubin From crescent_au at yahoo.com Fri Nov 7 04:43:59 2003 From: crescent_au at yahoo.com (Ben) Date: 7 Nov 2003 01:43:59 -0800 Subject: web server - accept() method Message-ID: hi all, Just trying to figure out what the accept() method in socket.py does. Lets consider the following webserver code: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = 8881 ock.bind(('',port)) ... ... while 1: (newSock, addr) = sock.accept() ... ... Here accept() returns newSock and addr. In my case "addr" holds the value something like: ('127.0.0.1', 2571). What is 2571? This value keeps changing each time i make a connection to above webserver. What does this mean? And also what is "newSock"? It holds value such as: What do i mean by this? Thanks Ben From dave at pythonapocrypha.com Wed Nov 12 12:31:38 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 12 Nov 2003 10:31:38 -0700 Subject: Python's simplicity philosophy References: <2259b0e2.0311112248.3be2d304@posting.google.com><17lsb.109042$fl1.4548960@twister.southeast.rr.com> <20031112170100.GA32388@godzilla.fibrespeed.net> Message-ID: <04ac01c3a942$d4ba4a20$891e140a@YODA> > On Wed, Nov 12, 2003 at 08:28:29AM +0000, Robin Becker wrote: > > sequence.sum() > > sequence.reduce(operator.add[,init]) > > sequence.filter(func) etc etc > > > > That would make these frighteningly incomprehensible ;) > > concepts seem less like functional programming. Personally I wouldn't > > like that to happen. > > I'm hoping you were being sarcastic ... but I get the feeling you aren't. > > Why, pray-tell, would you want an OO program to do: > > results = [ func(x) for x in sequence ] > > ... instead of ... > > results = sequence.map(func) ?? Because I find the first much more readable (and IMO the "an OO program to do" bit is irrelevent from a practical point of view). Also, someone not familiar with either version is likely to correctly guess what the first one does. It's not an issue of whether or not a person can be taught what 'map' means). It's subjective, yes, but not _completely_ subjective because the "guessability" of the first form is higher because it uses other well-known keywords to do its thing. (FWIW I don't think map() is that big of a deal, but you asked... :) ). -Dave From bignose-hates-spam at and-benfinney-does-too.id.au Mon Nov 24 08:35:12 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 25 Nov 2003 00:25:12 +1050 Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> <7xwu9svyny.fsf@ruckus.brouhaha.com> <7xvfpcowjt.fsf@ruckus.brouhaha.com> <653b7547.0311222346.b4d9e98@posting.google.com> <653b7547.0311231952.5abe71ab@posting.google.com> <23891c90.0311240320.6960d468@posting.google.com> Message-ID: On 24 Nov 2003 03:20:59 -0800, Paul Boddie wrote: > One wonders why the FSF doesn't have a "GPL licensing wizard" on their > Web site. ;-) Almost: Amazing how many questions get continually asked and fallacies repeated, that are answered by the above two pages. -- \ "I bought some powdered water, but I don't know what to add." | `\ -- Steven Wright | _o__) | Ben Finney From aleax at aleax.it Wed Nov 12 11:16:53 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 12 Nov 2003 16:16:53 GMT Subject: ZSI & Python newbie References: <3fb251d3.21252950@News.CIS.DFN.DE> Message-ID: Faser wrote: > Sorry if this post is stupid, but I'm a python newbie. I would like to do > some experiments with webservices and I try to consume a web service that > return an italian fiscal code (a simple string). I have to send some > strings and a date (birth date). I'm using the ZSI module, but I don't > understand how I can convert a python date in a ZSI SOAP date. The > documentation doesn't help me much. > (http://pywebsvcs.sourceforge.net/zsi.html#SECTION007600000000000000000) The doc you quote says, and I quote its very first line: """ SOAP dates and times are Python time tuples in UTC (GMT), as documented in the Python time module. """ Are you using the Python time module, and the time tuples documented in it? You surely don't seem to be: > import datetime ... > nascita = datetime.date(1950,12,22) > soapNascita = TC.gDate(nascita) Now, if you passed nascita.timetuple(), THAT might help -- at least it could be said to place you in compliance with the doc you quote. However, from the traceback you quote it doesn't seem like that...: > File "D:\MySoft\Python\codicefiscale\cf.py", line 16, in ? > soapNascita = TC.gDate(nascita) > File "C:\PROGRA~1\Python23\Lib\site-packages\ZSI\TC.py", line 65, in > __init__ > i = self.pname.find(':') > AttributeError: 'datetime.date' object has no attribute 'find' Indeed it does, and neither does a timetuple. What this code in TC.py is doing is trying to parse a string by finding a colon in it. So, maybe, a string is what you need to pass...? That parameter IS called 'name' in the docs you quote, after all -- even though to think of a 'name' as something containing a colon seems strange to me. Somebody else who IS familiar with ZSI (I'm not) can no doubt help you more with the details; all I can say for sure is that you surely don't want to pass a datetime.date object, but what it IS that you DO want to pass is not clear to me. Alex From aleaxit at yahoo.com Fri Nov 7 18:56:46 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 07 Nov 2003 23:56:46 GMT Subject: binary string question References: Message-ID: <2jWqb.109920$e5.3983916@news1.tin.it> Ben Finney wrote: > On Fri, 07 Nov 2003 23:20:05 GMT, Alex Martelli wrote: >> Dan Jones wrote: >>> I'm trying to figure out how to get bit operators to work on a binary >>> string. >> >> You can access an individual byte simply by indexing the string > > It's possible the original poster is asking (ambiguously) about treating > a string consisting of '0' and '1' digits, as a binary number. oh, then: x = long(thestringof0sand1s, 2) might work, but to access individual bits, bytes, etc, you need masks and shifts. Alex From martin at v.loewis.de Wed Nov 5 14:36:33 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 05 Nov 2003 20:36:33 +0100 Subject: Unicode and Zipfile problems References: <3fa8d5ee.304218@news.t-online.de> <3fa8fdaf.10480921@news.t-online.de> Message-ID: gerson.kurz at t-online.de (Gerson Kurz) writes: > Here is my "dontcare"-codec, ugly on purpose: Of course, this codec does not work for your original problem: Just see try it on your original data, and then see how Winzip misinterprets the file names. zipfiles encode file names in code page 437. Regards, Martin From tom_verbeure at hotmail.com Mon Nov 17 12:10:32 2003 From: tom_verbeure at hotmail.com (Tom Verbeure) Date: 17 Nov 2003 09:10:32 -0800 Subject: Unit Testing Examples Message-ID: Hello All, so I'm now convinced that unit testing is really the way to go and I want to add it to an existing project. The first thing that I find out, is that, well, it's hard work. Harder than writing the real functional code. My application manipulates graphs. I first write the skeleton in Python, then convert it to C++ for high performance (some graphs can have millions of nodes.) Up to now, I simply evaluated the validity of a graph by eye-balling the results of toy problems. Obviously, this gets harder as the graphs grow, so unit testing sounds like a good way to make sure I catch mistakes early. I'm not sure, though, at what level I have to write unit tests. It's easy to write a tests that validates the consistency of a single node of a graph, but the real complexity is, of course, in the interaction of multiple nodes. What I'm looking for is some examples, existing open source projects that make heavy use of unit testing. I'd like to see a real life example about how those tests are structured and how the complexity of these tests expands from object level to system level. Thanks, Tom From scott_list at mischko.com Wed Nov 12 22:42:27 2003 From: scott_list at mischko.com (Scott Chapman) Date: Wed, 12 Nov 2003 19:42:27 -0800 Subject: True inconsistency in Python Message-ID: <200311121926.37395.scott_list@mischko.com> There seems to be an inconsistency here: Python 2.3.2 (#1, Oct 3 2003, 19:04:58) [GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2 >>> 1 == True True >>> 3 == True False >>> if 1: print "true" ... true >>> if 3: print "true" ... true >>> 0 == False True >>> -1 == False False >>> -1 == True False >>> if -1: print "true" ... true >>> if -2: print "true" ... true >>> if None: ... print "hello" ... >>> x = None >>> x == None True >>> x == True False >>> x == False False >>> x <> True True >>> x <> False True >>> None == True False >>> None == False False Historically Python has allowed <> 0 to equal true in evaluations. Now <> 0 still evaluates to true in evaluations. However it doesn't equal True. They are not interchangable. (Same with empty lists, etc.) Assuming the old behavior is desired, programmers need to be careful not to compare a variable with True as in: if var == True: # only works if var is 1 blah ' Must use: if var: # works if var is not 0 blah Is this inconsistency going to be resolved in the future? How? (Will <>0 == True or will <>0 <> true or will it be resolved some other way that I'm too opaque to see? :-) It seems that maybe Python should throw a warning (perhaps if a flag is set) any time it bumps into code comparing a variable to True or False. It's pretty subtle and would easily throw a newbie. Of course, according to the above logic, if 1 == true and 2 == true, then 1 == 2! Thankfully this doesn't work in Python. Python is magic. I love the magic but it creates some interesting inconsistencies. Scott From scott_list at mischko.com Fri Nov 7 23:39:49 2003 From: scott_list at mischko.com (Scott Chapman) Date: Fri, 7 Nov 2003 20:39:49 -0800 Subject: Can I hook a "file" to a python script? Message-ID: <200311072039.49034.scott_list@mischko.com> Hi! I'd like a "file" on the Linux box to actually be the input and output of a Python script. Anything written to the file would be sent to a database and anything read from the file would come from the database. I know how to do the database end of this but I'm not sure if a script can be hooked to a "file" transparently. The script would probably have to be run as a daemon. I doubt there's enough magic in the Linux world to make it so that a read/write would actually launch the script. That'd be Ok. Scott From bokr at oz.net Sat Nov 8 17:42:13 2003 From: bokr at oz.net (Bengt Richter) Date: 8 Nov 2003 22:42:13 GMT Subject: prePEP: Decimal data type References: Message-ID: On Thu, 6 Nov 2003 10:43:52 -0500, "Tim Peters" wrote: [...] > >It has to support some half dozen specific rounding modes already (the spec >requires them). The mandated modes have been reviewed by many people now >over several years, so it's tempting to call YAGNI on adding more rounding >complexity. My FixedPoint does support user-defined rounding modes; alas, >all evidence to date suggests I'm the only person to date able to define one >correctly understanding of every stinking detail of every stinking endcase -- it's not >easy the first time someone tries it>. > Following is an exact decimal/rational module hack that implements rounding when the .round() method is called. This is not too elegant, but it might make an interesting toy to cross-check results with. 30 years of monthly compound interest does generate a fair amount of digits, but it can handle it. And you can check the _exact_ difference from doing it floating point, and perhaps demonstrate when/how it's safe to use hardware floating point (the below has a software decimal floating point). About the 30 years interest, >>> from exactdec import ED >>> monthly5 = 1 + ED( '.05/12') >>> monthly5 ED('3.0125 / 3') >>> start = ED(1) >>> start ED('1') >>> fm5 = 1.0+ 0.05/12 >>> fm5 1.0041666666666667 >>> monthly5.round(20) ED('1.00416666666666666667') >>> fstart = 1.0 >>> for i in xrange(30*12): ... fstart *= fm5 ... start *= monthly5 ... >>> fstart 4.4677443140061053 >>> start.round(20) ED('4.46774431400613221243') >>> err = ED(fstart,'all')-start >>> err ED('-1.56304148231013236986795175352733832996669654337153733730960097118272041942305024046142360 963012057392399385808513132735004380045887019491590594848567543746099279247782492404211092305697 981942603081504204074464788922982296549717752974330439000221572233435214122399335151325954144618 900462032107403557206447160788112551619335537177864834308165003815651982743545600184830416792430 006198225629411824849523906416912497782230577924310271500267297956136382334806613723525165395284 535900838608901737436464025004714288622793588896506577479134017475377641227803205011713549091096 133145948633022116071771866555211557151726225215476514565787630190565855468620450845083504202642 689190693005234276689807253839309304532499468247786496752880094937190474830588626230621777889479 703217124659874396057456877927948952659639736522210676920364370104538827117231761130501253771264 878907949516858455102771211294274323473541556175745838790698849963815157512517119109683330894122 419465602517028421797269789171429961866520967620825108423637749408425943209381542284540329915368 857997235383065705584065571271008721284350021123549868449933295248144722514707438777251932770746 090987731235646452226688847245082616867972045549031014767048143096992525819923039646122088361644 579918406562388873940433411106385019399448321943189013300306911684700844253559215810364410055218 335449640228259572789992966032626222008918446886031635163380806543318900671084821575936160455692 493336358710092579196071811371493642452908504603585136777462572632798060122885204925037488881947 910781074947690321238995118414971674525304479175247251987457275390625e158 / 58029883553010642635 729412690188122648867574983421180398276039568933683892061549947054264296629049795373656629387735 93537918329060451697709838267789886857631025156060199201') >>> err.round(50) ED('-2.693511319701830367844690393524096646e-14') >>> err.round(49) ED('-2.69351131970183036784469039352409665e-14') >>> err.round(48) ED('-2.6935113197018303678446903935240966e-14') But there is a lot of digits in the exact result, and the percentage error of the floating point isn't so bad: >>> (err/start).round(30) ED('-6.028794690103059e-15') ====< exactdec.py >==================================================================== # exactdec.py -- exact decimal/rational class # 20031107 14:54:21 alpha -- bokr # 20031108 09:42:18 added contruction from float with all info or specified rounding -- bokr # 20031108 13:58:10 added more docs and interactive calculator thing -- bokr # # WARNING: Not signigicantly tested. Not optimized. No warranty. Use at your own risk. And, # if you run this program interactively, it passes your raw_input to eval unvalidated! # # The ED class preserves accuracy exactly by including a denominator for a kind of # hybrid rational. The info defining the value can be retrieved via ED.astuple # as a 3-tuple of (numerator, denominator, power_of_10) for the exact value # (numerator*10**power_of_10)/denominator. # # Currently, rounding is a separate operation that returns an exact result. Only rounding # away from zero on halves is implemented (and not very well tested ;-) # # Examples of valid string literals being passed to the constructor are: # ED('-12.34e-56/78') -- which by the way currently reprs as the exactly equivalent # normalized ED('-6.17e-56 / 39') # ED('.1') which reprs as ED('.1') # Converting the same floating point value preserving total or otherwise specified # accuracy get you: # ED(.1, 'all') => ED('1.000000000000000055511151231257827021181583404541015625e-1') # ED(.1, 24) => ED('1.00000000000000005551115e-1') # ED(.1, 23) => ED('1.0000000000000000555112e-1') # ED(.1, 22) => ED('1.000000000000000055511e-1') # ED(.1, 20) => ED('0.10000000000000000555') # ED(.1, 19) => ED('0.1000000000000000056') # ED(.1, 18) => ED('0.100000000000000006') # ED(.1, 17) => ED('0.10000000000000001') # ED(.1, 16) => ED('0.1') # # Integers and longs are accepted as accurate, and value will be preserved, though # representation may be normalized. # # ED(2L**55) => ED('36028797018963968') # ED(20L**55) => ED('3.6028797018963968e71') # ED(10L**55) => ED('1.0e55') # The inverse can be calculated accurately, and mutiplied out again: # 1 / ED(10L**55) => ED('1.0e-55') # 1 / ED(20L**55) => ED('2.77555756156289135105907917022705078125e-72') # (1 / ED(20L**55)) * ED(2**55) => ED('1.0e-55') # (1 / ED(20L**55)) * ED(2**55) * ED('1e55') => ED('1') # ############################################################################# # # The literal for an exact value is a string import re rxo = re.compile(r'\s*([+-]?\d*)(\.(\d*))?(e([+-]?\d+))?(\s*/\s*([+-]?\d+))?') # example # rxo.search('12.34e-45 / 678' ).groups()[::2] # ('12', '34', '-45', '678') def fracnorm(num,den): """make numerator carry sign and return equivalent num,den with no common divisor""" if num==0: return 0,1 elif den==0: raise ValueError,'zero fracnorm den!' if den<0: num=-num; den=-den n=abs(num); d=den if n.e / i1,i2,p10,den = rxo.search(v).groups()[::2] if den is None: den = 1 else: den = int(den) if p10 is None: p10=0 else: p10 = int(p10) if i2 is None: i2='' p10 -= len(i2) self.num = int(i1+i2) self.den = den self.p10 = p10 elif isinstance(v, float): if decimals is None or (not isinstance(decimals, int) and decimals!='all'): raise ValueError( "Specify decimals for least significant digit of 10**(-decimals)\n" "(decimals may also be specified as 'all' to capture all bits of float)") sign = v<0 if sign: v = -v acc = type(self)(0) p2=1; shift2=2**27 # usual double has 53 bits while v: i = int(v) # depend on accurate truncation and promotion to long acc = acc + type(self)((i,p2,0)) v = (v-i)*shift2 p2 *= shift2 if sign: acc.num = -acc.num self.num = acc.num self.den = acc.den self.p10 = acc.p10 elif isinstance(v, type(self)): self.num = v.num self.den = v.den self.p10 = v.p10 elif isinstance(v, tuple): self.num = v[0] self.den = v[1] self.p10 = v[2] else: raise ValueError, 'Exactdec constructor does not accept %r' %type(v) self.normalize() if decimals !='all' and decimals!=None: self.num, self.den, self.p10 = self.round(decimals).astuple() def __repr__(self): self.normalize() num = self.num; den=self.den; p10=self.p10 s = str(abs(num)) sign = '-'[:num<0] # '' or '-' dens = den != 1 and ' / %s'%den or '' # normalize to x.xxxxe if total string > 20 long zs = len(s)+p10 # leading digits or leading-zero deficit if negative if (zs<0 and -zs or p10)+len(s)>20: return "ED('%s%s.%se%s%s')" %(sign, s[0], s[1:].rstrip('0') or '0', zs-1, dens) zs = zs<0 and '0'*-zs or '' s = zs+s if p10>=0: return "ED('%s%s%s%s')" %(sign, s, '0'*p10, dens) elif zs>0: return "ED('%s%s.%s%s')" %(sign, s[:p10] or '0', s[p10:], dens) else: return "ED('%s%se%s%s')"%(sign,num,p10,dens) def __mul__(self,other): """multiply exactly""" other = type(self)(other) num = self.num * other.num den = self.den * other.den p10 = self.p10 + other.p10 return type(self)((num,den,p10)).normalize() __rmul__ = __mul__ def __add__(self, other): """add exactly""" other = type(self)(other) num = self.num; p10 = self.p10; den = self.den numo = other.num; p10o = other.p10; deno = other.den dshift = p10-p10o if dshift: if dshift<0: p10o += dshift numo *= 10**-dshift else: p10 -= dshift num *= 10**dshift numsum = num*deno+numo*den densum = den*deno return type(self)((numsum, densum, p10)).normalize() __radd__ = __add__ def __sub__(self, other): """substract exactly (negates other and adds)""" other = type(self)(other) other.num = -other.num return self + other def __rsub__(self, other): """add as right operand""" return type(self)(other) - self def __div__(self,other): """divide exactly -- multiplies inverse""" other = type(self)(other) num = self.num * other.den den = self.den * other.num p10 = self.p10 - other.p10 return type(self)((num,den,p10)).normalize() def __rdiv__(self, other): """divide in role of right arg""" return type(self)(other)/self def normalize(self): """ make num part carry sign remove common factors of num, den parts convert factors of 10 to exponent count convert den factors of 2 to 10/5 and remove 10's to exponent """ self.num, self.den = fracnorm(self.num, self.den) while self.num and self.num%10==0: self.num //= 10 self.p10+=1 while not self.den%2: self.num *=5 self.den //=2 self.p10 -=1 while not self.den%5: self.num *=2 self.den //=5 self.p10 -=1 return self def round(self, ndec=2): """ Return rounded value as exact decimal. Round away from zero on fractions of .5 and more XXX needs alternative rounding choices. """ ret = type(self)(self) sign = ret.num<0 ret.num = abs(ret.num) ret = ret + type(self)((5,1,-ndec-1)) psh = -(ret.p10+ndec) ret.num //= (ret.den*10**psh) ret.den = 1 ret.p10 += psh if sign: ret.num = -ret.num ret.normalize() return ret def astuple(self): self.normalize(); return self.num, self.den, self.p10 def __eq__(self, other): return self.astuple() == type(self)(other).astuple() def __lt__(self, other): return (self-other).num<0 def __nonzero__(self): return self.num!=0 def __int__(self): return (self.num*10**self.p10)//self.den def test(): import sys for x in xrange(-9,10): sys.stdout.write('+') for y in xrange(-9,10): if not y: continue # skip zero denom for p10 in xrange(-9,10): s='%se%s/%s'%(x,p10,y) assert ED(s) == ED((x,y,p10)) print if __name__ == '__main__': print """ Enter 'test' to run test (such as it is), otherwise Enter arguments to be passed to the ED constructor, or prefix with *, /, +, or - to operate with previous result Enter r to round previous result. Note that your input is passed to eval unvalidated, so do NOT let this run where that would be dangerous!! Enter quotes to make string literals for ED constructor. To pass a float per se, specify decimals, e.g., > 0.1, 'all' ED('0.1000000000000000055511151231257827021181583404541015625') > 0.1, 22 ED('0.1000000000000000055511') > 0.1, 18 ED('0.100000000000000006') > 0.1, 16 ED('0.1') To constrast, a string literal (second below) is accurate: > 0.1, 'all' ED('0.1000000000000000055511151231257827021181583404541015625') > - '0.1' ED('5.5511151231257827021181583404541015625e-18') Press Enter only, to Exit.""" value = ED(0) while 1: try: cmd = raw_input('%r\n> '%value).strip() if not cmd: break if cmd == 'test': test(); continue if not cmd[0] in '*/+-r': value = eval('ED(%s)'%cmd) else: if cmd[0]=='r': value = eval('%s.round(%s)'%(value, cmd[1:].strip())) else: value = eval('%s %s ED(%s)'%(value, cmd[0], cmd[1:].strip())) except (EOFError, KeyboardInterrupt), e: raise SystemExit, 'Exiting due to %s'%e.__class__.__name__ except Exception, e: print '%s: %s'%(e.__class__.__name__, e) ======================================================================================= Regards, Bengt Richter From peter at engcorp.com Mon Nov 10 17:56:07 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Nov 2003 17:56:07 -0500 Subject: response time References: <1jSrb.2419$9_.105379@news1.tin.it> <87d6bzetsz.fsf@pobox.com> Message-ID: <3FB01787.529425BC@engcorp.com> "John J. Lee" wrote: > > Alex Martelli writes: > > > Jos? wrote: > > > > > I'm programming a simple script to calculate response time from one > > > server to another server. > [...] > > > I can only calculate it in seconds, is there a way to do it in > > > miliseconds? > > > > After "import time", time.time() returns the time (elapsed since an > > arbitrary epoch) with the unit of measure being the second, but the > > precision being as high as the platform on which you're running will > > allow. The difference between two results of calling time.time() is > [...] > > Also note that Windows' time(), in particular, has a precision of only > around 50 milliseconds (according to Tim Peters, so I haven't bothered > to test it myself ;-). Pretty strange. Strange, but based on a relatively mundane thing: the frequency (14.31818MHz) of the NTSC color sub-carrier which was used when displaying computer output on a TV. This clock was divided by 3 to produce the 4.77MHz clock for the original IBM PC (because oscillators were/are relatively expensive, so you wanted to re-use them whenever possible, even if just a submultiple) and then by 4 again to produce the clock signal that went to the chip involved in time-keeping, which then counted on every edge using a 16-bit counter which wrapped around every 65536 counts, producing one interrupt every 65536/(14.31818*1000000/12) or about 0.5492 ms, which is about 18.2 ticks per second. So other than it being closer to 55 ms than 50, you're right. Google searches with "18.2 14.31818" will produce lots of background for all that. -Peter From newsgroups at jhrothjr.com Sat Nov 1 14:10:15 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 1 Nov 2003 14:10:15 -0500 Subject: prePEP: Decimal data type References: Message-ID: "Alex Martelli" wrote in message news:MTSob.78975$e5.2933818 at news1.tin.it... Alex, I think we've lost context, so I'm going to state, up front, the context I see for the discussion. More detail is at the back of this post. I'm quite happy with the notion of all the messy accounting and regulatory details being handled by a money type that is designed to keep the accountants and regulators happy, at the expense of programming simplicity. I spent quite a few years doing that type of programming; I think I know a bit about it. Given that, I don't see any real advantage in having a separate decimal type that duplicates the functionality needed for money. The decimal type should be directed more toward the intuitive, ease of use angle that Python is famous for. I also don't see a case for a floating decimal type. If you have the money type, then there isn't a whole lot that you can do with floating decimal that you can't do with regualar binary floats. I can see some justification for a simple, straightforward, fixed decimal type that makes reasonable assumptions in corner cases, while still allowing the programmer a good deal of control if she wants to exercise it. That's the context of my remarks. > John Roth wrote: > ... > > Alex, where did I suggest that I wanted a rational data type? Please > > tell me one place in my response where I said that. Please? > > You fought against limited precision, and said NOTHING against > the requirement that the new type support division (point 12 in > the specs). This implies the implementation must use rationals > (by any other name). The alternative explanation is that I simply hadn't thought that part of the issue through when I made the response. It's a much simpler explanation, isn't it? > Of course, if you now change your responses > (and in particular change the lack of objection to / into a > request that it be abrogated, as you do below) then (at least > some of) the objections to your proposals change (the one against > the crazy idea of having number+string implicitly convert the > string "just as if" it had been explicitly converted stands, of > course -- "if you want Perl, you know where to find it"). That's discussable, of course. > > > The only place where you can get into trouble is with division > > and equivalent operations. That's the one place where you actually > > If one accepts that an arbitrary float is somehow (perhaps a bit > arbitrarily) coerced into a decimal-fraction before operating > (e.g. by multiplication) -- or forbids such mixed-type operations, > against your expressed wishes -- yes. If we're going to have to specify additional information when we explicitly construct a decimal from a float, as one variety of proposal suggests, then I see no difficulty with prohibiting implicit conversions. In fact, I seem to remember a note that implicit type coercion may vanish sometime in the misty future (3.0 time frame.) > The resulting decimal type, however, may not be highly usable > for some kinds of monetary computations. I think that was the justification for a separate money data type. > It's an unfortunate > but undisputable fact of life that laws and regulations exist > that specify some monetary computations in detailed ways that > differ from each other. Understood, in detail. [...] > Note that the operation that gives trouble here is not a > division -- it's a multiplication. The problem is with carrying > around "unbounded precision" _when laws and regulations > tell you otherwise_. Forcing the user to remember to round > again (by calling the appropriate rounding function) after every > multiplication is dangerous, because subtly wrong but plausible > results will come if the user forgets one of those calls. The > sensible approach would seem to be to imbue every Decimal instance > with the rounding rules that instance is supposed to follow (in > most programs the rules will be the same for every instance, but > _allowing_, albeit with some trouble if need be, particularly > complicated programs to carry on computations with several > different sets of rules, would be good -- as long as no accidental > and incorrect "mix" of them can happen by mistake). That is, in fact, the way money needs to be handled. However, I was under the impression that the separate money type was still in play, for the reasons stated in the pre-pep. [...] > I have no issue with that, but I definitely think that, to actually > be USEFUL in practice, Decimal instances should be able to carry > around their own precision and rounding-rules. Then you can use > explicit div and mul (functions or methods) when you want to > explicitly specify something different -- probably add and sub too, > when you want to produce a Decimal that may have different rules > as a result, or explicitly "mix" (operate betweem) instances that > might have different and possibly conflicting rules. But you can > also use the ordinary operators in ordinary circumstances when you > are operating between instances that have the same rules. In > this case, I think that add(a,b) , mul(a,b) , etc, without specific > parameters for precision, rounding, nor other rules, might be > totally equivalent to a+b , a*b , etc. It costs nothing and it > might endear us a little bit to the "migrating from Cobol" crowd > (OK, not as much as "add a to b" would, but we can't have that:-). The base problem with this is that COBOL doesn't do it that way, and COBOL was deliberately designed to do things the way the accounting profession wanted, or at least make it possible to do them without the language getting in your way. Part of the reason why COBOL has the separate operators is that the *destination* of the operation specifies how the result is computed. You can't do that with intermediate results if you use expression notation. The only way you can do anything similar in a language like Python is to avoid the operators and use functions or methods that allow you to explicitly specify the exact form of the result, together with the rounding rules, if any, used to get there. Another thing that hasn't been brought up, though: COBOL also allows you to specify a maximum for a value: you can't exceed it without causing an overflow exception (which can be caught with an ON OVERFLOW clause, of course.) John Roth > > > Alex > From b.hall at irl.cri.nz Sat Nov 29 18:08:29 2003 From: b.hall at irl.cri.nz (Blair Hall) Date: Sun, 30 Nov 2003 12:08:29 +1300 Subject: The namespace for builtin functions? Message-ID: <3FC926ED.7070906@irl.cri.nz> Can anyone please tell me how to correctly use a built in function when there is a function of the same name in local scope? Here is an example. Suppose the following is in myApply.py: def apply(func,seq): # # Code can default to # built-in definition in some cases: return __builtins__.apply(func,seq) #------------------------------------- if(__name__ == '__main__'): print "Three = ",apply(lambda x,y: x+y, (1,2) ) This seems to work, but if I import the definition of 'apply', like: >>> from myApply import apply >>> apply(lambda x,y: x+y, (1,2) ) I get a crash: Traceback (most recent call last): File "", line 1, in ? File "C:\proj_py\Learning\builtins\myApply.py", line 5, in apply return __builtins__.apply(func,seq) AttributeError: 'dict' object has no attribute 'apply' I can't see what to use instead of '__builtins__' as the namespace for the built in functions. From peter at engcorp.com Wed Nov 26 09:31:07 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 Nov 2003 09:31:07 -0500 Subject: Pychecker under Windows References: <153fa67.0311252016.2e02b575@posting.google.com> <153fa67.0311260620.9f22938@posting.google.com> Message-ID: <3FC4B92B.5AD8C86D@engcorp.com> Kylotan wrote: > > "Steve Holden" wrote in message news:... > > > You can redirect python output to a file from the Windows command line. The > > only caveat is for *some* command processors (NT in particular, IIRC) output > > redirection only works if you explicitly call the python interpreter (i.e. > > use the command "python prog.py > file.out") rather than implicitly call it > > (i.e. use the command "prog.py > file.out"). > > Sadly, the way to use Pychecker on Windows involves indirect usage; > you call it via a batch file on the command line. Redirecting that - > at least on Win98 SE - doesn't work, instead creating an empty file > and sending all output to stdout as normal. Easy enough to solve. Either type the same commands as the .bat file contains directly on the command line, redirecting the output, or change the .bat file (or make your own) which always redirects output to a predetermined file, then just view the file after PyChecker runs. -Peter From hanesjenny at verizon.net Fri Nov 28 13:25:19 2003 From: hanesjenny at verizon.net (jennifer haynes) Date: Fri, 28 Nov 2003 18:25:19 GMT Subject: jython applet Message-ID: I can't Date() to print out in an applet this is what I have from java.util import Date from java import awt, applet from java.lang import String class Enhanced(applet.Applet): def paint(self, g): today = Date() g.drawString(today, 10, 30) if __name__ == '__main__': import pawt pawt.test(Enhanced()) From daniels at dsl-only.net Thu Nov 13 23:45:25 2003 From: daniels at dsl-only.net (sdd) Date: Thu, 13 Nov 2003 20:45:25 -0800 Subject: Access sql with python, please. I'm desperate In-Reply-To: References: <3fb31f7a$1@nntp0.pdx.net> Message-ID: <3fb46bdc$1@nntp0.pdx.net> dd wrote: > Thank you very much. It really helped. You are welcome. By the way, we try to avoid "top-posting" here in the c.l.p newsgroup, since it makes the message hard to read. These messages get searched pretty intensively by people looking for answers, and we like to keep them readable. > By the way, can one do the following? > select * from [a-query] where ....... > So, select from a query instead of a table... Well, that depends on your database provider (Access in this case), rather than ODBC. I have two suggestions: 1) (A Python suggestion) Just try it. Fire up Idle, pythonwin, the python interpreter, or whatever interactive python you find the most comfortable and type away. 2) (a database guy suggestion) Avoid it if you can. Your query is best handled if it is in a nice, flat, and-only query. A query optimizer "wants" to try a lot of different ways to evaluate your query, and pick the one with the least estimated cost based on things like indices, estimated sizes, and actual sizes. The "nested query" form is not trivially transformed into a form that allows for many rewrites; several cheaper optimizers just "punt" on such queries and run the obvious way. That said, on at least some systems you can say: SELECT * for (SELECT age, weight FROM personnel) WHERE age in (SELECT age FROM retirees) -Scott David Daniels Scott.Daniels at Acm.Org From StefanoZAP.THIS at gaburri.net Thu Nov 6 13:56:38 2003 From: StefanoZAP.THIS at gaburri.net (stefanogaburri) Date: Thu, 06 Nov 2003 19:56:38 +0100 Subject: [XPOST] [REQ] open source multimedia authoring tools? In python maybe? In-Reply-To: References: Message-ID: email9898989 at yahoo.com wrote: > I forgot to mention, if it can be Windows-only, you can embed Internet > Explorer in your wxPython app and play the videos with it. See > ActiveXWrapper_IE in the wxpython demo. interesting - besides the fact that this and the Acrobat wrapper don't seem to work on my machine :) > David Woods also figured out a way to play video in wxPython using an > ActiveX interface to ActiveMovie on the Windows side and a > Carbon/Quicktime wrapper for the Mac side: ok, I'll try to find the time to check them out, although Kevin's E.Class Builder above seems more promising right now... thanks again, SG From mbabcock at fibrespeed.net Mon Nov 3 15:45:41 2003 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Mon, 03 Nov 2003 15:45:41 -0500 Subject: Does python always need to compile ENTIRE program before it canstart to run it??? In-Reply-To: References: Message-ID: <3FA6BE75.1020609@fibrespeed.net> > > >"Michael T. Babcock" wrote: > > >>> ... that'll still run 'fine' because you don't use "a" >>> >>> That said, the "compilation" time of a Python program is almost >>> nonexistant in most cases. Most of the work is runtime; load a class, >>> wait for the class to compile, and so on.. >> >> > >That's not *exactly* true, I'm afraid. The above example would >actually raise a NameError, since the name "help" is not defined >at the time of execution, if you tried constructing an a(). > > You seem to have completely missed my saying 'because you don't use "a"' in that message. In fact, I actually ran that program to check before making the post. For what its worth, if you had "help = " instead of just "help", it would raise a SyntaxError on execution. However, it doesn't know if "help" is a valid statement or not yet because it hasn't evaluated 'a' and therefore leaves you alone about it. >Therefore I believe your first statement is actually not true, and >in fact Python code that "wouldn't compile" actually cannot be run, >because it has to be compiled prior to running. > It does not throw a SyntaxError, and it does in fact run. Have a go at it. -- Michael T. Babcock C.T.O., FibreSpeed Ltd. http://www.fibrespeed.net/~mbabcock From ianb at colorstudy.com Sun Nov 2 19:13:25 2003 From: ianb at colorstudy.com (Ian Bicking) Date: Sun, 2 Nov 2003 18:13:25 -0600 Subject: form processing question In-Reply-To: <423f3$3fa58837$42a655ea$20950@msgid.meganewsservers.com> References: <423f3$3fa58837$42a655ea$20950@msgid.meganewsservers.com> Message-ID: <8AD3B5BD-0D92-11D8-92EF-000393C2D67E@colorstudy.com> On Nov 2, 2003, at 4:41 PM, WmGill wrote: > I am experimenting with Python, and want to convert some of my PHP > scripts > to python cgi scripts. In PHP I use PHP_SELF for the action target. > This > way I can "reuse" data in fields (i.e. if the user enters data in a > field > then submits the form, it comes back already filled in on each > subsequent > iteration). I know I can do this in Python, but before I spend a lot > of > time, is it very complicated, or can form field values be > (re-)populated > easily? You probably will be happier if you use something other than CGI, but for CGI I believe os.environ()['SCRIPT_NAME'] should give you what you want. (This URL introspection differs considerably between frameworks) -- Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org From prunesquallor at comcast.net Sat Nov 1 10:10:21 2003 From: prunesquallor at comcast.net (prunesquallor at comcast.net) Date: Sat, 01 Nov 2003 15:10:21 GMT Subject: Python from Wise Guy's Viewpoint References: <3F994597.7090807@ps.uni-sb.de> <1j5o61-co2.ln1@ID-7776.user.dfncis.de> <9eso61-mu7.ln1@ID-7776.user.dfncis.de> <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <8yn6gmic.fsf@comcast.net> <1xssqozs.fsf@comcast.net> Message-ID: Joachim Durchholz writes: > prunesquallor at comcast.net wrote: >> And most people seem to think that my `black hole' `syntactic >> construct', which does not type check under OCaml without the flag, >> but *does* under OCaml with the flag, can be unambiguously called a >> `program'. > > I'm still hoping for an explanation on the practical relevance of that > black hole device. Neel Krishnaswami had a wonderful explanation in article From vze4rx4y at verizon.net Sun Nov 30 01:30:40 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 30 Nov 2003 06:30:40 GMT Subject: sorting dictionary keys? References: <3fc91af5$0$28610$636a55ce@news.free.fr> Message-ID: > > sort() sorts in place and returns None > > > > > Which is one of the main PITA in Python IMHO :( > (not the fact that it sort in place, the fact that it does not return self). > > > Bruno Wish granted! Py2.4 will have a classmethod called list.sorted() that accepts any iterable as an argument and returns a new sorted list as a result. It can be used anywhere you can use an expression (function call arguments, lambdas, list comps, etc). Raymond Hettinger From richie at entrian.com Wed Nov 19 05:28:26 2003 From: richie at entrian.com (Richie Hindle) Date: Wed, 19 Nov 2003 10:28:26 +0000 Subject: PyQt, Qt, Windows and Linux In-Reply-To: References: Message-ID: [Rob] > The "official" Qt3 book is due in February of 2004, and the > included CD will include a non-commerical version of Qt 3.2.1 > for Windows [...] it appears that you will be able to distribute > the Qt runtime DLLs with your non commerical application [...] This is great news for people who want to develop free Windows software with Qt. Phil, do you yet know whether PyQt Non-Commercial will support this version of Qt? -- Richie Hindle richie at entrian.com From nav+posts at bandersnatch.org Sat Nov 22 12:16:58 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 22 Nov 2003 12:16:58 -0500 Subject: Using an interable in place of *args? References: <99dce321.0311211709.38f792fb@posting.google.com> Message-ID: dw-google.com at botanicus.net (David M. Wilson) writes: > Just random passing code commentary: [...] > for format, field in structure: [...] > That avoids the triple iteration. The vars(self) call is unnecessary, > I just think it looks cleaner. :) Interestingly enough, I'd already swapped out the list comprehensions for a single for loop. :^) Some respondants seemed confused about what I was trying to do... I'm communicating with a C program that generates datagrams from a C structure. Many of the datagrams have, for the last two fields, "unisigned int datasize; char data[]". I wanted a convenient way of extracting the fields of known size, and the data blob at the end. If others are interested in the class I've built, I can make it available (maybe through the Cookbook web site) when it's a little more mature. Again, thanks for all the pointers. Although the language itself is the first reason, the community is a close second for why I love programming in Python. 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 logan at phreaker.nospam Tue Nov 25 19:01:59 2003 From: logan at phreaker.nospam (Logan) Date: Wed, 26 Nov 2003 01:01:59 +0100 Subject: wxPython - wx package (new style wxPython?) Message-ID: Would you recommend to use the wx package of wxPython? >From the documentation: Provides a way to drop the wx prefix from wxPython objects by dynamically loading and renaming objects from the real wxPython package. This is the first phase of a transition to a new style of using wxPython. For example: import wx class MyFrame(wx.Frame): ... instead of: from wxPython.wx import * class MyFrame(wxFrame): ... What does 'this is the first phase of a transition to a new style using wxPython' in the above mean? Will this new style become the only way to use wxPython in future releases? Thanks in advance for any answers. -- mailto: logan at phreaker(NoSpam).net From gerrit at nl.linux.org Fri Nov 28 04:54:49 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Fri, 28 Nov 2003 10:54:49 +0100 Subject: How to GetClassName in Python In-Reply-To: <000c01c3b569$e30428c0$440210ac@Bala> References: <000c01c3b569$e30428c0$440210ac@Bala> Message-ID: <20031128095449.GA2426@nl.linux.org> bala wrote: > Hi, > I want to know how to getclassname of application from python..In python There is no method like GetClassName... > Is there any other Method ...I kindly give some example in python.. > If anyone answer to the above problem....I will be very thankfull to you... I think you are looking for the __class__ attribute. Each object has a __class__ attribute referring to the class of the object: (3).__class__ refers to int, MyClass().__class__ refers to MyClass, and int.__class__ refers to type. yours, Gerrit. -- 25. If fire break out in a house, and some one who comes to put it out cast his eye upon the property of the owner of the house, and take the property of the master of the house, he shall be thrown into that self-same fire. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From gerrit at nl.linux.org Tue Nov 18 11:15:56 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 18 Nov 2003 17:15:56 +0100 Subject: Library to generate 3D Graphs In-Reply-To: <3fb9f2ae$0$9729$edfadb0f@dread14.news.tele.dk> References: <3fb9f2ae$0$9729$edfadb0f@dread14.news.tele.dk> Message-ID: <20031118161556.GA6406@nl.linux.org> Johan Holst Nielsen wrote: > Anyone have knowlegde of good (and easy-to-use) (free) libraries to > generate 3D graphs? Gnuplot (www.gnuplot.info) can do it. There are also Python bindings. yours, Gerrit. -- 33. If a ... or a ... enter himself as withdrawn from the "Way of the King," and send a mercenary as substitute, but withdraw him, then the ... or ... shall be put to death. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From aleax at aleax.it Mon Nov 17 11:41:27 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 17 Nov 2003 16:41:27 GMT Subject: for what are for/while else clauses References: <2259b0e2.0311142321.aba58d3@posting.google.com> Message-ID: Alexander Schmolck wrote: > Alex Martelli writes: >> Python could presumably help a little by warning about an 'else' on >> a for or while loop that contains no 'break' statements. But the >> reason Python's for/else and while/else statements are not intuitive >> to most people can be boiled down to identifying that "controlling >> condition" -- the fact that the 'controlling condition' is "a break >> statement has executed" is """hardly obvious or most particularly "the >> only obvious" interpretation""", to repeat myself:-). > > Hmm, I can't see the break here: > >>>> for x in []: print 'something' > ... else: print 'nothing' > ... > nothing Exactly because there is no 'break' in the loop's body, the 'else: ' clause-header is useless in this case; the code: for x in []: print 'something' print 'nothing' (where the second print follows the whole loop rather than being the body of its 'else' clause) would be quite equivalent. > (Not that I wouldn't argue that the semantics of else in loops are > blindingly obvious, but I can see the (albeit slightly strained) analogy > with if/else). If I squint hard enough I can see the similarity, sure, but I keep thinking that "how do I _USE_ this language feature" is a more generally useful viewpoint than "how is this language feature implemented". And the (modest) _usefulness_ of the else clause on for and while loops is inevitably connected to the possibility that a 'break' in the loop's body may execute. If there is no such possibility, you might as well just code the statements right after the whole loop, rather than putting them in an else clause. Alex From jsbenson at bensonsystems.com Mon Nov 17 14:46:30 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Mon, 17 Nov 2003 11:46:30 -0800 Subject: oops: correction to "question on precision" post Message-ID: <065e01c3ad43$81b235e0$210110ac@jsbwxp3> I got the multiplication precision rule wrong: relative precision is defined as the uncertainty divided by the magnitude of the measured quantity, e.g. 10 meters +/- 1 meter gives an uncertainty of 1 meter, and a relative precision of 1/10 or 10% The rule is that the relative precision of the multiplication is the sum of the relative precisions of the factors. When we square 10 +/- 1 meters to find the square area corresponding to that side, we get 100 square meters with a relative precision of 1/10 + 1/10 or a 20% relative precision of the 100 square meter result, which squares (sorry) with the +/- 20 range computed by squaring the range 9 through 11 meters for a squared area range of 81 through 121 square meters. The problem still remains, though, that the midpoint of the squared range is 101, and not 100! -------------- next part -------------- An HTML attachment was scrubbed... URL: From cbeck at mercury.bc.ca Sat Nov 1 22:14:11 2003 From: cbeck at mercury.bc.ca (Coby Beck) Date: Sun, 2 Nov 2003 14:14:11 +1100 Subject: Explanation of macros; Haskell macros References: <87brs2tjut.fsf@memetrics.com> <87he1rdt9d.fsf@memetrics.com> <874qxpgp70.fsf@swangoose.isst.fhg.de> Message-ID: "Olaf Klischat" wrote in message news:874qxpgp70.fsf at swangoose.isst.fhg.de... > "Coby Beck" writes: > > > "Pascal Costanza" wrote in message > > news:bnscfb$p1k$1 at newsreader2.netcologne.de... > >> > >> The essence of this is as follows: > >> > >> (defmacro my-cond (&body body) > >> `(cond ,@(append body '(t (handle-the-default-case)))) > >> > > > > Just to provide a more apparently general (and working ;) version, analogous > > to CL's ECASE: > > > > CL-USER 90 > > > (defmacro econd (&body body) > > `(cond ,@(append body > > `((t (error (format nil > > "fell through ECOND form. could not > > satisfy any of the following: ~{~%~A~}~%" > > (mapcar #'(lambda (cond) > > (car cond)) > > ',body)))))))) > > > Just for the record: Is the "append" stuff necessary? Why not write > this as > > (defmacro econd (&body body) > `(cond , at body > (t (error (format nil "fell through ECOND form. could not satisfy any of the following: ~{~%~A~}~%" > ',(mapcar #'(lambda (cond) > (car cond)) > body)))))) > That works. I blame Pascal for my gratuitous use of append and now I have been exposed as one of those copy-paste-alter code monkeys without a formal correctness proof in my head ;) -- Coby Beck (remove #\Space "coby 101 @ big pond . com") From aaron at reportlab.com Wed Nov 12 11:22:54 2003 From: aaron at reportlab.com (Aaron Watters) Date: 12 Nov 2003 08:22:54 -0800 Subject: program surgery vs. type safety Message-ID: <9a6d7d9d.0311120822.553cd347@posting.google.com> I'm doing a heart/lung bypass procedure on a largish Python program at the moment and it prompted the thought that the methodology I'm using would be absolutely impossible with a more "type safe" environment like C++, C#, java, ML etcetera. Basically I'm ripping apart the organs and sewing them back together, testing all the while and the majority of the program at the moment makes no sense in a type safe world... Nevertheless, since I've done this many times before I'm confident that it will rapidly all get fixed and I will ultimately come up with something that could be transliterated into a type safe system (with some effort). It's the intermediate development stage which would be impossible without being able to "cheat". A type conscious compiler would go apopleptic attempting to make sense of the program in its present form. If I were forced to do the transformation in a type safe way I would not be able to do as much experimentation and backtracking because each step between type safe snapshots that could be tested would be too painful and expensive to throw away and repeat. This musing is something of a relief for me because I've lately been evolving towards the view that type safety is much more important in software development than I have pretended in the past. ah well... back to work... -- Aaron Watters === You were so cool back in highschool what happened? -- Tom Petty From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Fri Nov 28 07:13:53 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Fri, 28 Nov 2003 15:13:53 +0300 Subject: invert dictionary with list &c In-Reply-To: References: Message-ID: Des Small wrote: > anton muhin writes: > > >>Des Small wrote: >> >>>Des Small writes: >>> >>> >>>>anton muhin writes: >>> >>>[...] >> >>Or like this: >> >>def dict_update(iter, func, default, d): >> def process_element(d, e): >> d[e[0]] = func(d.get(e[0], default), *e[1:]) >> return d >> >> return reduce(process_element, iter, d) >> >>def count(l): >> return dict_update(l, lambda x: x + 1, 0, {}) > > > With these I get: > > >>>>count(["yes", "yes", "no"]) > > > Traceback (most recent call last): > File "", line 1, in ? > File "", line 2, in count > File "", line 5, in dict_update > File "", line 3, in process_element > TypeError: () takes exactly 1 argument (3 given) > > I tried to write something that would work on more generic arguments, > but I couldn't do it without explicit type checking, so I gave up. > > [...] > > Des > has now embalmed versions in his utils collection. > My fault :( A small patch: def count(l): return dict_update([(e,) for e in l], lambda x: x + 1, 0, {}) now print count(['yes', 'yes', 'no']) print count('aabbbc') prints {'yes': 2, 'no': 1} {'a': 2, 'c': 1, 'b': 3} regards, anton. From jbublitzno at spamnwinternet.com Thu Nov 20 13:00:40 2003 From: jbublitzno at spamnwinternet.com (Jim Bublitz) Date: Thu, 20 Nov 2003 18:00:40 GMT Subject: PyQt, Qt, Windows and Linux References: Message-ID: email9898989 at yahoo.com wrote: > Jarek Zgoda wrote in message > news:... >> Don't spread FUD. You don't have to pay for Qt if you >> distribute it under GNU Public License. Even commercially. You >> can earn money for your software and you have nothing to pay >> to Trolltech if this is GPL-ed software. They can say >> anything, but it's GPL, they just can not impose such >> restriction. > That is incorrect. You DO have to play them if you want your > app to run _on any platform_ (i.e., Linux AND Windows), > regardless if it is GPL licensed, free, commercial, or > whatever. *Somebody* has to pay for Qt libs/PyQt to be used on Windows - not necessarily the author/distributor, if the end-user already has a license. The point Jarek and I are making is that since the Linux versions of both Qt and PyQt are GPL'd, *nobody* has to buy a Qt or PyQt license to run on Linux (or OSX, or other *nix as far as I know). Also, there's nothing stopping you from charging for your software in that case, or for Qt or PyQt, but you do have to provide source code at no charge. As far as commercial use, you only have to make source code available *if you distribute* the software - that wouldn't apply to strictly internal use. As long as "cross-platform" doesn't include Windows, you can write cross-platform code with Qt and PyQt and no one has to buy a license. A Windows version would require licenses for Qt and PyQt. Jim From jjl at pobox.com Fri Nov 14 12:40:08 2003 From: jjl at pobox.com (John J. Lee) Date: 14 Nov 2003 17:40:08 +0000 Subject: Amazon full-text book index [was: Re: a python book hint] References: Message-ID: <87oeveetmv.fsf_-_@pobox.com> claird at lairds.com (Cameron Laird) writes: > In article , [...] > I can't now do Amazon's text-search capabilities justice; they are > making for a sea change of the scale of Google or VoIP or other > "epochal" innovations. Briefly, if there's a book that interests > you, and Amazon has it, it's likely you can bring up any of its > pages on-line. You can sample it freely. [...] I'm told (bookpeople mailing list) they scanned and OCRed them all, even though books are now always (well, almost always) in machine- readable textual form at some stage in their preparation. A bit sad in terms of duplication of effort, though another recent bookpeople post told the story of somebody's personal first "perfect" OCR of a book: fewer errors in the scan than in the original! The ability to search books is certainly interesting and new (I've tried to find even a tables-of-contents database for books before, and the university librarian told me that no such beast existed). Maybe it's even as important as Google, dunno. It will be missing two central parts of Google, though: instant, zero-marginal cost access to the content, and linking information. John From jjl at pobox.com Sat Nov 22 19:10:36 2003 From: jjl at pobox.com (John J. Lee) Date: 23 Nov 2003 00:10:36 +0000 Subject: pythoncom.connect() References: Message-ID: <87k75sgd1f.fsf@pobox.com> "John J. Lee" writes: Not another one! And there was I thinking my "J." made me safe from namespace clashes... :-( > I have problems when I get the IDispatch with pythoncom.connect(). > When I called the 'Excel.Application' with it, it worked. (At least I can > see the pythoncom.connect() is working for the well-designed COM like > Excel.) > When I called my COM module which was derived from IDispatch interface, > the pythoncom.connect() issued error like > com_error: (-2147221021, 'Operation unavailable', None, None). [...] Do you know about win32com.client.Dispatch and friends? Why are you calling pythoncom.connect()? John From martin at v.loewis.de Sat Nov 15 17:23:57 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 15 Nov 2003 23:23:57 +0100 Subject: python-2.3.2 and pth References: Message-ID: dave writes: > did anyone have problem with "--with-pth" when compiling python-2.3.2 on > solaris2.9? Most likely, the answer is "no" - not because there wouldn't be problems if anybody tried, but more because nobody tried. Why would anybody want to use pth on Solaris 9? Regards, Martin From jegenye2001 at fw.hu Thu Nov 13 16:49:06 2003 From: jegenye2001 at fw.hu (Jegenye 2001 Bt) Date: Thu, 13 Nov 2003 22:49:06 +0100 Subject: Python programmers required (High tax free savings package) References: Message-ID: Jegenye 2001 Bt wrote in message news:bou8i0$niq$1 at namru.matavnet.hu... > > tglinternational wrote in message > news:mailman.655.1068634052.702.python-list at python.org... > > Please check details on www.tgl-international.com/jobs.html Send > > your CV / resumes alongwith covering letter to steve at tgl- > > Huh, they have to really pay a lot so that one would work in the Saudi > Arabian desert... ;) > > Mikl?s > > I'm still musing over what money I'd take this adventure... despite this stuff being Python... and I just cannot make up my mind. ;) Well, "gnothi seauton" applies.. Mikl?s From olivier.hoarau at mortauxspams.bz Thu Nov 13 11:25:05 2003 From: olivier.hoarau at mortauxspams.bz (Olivier Hoarau) Date: Thu, 13 Nov 2003 17:25:05 +0100 Subject: XLM and XSLT Message-ID: <3FB3B061.B72526CA@mortauxspams.bz> Hello, I would like to create a file from a xml file with a xslt transformation in a python program. Is there someone who can give me some examples to do that ? something like this import libxslt import libxml2 xsl=parseStylesheetFile(xsl file) xml=parseFile(xml file) result = applyStylesheet(xls,xml) saveResultToFilename(result,outfile) Olivier From nessus at mit.edu Sat Nov 22 13:07:09 2003 From: nessus at mit.edu (Douglas Alan) Date: Sat, 22 Nov 2003 13:07:09 -0500 Subject: Tkinter widget that functions like Explorer "Details" mode? References: Message-ID: Logan writes: > I think, you have to write such a widget yourself (which is in fact > not so difficult - except for the 'adjustment of the column width'). Well, yes, that's the part that's been worrying me. |>oug From email9898989 at yahoo.com Sun Nov 9 11:59:37 2003 From: email9898989 at yahoo.com (email9898989 at yahoo.com) Date: 9 Nov 2003 08:59:37 -0800 Subject: Inter-Process comunication References: Message-ID: Zunbeltz Izaola wrote in message news:... > I want to plot the data in a "canvas", but i want to replot each time > a point is added to data. I don't watn to insert the code to plotting > inside the Measure (becose this code is GUI dependent). The code for > plotting is in another function DrawPlOt() > > I want something like to send a signal each time the data is changed > to execute DrawPlot(). I'm no proffesional programmer and i don't know > wich technique is the best, signals, theread, anothero one ... > Any sugestions? First do you want your data collecting class running as a separate thread in your wxPython app (simplest way), or as a completely separate process/application that communicates remotely with your wxPython app? To do it using threads, see: http://wiki.wxpython.org/index.cgi/LongRunningTasks If it is running as a separate application, then you would need to use something like sockets/Pyro/Twisted to communicate with your wxPython app. Second, if you are just plotting the data, see something like wxPyPlot or SciPy's wxPython plotting options. http://scipy.com/ http://www.cyberus.ca/~g_will/wxPython/wxpyplot.html Next, see the Observer-Observable and Model-View-Controller patterns. Bruce Eckel has an example of observer and observable in Python: http://jamesthornton.com/eckel/TIPython/code/util/ Make your data collecting class (the Model) a subclass of Observable. When it gets new data, it calls its own "notifyObservers" method, and optionally passes the data value (with or without a time stamp too) as an argument. Your wxPython canvas (the View) subclasses Observer, and implements a "notify" method to receive the new data and draw it. But don't redraw it immediately if the Model is running in a separate thread, use something like wxCallAfter(self.RedrawPlot) so that all drawing happens in the main wxPython application thread (or if you are using SciPy, see its gui_thread module). One other problem - if your model is continuously collecting a lot of data very fast, then your wxPython app will get bogged down if you redraw every time new data is received. What I do is have the "notify" method just append the time stamped data to an array (see the Numeric module). Then I use a wxTimer to draw the new data at regular intervals. From __peter__ at web.de Tue Nov 4 14:20:46 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Nov 2003 20:20:46 +0100 Subject: XORing long strings opimization? References: <3ISpb.24447$BD3.4566933@juliett.dax.net> Message-ID: Noen wrote: > def XOR(s1,s2): > """ XOR string s1 with s2 """ > output = "" > # Argument check > if (type(s1) and type(s2)) != type(""): > raise TypeError, "Arguments are not strings" > if len(s1) != len(s2): > raise ValueError, "Size differs in strings" > # Xoring > for c1 in s1: > for c2 in s2: > output += chr(ord(c1) ^ ord(c2)) > return output > > This way is very slow for large strings. > Anyone know of a better and faster way to do it? Before we start optimizing: len(XOR(s1, s2)) == len(s1) * len(s2) Bug or feature? Peter From edreamleo at charter.net Mon Nov 10 15:56:40 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Mon, 10 Nov 2003 14:56:40 -0600 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: <7N6dnUz1P9CKZTOiRVn-hQ@comcast.com> Message-ID: > Such a request is *NOT* a legitimate 'anti-junk-mail' measure. Yes, it is. If you aren't willing to take 20 sec. to talk to me, then I'm not willing to talk to you. Bye. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From adalke at mindspring.com Tue Nov 18 01:17:44 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 18 Nov 2003 06:17:44 GMT Subject: Python's simplicity philosophy References: <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> <%N8tb.28277$hV.1041253@news2.tin.it> Message-ID: Terry Reedy: > Perhaps my career in statistics and data reduction made reduce() more > immediately obvious to me than some other people. I know when I first saw reduce, in Python BTW, I did not intuit that meaning. I was in physics grad school and with a bachelor's in math, with an emphasis in analysis, so my math background was pretty strong. (Though nowadays I look through my books and wonder that I actual knew all that once upon a time... *sigh*) Andrew dalke at dalkescientific.com From skilchen at bluewin.ch Sun Nov 9 19:56:54 2003 From: skilchen at bluewin.ch (Samuel Kilchenmann) Date: Mon, 10 Nov 2003 01:56:54 +0100 Subject: prePEP: Decimal data type References: Message-ID: <3faee2f8$1_1@news.bluewin.ch> "Bengt Richter" schrieb im Newsbeitrag news:bojrg5$vim$0 at 216.39.172.122... > > Following is an exact decimal/rational module hack that > implements rounding when the .round() method is called. > This is not too elegant, but it might make > an interesting toy to cross-check results with. Thanks a lot for this interesting toy! some results seem a little bit strange to me, eg.: Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from exactdec import ED >>> ED('0.95',1) ED('9..0') >>> ED('0.995',2) ED('99..0') >>> ED('0.9995',3) ED('99.9.0') >>> ED('0.99995',4) ED('99.99.0') >>> ED('0.999995',5) ED('99.999.0') >>> ED('0.9999995',6) ED('1.0') >>> its probably due to the line: ret.num //= (ret.den*10**psh) in your rounding code and the fact that: >>> 1 // 0.1 9.0 >>> 10 // 0.01 999.0 >>> 100 // 0.001 99999.0 >>> 1000 // 0.0001 9999999.0 >>> 10000 // 0.00001 999999999.0 >>> 100000 // 0.000001 100000000000.0 From peter at engcorp.com Mon Nov 10 17:12:11 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Nov 2003 17:12:11 -0500 Subject: What do you think of this Python logo? References: Message-ID: <3FB00D3B.2BCE081A@engcorp.com> "Brandon J. Van Every" wrote: > > What do you think of this Python logo? > http://pythonology.org/logos > Good, bad, indifferent, love it, hate it? Pretty slick, although at least the larger version look a lot like an egg being impregnated by a sperm... Has potential though. What about minus the planet? -Peter From aleax at aleax.it Thu Nov 13 10:38:26 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Nov 2003 15:38:26 GMT Subject: True inconsistency in Python References: Message-ID: Scott Chapman wrote: ... > It seems that maybe Python should throw a warning (perhaps if a flag is > set) any time it bumps into code comparing a variable to True or False. It's a bit hard to do it just for variables, but doing it for _any_ comparison would _almost_ be reasonable -- testing if something "== True" is hardly ever sensible. Unfortunately "a == b" CAN be perfectly sensible and either or both of the variables MIGHT just happen to be set to True. However, this looks to me like a good suggestion for PyChecker and the like, which should be able to catch and flag the actual explicit use or the constant True in code involving == or != ... Alex From mhammond at skippinet.com.au Sun Nov 30 19:12:59 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 01 Dec 2003 11:12:59 +1100 Subject: struct module usage In-Reply-To: References: Message-ID: BW Glitch wrote: > Hi! > > I'm trying to send a message from a Python script to a Scite window via > win32gui.SendMessage() I'm trying to pack the commands using the struct > module. However, I can't figure out why Scite isn't responding as I > expect. The SendMessage is returning 0. > > I've searched Google and haven't found anything that would help me. > There was a discussion about this same thing about 2 years ago and the > poster solved the problem using calldll. I checked last night and > calldll is available only for Python 2.1, while I'm using 2.3. > > Here's a snippet from the code: > > ##### > import win32api, win32gui, win32con > import sys > import struct > > SDI = win32api.RegisterWindowMessage("SciTEDirectorInterface"); > w = win32gui.GetWindow(win32gui.GetDesktopWindow(),win32con.GW_CHILD) > > while w: > res = 0; > res = win32gui.SendMessageTimeout(w, SDI, 0, 0, > win32con.SMTO_NORMAL, 1000) > if res[1] != SDI: > w = win32gui.GetWindow(w, win32con.GW_HWNDNEXT) > else: > break > n = len("goto:20") + 1 > s = struct.pack(`n` + "sii", "goto:20,3", 9, 0) > > res = win32gui.SendMessage(w, win32con.WM_COPYDATA, s, SDI) > ##### Are you sure you are sending the correct message with the correct params? The Windows doc for WM_COPYDATA say wparam should be a hwnd, and lparam should be the COPYDATASTRUCT. It appears you are sending the struct in wparam, and a custom message integer as wparam. Further, the COPYDATASTRUCT contains pointers, not char arrays. Your struct code will need to be more complicated. Something like: import struct, array int_buffer = array.array("L", [0]) char_buffer = array.array("c", "the string data") int_buffer_address = int_buffer.buffer_info()[0] char_buffer_address, char_buffer_size = char_buffer.buffer_info copy_struct = struct.pack("pLp", # dword *, dword, char * int_buffer_address, char_buffer_size, char_buffer_address) # find target_hwnd somehow. win32gui.SendMessage(w, WM_COPYDATA, target_hwnd, copy_struct) Mark. From rkern at ucsd.edu Sat Nov 22 15:03:16 2003 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 22 Nov 2003 20:03:16 +0000 (UTC) Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> Message-ID: In article <7xu14xdu8a.fsf at ruckus.brouhaha.com>, Paul Rubin writes: > Tim Churches writes: >> If a compiled Python extension module B includes code from some >> other software A which is licensed only under the GPL, do other >> Python programmes, C, which import module B also need to be licensed >> under a GPL-compatible license (assuming C is/are to be distributed >> to third parties)? > > It's not enough for B and C to be under "GPL-compatible licenses". > They have to be under the actual GPL. > > From http://www.gnu.org/licenses/gpl-faq.html#LinkingWithGPL > > You have a GPL'ed program that I'd like to link with my code to build > a proprietary program. Does the fact that I link with your program > mean I have to GPL my program? > > Yes. Note that the question is phrased as a "proprietary vs. GPL" dichotomy. I think the following entry is more appropriate: http://www.gnu.org/licenses/gpl-faq.html#TOCGPLModuleLicense """ If I add a module to a GPL-covered program, do I have to use the GPL as the license for my module? The GPL says that the whole combined program has to be released under the GPL. So your module has to be available for use under the GPL. But you can give additional permission for the use of your code. You can, if you wish, release your program under a license which is more lax than the GPL but compatible with the GPL. The license list page gives a partial list of GPL-compatible licenses. """ -- 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 for_usenet2000 at yahoo.de Tue Nov 4 13:22:46 2003 From: for_usenet2000 at yahoo.de (Daniel Schüle) Date: Tue, 4 Nov 2003 19:22:46 +0100 Subject: static? + some stuff References: Message-ID: [...] > is "cnt" considered to be used as "static" or not > what if i would write ... > foo.cnt += 1 #static > and later in one of member functions > self.cnt = 1 #non static after long thinking i came to the conclusion that .. from what KefX said .. "assigning to it .. would smash 'static' for this instance of the class" i would say ... class some_class: cnt = 0 def __init__(self): foo.cnt += 1 self.my_id = foo.cnt def some_func(self): self.cnt = 100 def print(self): print foo.cnt x = some_class() x.print() #1 y = some_class() y.print() #2 x.some_func() #<--- smashes cnt ONLY for x instance?!?! x.print() #100 z = some_class() #..but not for the instances that might come z.print() #3 i haven't tested that, ALL OUTPUT assumed!!! [...] From X.3.M__antispam__ at mail.ru Mon Nov 10 04:12:23 2003 From: X.3.M__antispam__ at mail.ru (sinisam) Date: Mon, 10 Nov 2003 10:12:23 +0100 Subject: Need help with OOP References: Message-ID: Guys, I don't know what to say... Thank you all! I was away for three days, and was hoping to see at least one answer to the problem, but there were far to many than one! You all did a great job, thanks again! From loiosh13 at yahoo.com Thu Nov 20 08:25:42 2003 From: loiosh13 at yahoo.com (Tim Isakson) Date: Thu, 20 Nov 2003 13:25:42 GMT Subject: PYTHONPATH problems References: Message-ID: On Thu, 20 Nov 2003 11:13:23 +0100, Fredrik Lundh wrote: > Tim Isakson wrote: > >> However, it isn't finding any of the modules in the directory tree that >> begins under /home/tim/python/PP/Examples (it's not having any problems >> with the standard modules - as evidenced by the import of sys above). > > "sys" is a built-in module; Python finds that one without even looking at > the path. > >> I'm at a loss - any thoughts on what I'm doing incorrectly? >> >> Thanks for any assistance! > > running Python with the "-vv" flag might provide you with some additional > clues: > > $ python -vv > >>> import mymodule > # trying mymodule.so > # trying mymodulemodule.so > # trying mymodule.py > # trying mymodule.pyc > # trying /mysystem/lib/python2.1/mymodule.so # trying > /mysystem/lib/python2.1/mymodulemodule.so /.../ > # trying /mysystem/lib/python2.1/site-packages/PIL/mymodule.py # > trying /mysystem/lib/python2.1/site-packages/PIL/mymodule.pyc > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named mymodule > > (also note that you must have read access to the scripts; if Python cannot > read a file, it treats it as if it didn't exist) > > Thanks for the -vv flag tip - it helped some. Sadly (for me, at least), the problem turned out to be user error - I was using BASH syntax for the path while within Python, and needless to say, that didn't do the trick. Once I changed the imports to use '.' as the delimiter, things worked fine. Thanks for your assistance! Tim From joeytsai at gehennom.net Wed Nov 19 19:40:46 2003 From: joeytsai at gehennom.net (Joey Tsai) Date: Wed, 19 Nov 2003 19:40:46 -0500 Subject: intra-module dependencies Message-ID: <20031120004046.GA30095@demogorgon> Assuming you have two directories of modules: project/lib project/filters How can functions in "filters" reference functions in "lib"? Right now I have in the files in filters: sys.path.append( ".." ) import lib But that's kinda ugly. Section 6.4 in the python tutorial says that if I'm in the project/filters directory I should be able to access lib like: import project.lib But that doesn't work if I'm running python scripts in the project/filters directory. Is there any nicer way to do this? Basically, I have a "main" project file that uses things in both lib and filters, so normally I don't have this problem, but I want the filters to be able to run by themselves. Thanks! Please CC to me, I'm not subscribed -- joey tsai | A witty saying proves nothing. | -- Voltaire From usenetBLOCK at myrealbox.com Thu Nov 20 20:48:59 2003 From: usenetBLOCK at myrealbox.com (Charlie Orford) Date: Fri, 21 Nov 2003 01:48:59 +0000 Subject: Best method for an NT service and python to interact? Message-ID: <9arqrv4umfpe1dhnicfjuod1bv7ihf8pds@4ax.com> Hello all, I have been asked to develop a python client that can talk to an NT service (coded in C). Does anyone have any advice for the best way in which to go about this task? The NT service monitors file access. When a file of a specific type is accessed I need to inform the python client. Would it be better for the NT service to message the python client or would it make more sense for the python client to poll the NT service at set intervals (every 1000ms for example)? Does anyone know of any online tutorials or examples that might point me in the right direction? TIA, -- Charlie aka gpuk E-mail? Remove the BLOCK to reply From no at spam.invalid Tue Nov 4 12:18:58 2003 From: no at spam.invalid (Russell E. Owen) Date: Tue, 04 Nov 2003 09:18:58 -0800 Subject: Tkinter event question References: Message-ID: In article , Eric Brunel wrote: >> #!/usr/local/bin/python >> from Tkinter import * >> root = Tk() >> >> class myLabel(Label): >> def sendFoo(self): >> self.event_generate("<>") > >Do you really need to send the event to the label itself here? Apparently, it >is >what causes the problem: doing a self.master.event_generate("<>") has the >expected result. That sounds like a good workaround. Thanks! What I'm actually trying to do is: - I have a "manage panels" widget that takes a list of control panel widgets, displays a column of checkbuttons (one per widget) and then either displays or hides each control panel depending on its associated checkbutton - In certain limited cases I want a control panel to open itself (with the associated checkbox toggling appropriately) - I was sending "<>" from the panel to accomplish this, and it only worked if the panel had ever been shown. I was considering using a logical variable, but felt it was inappropriately tight coupling between the "manage panels" widget and the panels themselves. I will verify that it's a tcl/tk bug and report it if so (and I agree it seems virtually certain to be so). -- Russell From tjreedy at udel.edu Mon Nov 10 10:56:48 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 Nov 2003 10:56:48 -0500 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: Message-ID: <8s2dnY6a29XCITKiRVn-vA@comcast.com> wrote in message news:mailman.592.1068443199.702.python-list at python.org... > On Sun, 9 Nov 2003 21:29:35 -0500 "Terry Reedy" > writes: > > > > "Edward K. Ream" wrote > > [lots of stuff about the benefits of Leo over several posts] > > > Edward K. Ream email: edreamleo at charter.net > > > > In response to this series, I sent you a friendly note saying a) I am > > considering Leo as a base for a future project and > > b) I think there is a problem with a couple of > > lines in the code you posted. > > NameError: name 'c' is not defined? > I wondered about that too...(if that was it) I wrote him about an apparent double binding of 'c'. > > In response, you sent me the > > > > ---------- > > You recently sent a message to me at the email address > > edreamleo at charter.net. To help cope with the ever increasing volume > > of > > junk e-mail, I am using ChoiceMail, a permission-based e-mail > > filtering tool. Your original e-mail is being held by ChoiceMail > > until > > you complete the following simple one-time process. > > Please click on the link > > [Click here to request approval] > > When your browser opens, fill in your name and a short reason for > > wanting to send e-mail to me. If your reason is acceptable, your > > first > > email and all subsequent e-mails from you will be delivered to me > > normally. > > ------------ > > > > I will not beg you to read my bug report. Such a request is *NOT* > > a > > legitimate 'anti-junk-mail' measure. > > personal email to an author is rarely welcome > as a bug report! although in this case a tossup. When someone posts articles in a newgroup, there are two appropriate response channels: a public followup article such as mine, yours, and mine, and a private note to the response address given. Since I was not completely sure there was a bug, and certainly did not know the appropriate fix, and since only people who downloaded Leo could run the example and stumble over the problem, if there was one, I thought it appropriate to respond privately at the address *HE INCLUDED IN THE TEXT* and let him followup as he thought appropriate. If the author of a newsgroup posting does not want personal replies, he should *not* put his address in the text and *should* either say explicitly 'Please no private replies.' and/or use an obviously fake address in the From: header. > if you've checked the sourceforge forums, > you would see the nature of the response > time to problems of any kind including wild eyed > spitballing of ideas is nearly immediate. I was responding to a newgroup posting -- in the standard and appropriate manner -- not the content on sourceforge. > > Being unable to communicate directly with you makes > > Leo less inviting to me. If I were > > to adopt Leo for a project anyway, > > I would warn users to not email the above address. > > not wanting the job of channeling EKR, > you must realize the level of spam a project like > Leo generates would render any email address > unusable in short time. If this is an intolerable problem for him, he could, when posting, use a throwaway or usenet-only address for replies. > really, it's a painless few clicks & keystrokes, Not for me...and I want anyone contemplating imitating Mr. Ream to know that. > if you can get over your initial reaction. To see if I were over-reacting, I asked my more socially adept wife to read his boilerplate reply. Her response was as strongly negative. > since spam isn't going away, you have to admit > this is one of few good solutions. NO, THIS IS A BOGUS 'SOLUTION'. Any rule-based or statistical filter worth installing would have passed my email. A legitimate whitelist program sends a reply, with coded subject line, something like 'I have received an email with your return address. If you receive this reply and you really sent that email, just hit reply and send and you will be added to my list of real people.' Very little junk mail come with a valid, non-forged address connected to a human reader. Read his response again. He is asking people to send a second message, thru an alternate channel, giving 'reasons' which he will judge for 'acceptibility'. This is crazy, if not egotistical. He can just as quickly read and even evaluate the original message, perhaps after verifying that it is from a real person. Not acceptible. > there are additional bug reports and a diary of > the Leo dev cycle in LeoPy.leo and LeoDocs.leo > and an active forum on sourceforge. > http://sourceforge.net/forum/?group_id=3458 Again, my response to him was about his posted articles, and not about Leo. Terry J. Reedy From gduzan at bbn.com Mon Nov 10 12:36:55 2003 From: gduzan at bbn.com (Gary D. Duzan) Date: Mon, 10 Nov 2003 17:36:55 GMT Subject: Can I hook a "file" to a python script? References: <3hru71-7p3.ln1@valpo.de> <2kqv71-9u4.ln1@valpo.de> Message-ID: In article <2kqv71-9u4.ln1 at valpo.de>, Mathias Waack wrote: >Scott Chapman wrote: > >> I understand named pipes to be "one-way" only. Is that correct? > >Not for Linux. Linux named pipes are bidirectional. I assume this >holds for all unices but I'm not sure. No, it doesn't hold everywhere. A more portable bi-directional construct would be a UNIX/LOCAL domain socket bound to a file. Gary Duzan BBN Technologies A Verizon Company From trentm at activestate.com Sat Nov 1 21:50:34 2003 From: trentm at activestate.com ('Trent Mick') Date: Sat, 1 Nov 2003 18:50:34 -0800 Subject: ANN: ActivePython 2.3.2 & ActivePython 2.2.3 In-Reply-To: <041d01c3a0db$557615b0$0500a8c0@eden>; from mhammond@skippinet.com.au on Sun, Nov 02, 2003 at 11:50:37AM +1100 References: <20031101143220.A4976@ActiveState.com> <041d01c3a0db$557615b0$0500a8c0@eden> Message-ID: <20031101185034.B3475@ActiveState.com> [Mark Hammond wrote] > IMO, the very best thing AS could do would be to arrange that a win32all > package could update the version in ActivePython. There are a number of > ways this could happen - I guess the one that needs the least of my time > would be for you to have your own "ActivePython Update", built from my > specific win32all tags in between ActivePython updates. That is probably the most likely, i.e. a new ActivePython build for each new win32all build/release. (ActivePython doesn't do "update" packages, i.e. you have to uninstall the previous APy before installing the "update"). AFAIK one _should_ be able to install a newer win32all build overtop of an ActivePython installation. The only problems would be ActivePython's installer perhaps complaining on uninstall, not completely cleaning up on uninstall, and ActivePython's installer's "Repair" functionality reverting back to its original win32all build. > A better way that would require some of my time is to have > win32all.exe itself find and upgrade ActivePython. Isn't this the same thing? Unless you mean something really fancy by "upgrade" there. > ... > * Drop all registry stuff, using a few .pth files > ... > > This will probably happen after the next 2 or so win32all releases. The > second item in that list would be a good time to work out how we could > upgrade ActivePython from win32all. Hrm. ActivePython uses MSI and the best way to upgrade such an install is to build MSI "update/patch" packages. I haven't ever looked into that but I can guarantee that it involves a steep learning curve that we may decide is not worth the trouble. Don't know though. The ActivePython build system is much improved recently s.t. it isn't too hard for me to whip off new builds when a new win32all comes along. (I know I've said that before though.) Trent -- Trent Mick TrentM at ActiveState.com From a.schmolck at gmx.net Wed Nov 12 10:28:10 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 12 Nov 2003 15:28:10 +0000 Subject: Leo + Python: the ultimate scripting tool: gui issues References: Message-ID: "Edward K. Ream" writes: > 2. One of my hopes in writing the original series of postings was that > there would be some discussion of integrating Leo with Emacs using pymacs. > This may have started to happen. I would really like help with this project, > and I'll support anyone working on such a project in any way I can. I think > running some kind of Leo window on Emacs would be totally cool. Have you come across allout.el and speedbar.el (a seperate tree browser window)? Emacs has several outlining facilities amongst which allout is the best IMO (I already use it for some of my python code) -- integrated with speedbar this would supply quite a bit of the core functionality that leo offers (plus, of course plenty additional functionality, most importantly good editing and search facilities). 'as From aleax at aleax.it Sat Nov 1 17:10:17 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 01 Nov 2003 22:10:17 GMT Subject: prePEP: Decimal data type References: Message-ID: John Roth wrote: > "Alex Martelli" wrote in message > news:MTSob.78975$e5.2933818 at news1.tin.it... > > Alex, I think we've lost context, so I'm going to state, > up front, the context I see for the discussion. More > detail is at the back of this post. > > I'm quite happy with the notion of all the messy accounting > and regulatory details being handled by a money type that > is designed to keep the accountants and regulators happy, > at the expense of programming simplicity. I spent quite a > few years doing that type of programming; I think I know > a bit about it. Most of the "expense of programming simplicity" can be hidden from application programs and placed in a suitable "decimal arithmetic" type. As per http://www2.hursley.ibm.com/decimal/ , "a single data type can be used for integer, fixed-point, and floating-point decimal arithmetic" -- and for money arithmetic which doesn't drive the application programmer crazy, too, as long as: 1. the existing standards are respected -- this means, again as per the quoted site, IEEE 754R + IEEE 854 + ANSI X3.274 + ECMA 334 2. specifying the rounding mandated by typical existing laws and regulations (e.g., the EU ones) is made reasonably easy for those typical applications that must apply such typical rules throughout 3. there are ways to specify other arbitrary sets of rules, and handle difficult cases such as more than one such set in use within a single program (but it's clear that a general approach to this point [3] may not achieve ease and simplicity) 4. syntax for cases sub [2] is adequately easy and Pythonic In other words, _no way_ a Pythonista will want to code some vaguely pythonic equivalent of (http://www2.hursley.ibm.com/decimal/dnusers.html): 18. decNumberDivide(&rate, &rate, &hundred, &set); // rate=rate/100 19. decNumberAdd(&rate, &rate, &one, &set); // rate=rate+1 20. decNumberPower(&rate, &rate, &years, &set); // rate=rate**years 21. decNumberMultiply(&total, &rate, &start, &set); // total=rate*start rather than, e.g.: total = start * (1 + rate/100)**years or something like this. As long as 'start' and 'rate' are suitable instances of Decimal, carrying appropriate precision and rules (the "decContext set" that here is being passed boilerplately at each painstaking step), there is nothing ambiguous nor dangerous here. > Given that, I don't see any real advantage in having a separate > decimal type that duplicates the functionality needed for > money. The decimal type should be directed more toward the > intuitive, ease of use angle that Python is famous for. The Decimal type discussed in this PEP is the arithmetic fundament for Money. Facundo started out with the idea of a PEP for a type named Money that mixed arithmetic, parsing and formatting concerns. He received ample and detailed feedback, on the basis of which he (quite reasonably, IMHO) concluded that a Decimal type, based on existing nondist/sandbox implementations that realized Cowlishaw's ideas and work (as per the first URL above) would be the right fundament for a Money type (which could either subclass or use it and add parsing and formatting niceties as needed). So, this Decimal type isn't "duplicating" anything: it's intended to _supply_ the arithmetic features needed (inter alia) by money computations. > I also don't see a case for a floating decimal type. If you > have the money type, then there isn't a whole lot that > you can do with floating decimal that you can't do with > regualar binary floats. We won't "have a money type" unless its arithmetic can be handled by a suitable Decimal class (or intermixed with parsing and formatting in an overcomplicated class, but I would consider that an inferior choice). What you can do with Decimal (fixed or floating point) is basically to respect the "principle of least surprise" for the innumerable newbies who are overwhelmed by the concept that, e.g., "1.1" is displayed as 1.100000000000000001 with full precision. Such newbies do not necessarily expect that (e.g.) (1/3)*3 == 1 -- basically because they have used calculators, which are invariably based on fixed or floating point decimal arithmetic with bounded precision. They *DO* expect to be able to write "the four operations" simply. ABC's idea was to meet these newbies' concerns by using rationals. Rexx, which has always used decimal arithmetic instead, has a better track record in this respect. There may be a niche for unbounded decimal precision, either as a special case of Decimal, a subtype thereof, or a completely independent numeric type. But if that type requires giving up on the handy use of / and % -- I predict newbies will shun it, and they will have a point (so we should not _foist_ it on them in preference to bounded-precision Decimals that _DO_ let them do divisions with normal rules). One further detail you should note is that Python (out of the box, i.e. without such extensions as gmpy) doesn't let you have binary floating point numbers *with whatever precision you specify*: you're limited to what your hardware supplies. If you need, e.g., 1024 measly bits of precision -- TOUGH. Decimal, be it used as a fixed or floating point number, should suffer from no such limitation: whatever bounded precision you may specify on number creation (your memory permitting) should work just as well. Just that fact will allow a range of tasks which are hard to handle with Python's floats -- not because of binary vs decimal issues, but because Python's floats are just too limited for some tasks (gmpy.mpf instances would be fine even though they're binary, Decimal instances would be fine even though they're decimal). > I can see some justification for a simple, straightforward, > fixed decimal type that makes reasonable assumptions in > corner cases, while still allowing the programmer a good > deal of control if she wants to exercise it. I do not think Decimal is limited to either fixed or floating point. The Hursley site is quite specific in claiming that both can be supported in a single underlying type. Unbounded precision is a different issue. >> > Alex, where did I suggest that I wanted a rational data type? Please >> > tell me one place in my response where I said that. Please? >> >> You fought against limited precision, and said NOTHING against >> the requirement that the new type support division (point 12 in >> the specs). This implies the implementation must use rationals >> (by any other name). > > The alternative explanation is that I simply hadn't thought that > part of the issue through when I made the response. It's a > much simpler explanation, isn't it? If you advocate a right triangle whose cathets (two shortest sides) are of length 3 and 4, you cannot then feel outraged if others claim you advocated a triangle with a hypotenuse of length 5. The obvious and inevitable mathematical consequences of what you DO advocate are fully part of your advocacy -- and if you haven't thought such elementary aspects through, then when they're rubbed in your face you could admit your mistake, and change your position, rather than try attacking those who may have thought thinks through a little more thoroughly (or may be simply so familiar with the issues that the consequence Z of certain premises X and Y are utterly obvious to them). >> the crazy idea of having number+string implicitly convert the >> string "just as if" it had been explicitly converted stands, of >> course -- "if you want Perl, you know where to find it"). > > That's discussable, of course. Sure, everything is. x+"23" may raise an exception when x is a number of type int, long, float, OR complex, and STILL when x is a number of type decimal entirely different and ad hoc rules COULD apply, just in order to astonish everybody I assume. Are you actually planning to DEFEND this ridiculous contention, or just claiming it's "discussable" in some abstract philosophical way? Just checking...:-). >> > The only place where you can get into trouble is with division >> > and equivalent operations. That's the one place where you actually >> >> If one accepts that an arbitrary float is somehow (perhaps a bit >> arbitrarily) coerced into a decimal-fraction before operating >> (e.g. by multiplication) -- or forbids such mixed-type operations, >> against your expressed wishes -- yes. > > If we're going to have to specify additional information > when we explicitly construct a decimal from a float, as > one variety of proposal suggests, then I see no difficulty > with prohibiting implicit conversions. In fact, I seem to > remember a note that implicit type coercion may vanish > sometime in the misty future (3.0 time frame.) Yes, coercion is going -- that basically means that e.g. an __add__(self, other) (etc) method should deal with all types of 'other' that the type of 'self' is prepared to deal with, rather than factoring out all of the type-conversion issues into __coerce__. Basically an acknowledgment that conversions may too often need to be different for different operations. >> The resulting decimal type, however, may not be highly usable >> for some kinds of monetary computations. > > I think that was the justification for a separate money > data type. Money often needs to get into arithmetic computation with "pure numbers" -- numbers that do not directly measure an amount of money. For example, in compound interest computations, the monetary amounts basically come in at the very end, in multiplications by pure numbers which are previously computed without reference to the monetary unit. So, I don't think the "money data type" can do without a suitable. purely arithmetical data type that is basically the Decimal being discussed here (with or without possible extension to "unbounded precision" -- but with the need for e.g. raising-to-power, yet another of those "division- equivalent" [or worse] operations, I have my doubts there). Therefore, the idea that Money uses (perhaps by subclassing) Decimal, and further adds (e.g.) parsing and formatting aspects (not needed for the pure numbers that so often have arithmetic together with Money, while the aritmetic aspects ARE needed throughout), seems sound to me. > I was under the impression that the separate money type was > still in play, for the reasons stated in the pre-pep. Sorry, I don't see any mentions of money in the prePEP as Facundo posted it here on Friday -- perhaps you can quote the relevant parts of that post? > The base problem with this is that COBOL doesn't do it that > way, and COBOL was deliberately designed to do things the > way the accounting profession wanted, or at least make it > possible to do them without the language getting in your way. > > Part of the reason why COBOL has the separate operators > is that the *destination* of the operation specifies how the > result is computed. You can't do that with intermediate > results if you use expression notation. > > The only way you can do anything similar in a language like > Python is to avoid the operators and use functions or methods > that allow you to explicitly specify the exact form of the result, > together with the rounding rules, if any, used to get there. Yes, _when_ you need that -- which fortunately is not all that common. Basically, you can control something based on the type of a destination only via augumented assignment -- say += as the equivalent to "add a to b" -- rather than via the equivalent of "add a to b giving c", and the control (coming "from the destination") doesn't extend to intermediate results. Also, making mutable numbers (so that += allows some control, or so that you can have a .set method to control e.g. overflow wrt a max on assignment) is not very Pythonic. Most of the time, though, the rules can just as well be embodied in the operands as in the result -- and don't change operation by operation. > Another thing that hasn't been brought up, though: COBOL > also allows you to specify a maximum for a value: you can't > exceed it without causing an overflow exception (which can > be caught with an ON OVERFLOW clause, of course.) Given the difficulties with mutable numbers, maybe the best way to do that in Python is with a 'raiseifabove' function. Or maybe a "settable-ONCE" number with a flag that records whether it's already been initialized or not is acceptable, though instinctively it feels a bit clunky to me. Alex From matt at pollenation.net Wed Nov 12 09:17:05 2003 From: matt at pollenation.net (Matt Goodall) Date: Wed, 12 Nov 2003 14:17:05 +0000 Subject: Automating FTP file transfers In-Reply-To: References: Message-ID: <3FB240E1.1080904@pollenation.net> Limey Drink wrote: >Hi all, > >Firstly :-) , is there any where I can search through archived newsgroup >posts so I am not cluttering up the newsgroup with repeated queries ? > > Yep, info on all the python lists, including archives, are available here: http://python.org/community/lists.html >And secondly :-), I know this has probably been discussed before but. > >I am wanting to do some scripting to automate a few administration tasks, >one of the first tasks is automating FTP file transfers. > >I would like to know if the following could be made more robust using python >and its FTP libraries rather than executing native OS commands in a shell >script. > >Basically I need to... >1. Check on the local system for new files in a specific directory >If new files exist then... >2. Connect to a remote FTP server. >3. Transfer local files to a specific directory on the remote FTP server. >4. Then remove/archive local files and end session. > > Most of this should be fairly straightforward. (1) and (4) should be covered using the os and os.path modules; for (2) and (3) you need the ftplib module. The only problem you are likely to encounter is getting a remote directory listing. The FTP protocol neglected to formalise the response to FTP's LIST command and different servers send different results back :(. If this is a problem I would recommend using one of the ftpparse Python APIs: * http://effbot.org/downloads/#ftpparse * http://c0re.23.nu/c0de/ftpparsemodule/ftpparse.html >This is critical operation and though while in the past I have written DOS >scripts etc. to do simple tasks I have not needed to check for errors as >they weren't absolutely critical tasks. I am going to need to run this >overnight using AT or CRON then I need to know about file transfer errors >etc. and other problems that f I were actually performing the FTP transfer >manually I would get feedback of the problem and could re-try the operation. > > The ftplib module reports errors using the Python exception mechanism so you can make it as robust as you need and take whatever action is appropriate on errors. Hope this helps. Cheers, Matt -- Matt Goodall, Pollenation Internet Ltd w: http://www.pollenation.net e: matt at pollenation.net From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Nov 17 20:51:18 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 18 Nov 2003 02:51:18 +0100 Subject: Memory exception with Tkinter root.quit In-Reply-To: References: Message-ID: <3fb97b16$0$58705$e4fe514c@news.xs4all.nl> Jane Austine wrote: >>>>from Tkinter import * >>>>r=Tk() >>>>b=Button(r,text='Quit',command=r.quit) >>>>b.pack() >>>>r.mainloop() > > > And when I press the "Quit" button the mainloop exits. After that, if > I finish the python shell, a memory exception occurs. > > This is Windows XP machine with Python 2.3. Not much of a help, but I've tried it here: no problems... (python 2.3.2, win xp). Can it be a Python 2.3.0 issue that has been fixed in 2.3.1 or 2.3.2 ? --Irmen From max at alcyone.com Thu Nov 6 00:56:49 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 05 Nov 2003 21:56:49 -0800 Subject: PEP 289: universal and existential operators References: <5d83790c.0310231158.65595858@posting.google.com> <698f09f8.0311050646.8767d19@posting.google.com> <698f09f8.0311051223.39271429@posting.google.com> Message-ID: <3FA9E2A1.73B4756A@alcyone.com> Mark Hahn wrote: > Python doesn't use iftrue and whentrue, so why should it use alltrue > and > anytrue? I vote for all and any. Well said. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Sanity is a cozy lie. \__/ Susan Sontag From skip at pobox.com Tue Nov 18 12:43:02 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 18 Nov 2003 11:43:02 -0600 Subject: maximum value for long? In-Reply-To: References: Message-ID: <16314.23078.70365.258877@montanaro.dyndns.org> S> I have set ulong_max above to the C compilers ULONG_MAX definition S> from limits.h I would have expected Python to complain when setting S> the value of the variable very_long_long to anything greater than S> ULONG_MAX. Since I am currently doing computations with integer S> values *much* bigger than ULONG_MAX, this behaviour suites me, but I S> am wondering if this is a "standard" Python behaviour since I do not S> want my scripts to become dependant on some obscure non-standard S> feature... Python has a builtin unbounded long type. In 2.3, most (all?) operations on integers will return longs if the op would overflow the machine's int (typically 32- or 64-bits): >>> print 17**100 1108899372780783641306111715875094966436017167649879524402769841278887580501366697712424694256005093589248451503068397608001 S> Also, if Python really can handle longs that are bigger than the S> machines native longs, the interpreter has to do some sort of S> arbitrary precision math somewhere. Could you please point me to the S> according interpreter's source file(s)? Look at Objects/longobject.c in the source distribution. Skip From aleax at aleax.it Mon Nov 17 09:36:05 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 17 Nov 2003 14:36:05 GMT Subject: Python's simplicity philosophy References: <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> <%N8tb.28277$hV.1041253@news2.tin.it> Message-ID: Terry Reedy wrote: > "Alex Martelli" wrote in message > news:%N8tb.28277$hV.1041253 at news2.tin.it... >> to be consistent with your other arguments, no doubt you'd argue for >> a .sort() followed by [-1] as "more general" than max... > > By my definition of "more general", a function that returns all order > statistics of a list is trivially more general than one that returns > any fewer, including just one. It conveys a superset of the Of course. So...? > infomation conveyed by less general functions and answers a superset > of the questions they answer. If you add a control parameter > specifying which order statistics to return, then less general > functions have a restriced domain. > > So I have no idea your intent in appearing to challenge this and how > you think it contributes to your overall argument. Is your idea of > 'more general' so different? Hmmm, nobody else seemed to have any problem understanding my quip, including the poster at which it was directed. Let me spell it out for you: a few people are attacking 'sum' and defending 'reduce' because the latter is "more general". Why, so is sorting a sequence "more general" than finding its maximum; for "consistency" with their other arguments (which by this quip I'm alleging are no good) they should then be clamoring for the removal of 'max' to leave only 'sort'. (I did expect an O()-based objection and punctually got it, ready for my repartee about reduce(str.add, lotsastrings) being O(N squared), etc, etc). So, no, I don't think my idea of "more general" is different from yours: e.g., a function that, given a sequence, returns its length AND the number of times 'None' occurs as an item, is more general than one which just returns the length. That does not make it in any intrinsic way "necessarily preferable" -- and THAT is my point. Alex From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Nov 27 17:25:34 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 27 Nov 2003 23:25:34 +0100 Subject: Python bug report on SF, what now? In-Reply-To: References: <3fc660c2$0$1492$e4fe514c@news.xs4all.nl> Message-ID: <3fc679de$0$1502$e4fe514c@news.xs4all.nl> Martin v. L?wis wrote: > It will be noticed automagically. As it has a patch associated, you > should have submitted it as a patch, though - some of us (including > myself) give patches higher priority, as they indicate that the > submitter is willing to do all the work. [...] So you're saying that if you find a bug, and have a patch for it, just submit the patch (with problem description of course) on SF and forget about the bug tracker? Anyway thanks Martin for explaining :-) --Irmen. From val at vtek.com Sun Nov 23 15:57:10 2003 From: val at vtek.com (val) Date: Sun, 23 Nov 2003 15:57:10 -0500 Subject: Python: Good for Quasi-Newbie? References: Message-ID: Clark, Forget (for awhile) Python - share your great long-life experience. :) val "Clark Griswold" wrote in message news:vs22ut4adu195c at corp.supernews.com... > My programming experience: > > - Pascal (college prog 101 type course about 100 years ago) > - Basic (on a CDC main frame for a 102 course about 85 years ago) > - xBase (quite a bit) > - VB scripting within MS Office (mostly Access) > - Oracle SQL (if that counts) > > Python looks pretty good for what I want to do (Point of Sale). I haven't > done serious prog in a long time. The price is right. Suggestions? > > Since I'm the boss in this instance... I am not tied down to anything. > > thanks, > clark > > From emile at fenx.com Tue Nov 11 12:48:46 2003 From: emile at fenx.com (Emile van Sebille) Date: Tue, 11 Nov 2003 09:48:46 -0800 Subject: Helpful antivirus spamming? (OT except it got by spambayes due tothe contingent from c.l.py :-) References: Message-ID: Pettersen, Bjorn S > Found this in my "unsure" folder today (51%) me too... > and was just wondering if > it's just a massive waste of bandwith... +1 Emile van Sebille emile at fenx.com From s-rube at uselessbastard.net Mon Nov 10 13:25:08 2003 From: s-rube at uselessbastard.net (Eric Williams) Date: Mon, 10 Nov 2003 19:25:08 +0100 Subject: web guru advise needed. References: Message-ID: Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: > > 1) simple presentation layer processing. The HTML pages produced by server > will be more focused on presenting images (dynamic), rather that fancy > tables, frames, buttons. 2) the framework has to be robust and FAST on > performance. 3) runs only on Linux, well not really a requirement, more a > statement. 4) runs on Apache (and/or Tomcat) > > What technology gives me the best performance? > I'm so afraid that adapters like WebKit kills my performance but because > of my jsp experience, psp seems the best option. > > Vincent FWIW, I recently complete a CMS project with the following constellation: 1) Apache with mod_python 2) PostgreSQL for content storage, mostly in the form of blob'd Pickles 3) Templating using SimpleTAL (elegant and leightweight, but requires some downright heinous URLs) 4) Everything running behind Squid in accelerator mode It's pretty dang snappy on performance, but you'd need a dedicated server/processor for dynamic images, I would think. cya, Eric -- --- s- should be removed to contact me... From nessus at mit.edu Sat Nov 8 02:01:03 2003 From: nessus at mit.edu (Douglas Alan) Date: Sat, 08 Nov 2003 02:01:03 -0500 Subject: Tkinter, resizing, and widget clipping References: Message-ID: Douglas Alan writes: > Is there a way to tell Tkinter that I'd like to allow a window to be > resizable, but only down to the point where no widget clipping occurs? To answer my own question, I think that the following does the job: window.minsize(window.winfo_reqwidth(), window.winfo_reqheight()) |>oug From chenyu468 at hotmail.com Mon Nov 10 23:01:41 2003 From: chenyu468 at hotmail.com (chenyu) Date: 10 Nov 2003 20:01:41 -0800 Subject: newbie question, doesn't the opertion steps can be shorter? Message-ID: <6143ac23.0311102001.62ecd550@posting.google.com> hi everyone, I have read others code and tried to add some test code by "print" command. But I found the operations in "pythonwin" are too much. Is there any unneccessary step in the operations? or short way? For example, use interactive window, class1.py(contains "classA" file 1. modify file "class1.py" by add one line of modification code into "__init__" method. 2. push the "Save button" or "ctrl-s" 3. push the "check button" 4. push the "reload button" 5. switch to "interactive window" 6. add "from class1 import classA" line 7. create new object of "classA" Thank you in advance. kind regards/chenyu From tjreedy at udel.edu Mon Nov 17 23:13:24 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Nov 2003 23:13:24 -0500 Subject: True inconsistency in Python References: <3FB8847F.6CB1BECA@alcyone.com> Message-ID: "Ron Adam" wrote in message news:ivqhrv403or6mm68arqg5793gnaaehjq8e at 4ax.com... > x = True > if x: > .... since the above snippert is equivalent to if True: ... which is equivalent to ... you must have meant something more imvolved. But I am having trouble filling in the missing pieces. > So I get consistent results for the language and platform I'm using > now and in the future. If down the road someone decided to make True > = 3, and False = -5, and they change the language so that any boolean > comparisons return 3 and -5 respectively, my use of True and False > will still work. This strikes me as comparable to worrying about being killed by an asteroid. Is there some actual historical event that makes it more plausible to you? 'Someone' would have to be someone with the authority to make such a change in either the language or a particular implementation thereof. Such people are usually at least somewhat sane. If someone did make such a lunatic change, I suspect that it would not be the only one, and one would have to be a lunatic to keep using that language/implementation for serious work. Unless the language were locked up and proprietary, users could reject such a change anyway. (On the other hand, exposure to lesser lunacies *is* one of the risks of using proprietary unclonible systems.) ... > It looks to me that 'True' in python is a combination of the boolean > binary logic of 1 or 0, and as an "exists" test of 0 or not 0. I do not understand this. If you have a reference to 0, then 0 exists. If you do not, then the 'existence' or not of an int with value 0 is irrelevant. > If python had an exists operator, you could do. I think you are confusing names and objects. You can only apply an operator to objects and only to objects that exist. > if x exists: > 'do something' Do you mean if bound_to_something('x'): ? Normally, in the absence of error, one only uses names that one has defined (bound to somethingj). So you must be worried about the following scenario: if a: x=1 if exists(x): In non-module script only: import __main__ as mm x = 1 hasattr(mm, 'x') # True hasattr(mm, 'y') # False Anywhere: use try ... except NameError Or, don't do that (have conditionally defined name). Instead, x=None if a: x = something_not_None() if x != None: In other words, name != None is often idiom for exists('name')! > This could serve two options also... does the object exist? Again, Python only operates on objects that do exist. ... > With pythons dynamic variables, I think an exists function would be > useful to check if an object exists. Same comment. Terry J. Reedy From jjl at pobox.com Sat Nov 8 07:49:26 2003 From: jjl at pobox.com (John J. Lee) Date: 08 Nov 2003 12:49:26 +0000 Subject: Trouble with seek(0) command References: Message-ID: <87n0b79ga1.fsf@pobox.com> "Randy Gamage" writes: > I can't figure out why this script gets an error. This is script that gets > a web page, then parses the title out of the web page. When it's done > parsing, I would like to reset the pointer to the beginnning of the response > file object, but the seek(0) command does not work. Anybody know why? [...] urllib2's response objects just don't have a seek. They *can't* have a seek without caching data, since the data in question is gettin read from a socket: it just ain't there any more after you've .read() it! You can just make sure you always keep data read from a response object, so you can reuse it later -- but that is an annoyance. If you want a response object that *does* cache, and allow seeking, you could pinch seek_wrapper from ClientCookie (http://wwwsearch.sf.net/): response = seek_wrapper(urllib2.urlopen(url)) page = response.read() ... response.seek(0) ... I think Andrew Dalke has also posted a similar thing to seek_wrapper, that only allows .seek(0). Called ReseekFile, or something similar. Or just use ClientCookie itself: from ClientCookie import build_opener, SeekableProcessor o = build_opener(SeekableProcessor) response = o.open(url) page = response.read() ... response.seek(0) ... (or, if you prefer, you can ClientCookie.install_opener(o) so you can do ClientCookie.urlopen(url) instead of o.open(url)) John From max at cNvOiSsiPoAnMtech.com Tue Nov 11 13:23:36 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Tue, 11 Nov 2003 18:23:36 GMT Subject: rest->ps (or PDF?) (slightly ot) Message-ID: Hi, is there a converter for "reStructured text" to Postscript or PDF? thanks. max From nicolas.lehuen at thecrmcompany.com Fri Nov 21 04:58:04 2003 From: nicolas.lehuen at thecrmcompany.com (Nicolas LEHUEN) Date: Fri, 21 Nov 2003 10:58:04 +0100 Subject: Suggestion for a new regular expression extension References: Message-ID: <3fbde1b0$0$25033$afc38c87@news.easynet.fr> "Terry Reedy" a ?crit dans le message de news:sa-dncv-SrE2vyCiRVn-gQ at comcast.com... > > But in my case, it forces me to duplicate each alternative > > in the big regexp in my normalisation function, > > which causes quite tedious maintenance of the whole piece of code. > > I do not see that. I believe I would factor out and label the > needed-twice pieces and use ''.join([list-of-pieces]) to make the big > regexp. I thought of that, and this would of course solve one part of the problem, which is code duplication. However, it won't spare me a double execution of the regexps, once to check the whole address and parse it into high level tokens, and the second time to normalise each token according to various normalisation rules. That's why using Scanner would be handy, as it could help me do it in one pass. And the regular expression extension could help me do it in just one (big, ugly, yet no-nonsense) regular expression, with no code added. Anyway, I'm not saying this extension is required to do the job, I'm doing it already. The extension would greatly simplify the code, which is the point of using Python, isn't it ;). I guess it would also be useful to anybody implementing transliterators or tokenizers. Plus, it would be a feature of the RE engine that may not exist in Perl (just saying this as an incentive to implement it...). I'm having a look at _sre.c, but I have to confess that it is not the easiest piece of code I've seen... Plus, it seems that matches (apparently created in pattern_new_match) are built using indices within the tested string, so return arbitrary strings in matches would require quite a few changes. Regards, Nicolas Regards, Nicolas From dave_member at newsguy.com Thu Nov 13 01:14:18 2003 From: dave_member at newsguy.com (dave) Date: 12 Nov 2003 22:14:18 -0800 Subject: python compilation questions Message-ID: Hi: i compiled python-2.3.2 and ahve a coupel of questions: 1) i can't get python compiled with option "--with-pth" 2) without the option "--with-pth", it went through the compilation, but i had some problems with testing: ld: fatal: relocations remain against allocatable but non-writable sections collect2: ld returned 1 exit status it went throught rest of testing ok. anybody has any idea on this? From seberino at spawar.navy.mil Wed Nov 5 17:09:13 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 5 Nov 2003 14:09:13 -0800 Subject: distutils: How add "-L path" switch when building C extension? Message-ID: How add "-L path" switch when building C extension? I want compilation to use a DIFFERENT version of a library in a DIFFERENT directory than usual. Thanks. Chris From skip at pobox.com Tue Nov 18 12:26:37 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 18 Nov 2003 11:26:37 -0600 Subject: recommendations for python web programming tools In-Reply-To: References: Message-ID: <16314.22093.14060.965643@montanaro.dyndns.org> Dennis> Matthew Wilson fed this fish to the penguins on Tuesday 18 Dennis> November 2003 07:53 am: >> I am about to start designing a web application for my office >> intranet. It is pretty simple: we need a way to track conversations >> with contacts and a way to update contact information. Dennis> I'm not an expert, but have you looked at Zope? I am not an expert, but Zope is often overkill, especially if your requirements don't match Zope's assumptions. I recently discovered Quixote from MEMS Exchange (well, I've known about it for awhile, but only recently began experimenting with it) and have become quite enamored with it. It looks like if your environment meets these basic criteria: * unix-y platform * your website developers are already Python programmers * you don't need to support remote site editing by potentially hostile folks (like your marketing and engineering departments) then you might want to take a close look at Quixote. It's programming model is somewhat different than that for most other web app/publishing systems. You essentially program in Python for most tasks and sprinkle in some HTML instead of the other way around. It's also got a very small footprint. The full source tree is under 700k, so it's quite possible that if you need to consult the source you'll actually be able to find the relevant source to gaze at. Details can be found here: http://www.mems-exchange.org/software/quixote/ Skip From alanmk at hotmail.com Tue Nov 11 11:49:11 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 11 Nov 2003 16:49:11 +0000 Subject: Python's simplicity philosophy References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: <3FB11307.C0000174@hotmail.com> [Robin Becker] >>> The whole 'only one way to do it' concept is almost certainly wrong. [Alex Martelli] >> Bingo! You disagree with the keystone of Python's philosophy. Every >> other disagreement, quite consequently, follows from this one. [Douglas Alan] > The "only one way to do it" mantra is asinine. I hate to interrupt anybody's free flowing argument, but isn't it the case that Guido never said "There should be only one way to do it"? My understanding of the "Pythonic Philosophy" is that "there should be only one *obvious* way to do it", which is quite a different thing entirely. This philosophy is aimed at making python easy for newbies: they shouldn't get confused by a million and one different possible approaches. There *should* (not "must"!) be a simple and obvious way to solve the problem. Once one is familiar with the language, and all of the subtle power it encompasses, anything goes in relation to implementing an algorithm. Just my ?0,02. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From talon2lm at yahoo.com Wed Nov 19 23:59:06 2003 From: talon2lm at yahoo.com (Rob) Date: Wed, 19 Nov 2003 21:59:06 -0700 Subject: TKinter Destroy Question Message-ID: My first GUI so be gentle... When I start my program I call a class that runs the initial window. While in this class if a certain button is pressed it calls a function outside the class. This function then initially calls another function to "root.destroy()". Basically I want the current window gone so the function I just called can open it's own window. The problem I'm stuck with is that once this function is done and I need to close the new window to go to the next window i again call the function which performs the "root.destroy()". When I try to call it a second time it tells me: TclError: can't invoke "destroy" command: application has been destroyed How can it already be destroyed if I opened a new window in my function? Should I slip in somewhere a new "root.mainloop()" statment? It seems when I try this I get some weird results (Every command after the new root.mainloop() nothing happens, no buttons drawn, nothing). Is there an easier way to clear windows than to use the root.destroy? I've basically run into a nice brick wall... Thanks for the help! Rob From newsgroups at jhrothjr.com Tue Nov 11 07:01:01 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 11 Nov 2003 07:01:01 -0500 Subject: make order of function definitions irrelevant References: <87he1beug3.fsf@pobox.com> Message-ID: "Joerg Schuster" wrote in message news:crtr80fz49w.fsf at pinatubo.cis.uni-muenchen.de... > Thank you all, so far. I had asked the question because I am writing a > program that translates linguistic grammars into python functions. The > python functions are supposed to be called by another program of mine > that does regular expression matching. Like so: > > (1) Linguistic grammar > > NP --> det AP n > AP --> Adv+ a > > ( Lexicon is given. Like so: > > Det --> ['the', 'a', ...] > Adv --> ['really', ...] > A --> ['blue', 'nice', ...] > N --> ['programmer', 'biologist', ...] > ) > > (2) Python functions > > def NP(): > return sequence(det(), AP(), n()) > > def AP(): > return sequence(plus(adv(), a()) > > (3) Matching routine "pm": > > $ pm -pattern "NP_biologist VP_love NP_programming-language" -file my_corpus > > Actually, (2) is lot more complex than in the example, because it needs > "wildcards" that can be filled with semantic and other information by > pm. Yet, the user should be able to write his own grammar, therefore > the translation (1) -> (2). (Of course, the grammar would not be a > context free grammar, though it looks like one.) > > *If* the order of function definitions did not matter, then the > order of the grammar rules in (1) would not matter, either. > > Yet, I thought the translation program over, and I will probably give > it a new design, today. Actually, the order doesn't matter; what matters is that the function *definition* has been installed into the namespace before it's invoked. The function isn't executed until it's called, and it won't be called until something that *isn't* a function starts the program by calling something. That's why scripts always end with the lines: if __name__ == "__main__" doSomething() where doSomething() is the first function to execute in the program. Everything up to that point is usually just loading function and class definitions into the module name space. You can define functions in any order you want, as long as the invocation of the whole mess is at the end of the module. John Roth > > J?rg From missive at frontiernet.net Sun Nov 9 07:41:49 2003 From: missive at frontiernet.net (Lee Harr) Date: Sun, 09 Nov 2003 12:41:49 GMT Subject: truly working multipart uploads. References: Message-ID: On 2003-11-09, Hunter Peress wrote: > I have been unable to write a script that can do (and receieve) a multipart form upload. > > Also, it seems that there really are differences between python's implementation and else's. > > Can someone please prove me wrong with a script that works with itself AND with example 18-2 > from php: http://www.php.net/manual/en/features.file-upload.php > > I have seen some discussions related to this question recently on the python web-sig mailing list: http://mail.python.org/pipermail/web-sig/ From william_k_edwards2000 at yahoo.com Wed Nov 26 22:30:28 2003 From: william_k_edwards2000 at yahoo.com (william_k_edwards2000) Date: Thu, 27 Nov 2003 03:30:28 -0000 Subject: a newbie Message-ID: I am new to python.I have familiarized myself with Python through Doc. and, simple code.My question is really about pygame.Which is somthing I am very unfamiliar with.I could really use some honest advice about getting started in python or pygame.I would like to learn Python as my first programing language.IF somone could spare a litle time.I would greatly appreciate as i know it is really precious.Anybody with any suggestions on ways they might have started will be put to use. From donn at drizzle.com Thu Nov 20 20:16:22 2003 From: donn at drizzle.com (Donn Cave) Date: Fri, 21 Nov 2003 01:16:22 -0000 Subject: cooler piping References: Message-ID: <1069377379.729708@yasure> Quoth Csaba Henk : ... | However, its not the case: there is os.pipe() which is low-level and its | usage is complex, and there are several popen functions which are simple to | use, but they evaluate the given command by passing it to the shell, | throwing me back to the middle of the quotation hell I want to escape from. | A typical case is when one tries to find out some info about a file by | invoking the "file" command on it: the name of the file can be (almost) | anything, thus doing os.popen("file " + filename) gets sucked easily (here | filename is a variable storing the name of the file). (Don't tell me there | is a module in Python with the fucntionality of the file command [I don't | know wheter is], I could find out many similar examples.) What would be cool | is having a function with an execvp-like syntax: if I could do something | like os.fancypopen('file', ['file',fname])... You may find that popen2.popen2() already comes pretty close to this. You may specify a command string, but you also may specify a list of strings for execvp. The only difference is that you supply only the argument list, and the file to execute is inferred from its first element. Donn Cave, donn at drizzle.com From richie at entrian.com Wed Nov 19 09:48:40 2003 From: richie at entrian.com (Richie Hindle) Date: Wed, 19 Nov 2003 14:48:40 +0000 Subject: PyQt, Qt, Windows and Linux In-Reply-To: <04875CB4331F0240A0AD66F970978651160A18@paul> References: <04875CB4331F0240A0AD66F970978651160A18@paul> Message-ID: <2ovmrv87bfh66f1m76gjr9nc1bgaasdj0b@4ax.com> [Jason] > gpl the software and then he can develop cross platform for free. :-) That's only true for non-Windows platforms or the old 2.3 Non-Commercial edition of Qt. There is no GPL version of Qt for Windows, and Trolltech no longer distributes Qt 2.3 Non-Commercial (I guess if you can get your hands on a copy then you can still legally use it). John Lee's post of 2nd Nov 2003 summed the situation up perfectly (though we should add "and you can get your hands on a copy of the no-longer-available Qt 2.3 Non-Commercial" in the appropriate place) - > if (you're only using unix/linux) OR (you're happy to stick to Qt > 2.x AND you're non-commercial), you don't need a license. They were > talking about using Qt 3 on Windows: in that case, you do need a > license from both TT and Phil (ie. you need to buy BlackAdder, unless > you want to spend large quantities of cash for no reason). This is why a Non-Commercial edition of 3.2.1 for Windows is good news, and why we're interested to know whether PyQt Non-Commercial will support it. -- Richie Hindle richie at entrian.com From mikael.lexen at spam.no.volvo.com Mon Nov 10 10:59:33 2003 From: mikael.lexen at spam.no.volvo.com (=?ISO-8859-1?Q?Mikael_Lex=E9n?=) Date: Mon, 10 Nov 2003 16:59:33 +0100 Subject: Problem with McMillans Installer In-Reply-To: References: <0fNrb.2779$uv1.2214@nntpserver.swip.net> Message-ID: As always google is your friend. The answer to the problem is and I quote """ Chad, Just change support/useUnicode.py to say: "import encodings" (codecs and encodings used to import each other, but not any longer). -- Gordon """ /Mikael Mikael Lex?n wrote: > Nop I have > > import unicodedata,codecs > > but it doesn't help. I will try the mailing list. Thanks > > /Mikael > > > Eric Brunel wrote: > >> Mikael Lex?n wrote: >> >>> Hi >>> >>> I have the following code >>> >>> fileName="test.txt" >>> inputFile=file(fileName,'r') >>> b = unicode(inputFile.read(), 'utf-8') >>> inputFile.close() >>> >>> outputFile=file(fileName,'w') >>> >>> print >> outputFile, b.encode('iso-8859-1') >>> >>> outputFile.close() >>> >>> This code works ok. Then I use the Installer and made a --onefile >>> "binary". The building process is also ok but when I try to execute >>> the program I get the following error >>> >>> c:\python\siebel>convert "copy of test.txt" >>> Traceback (most recent call last): >>> File "", line 18, in ? >>> LookupError: no codec search functions registered: can't find encoding >>> >>> I change to --onedir build and get the same result. I did some >>> tests and found that if I put the "encodings" directory (from >>> ".../python22/lib" directory) in the "--onedir" directory >>> everything works ok . So my question is how can I tell the Installer >>> to get the "encodings" directory in the build process? >> >> >> >> Expicitely importing the codecs module in the Python program should >> solve the problem. >> >> BTW, McMillan Installer has its own mailing list (see >> http://trixie.triqs.com/mailman/listinfo/installer). You'll usually >> get quicker and/or better answers if you post your questions there >> rather than on c.l.py. >> >> HTH > > From __peter__ at web.de Sat Nov 22 06:31:01 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Nov 2003 12:31:01 +0100 Subject: Newbie here... getting a count of repeated instances in a list. References: Message-ID: Peter Otten wrote: > def filter_domains(domains, threshold=10): > "The most frequent domains in alphabetical order" Oops, above is an involuntary example of a bad docstring :-( Should rather be "Domains with threshold or more occurences in alphabetical (case-sensitive) order" Peter From aleaxit at yahoo.com Sat Nov 1 04:57:27 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 01 Nov 2003 09:57:27 GMT Subject: XML-RPC References: Message-ID: Ben wrote: ... > def _dispatch(self, method, params): > if method == 'pow': > return apply(pow, params) > elif method == 'add': > return params[0] + params[1] > else: > raise 'bad method' ... > p= [2,2] > print myserver._dispatch("add",p) the way you've coded your server, the client should call myserver.add(2,2) and NOT what you've coded on the client side. To see why add a simple print of method and params as the first line of _dispatch and you'll see: for the call to .add(2,2): dispatching 'add' (2, 2) for the call to ._dispatch('add', [2,2]): dispatching '_dispatch' ('add', [2, 2]) i.e. the way you call it string '_dispatch' becomes the method and the tuple of args that ends in params isn't what you apparently think it should be. Alex From infoNOSPAM at PythonRAD.tk Sun Nov 2 13:08:01 2003 From: infoNOSPAM at PythonRAD.tk (PythonRAD) Date: Sun, 02 Nov 2003 18:08:01 GMT Subject: Newbie Question References: Message-ID: <5Kbpb.399034$R32.13255274@news2.tin.it> "PythonRAD" ha scritto nel messaggio news:OY6pb.397431$R32.13194638 at news2.tin.it... Thank U so much! Michelangelo > www.pythonRAD.tk > ########################## > # Yahoo Messenger: ShineMiku > # Ti aspetto per chiccherare su > # Programmazione, Tecnologie > # Collaborazioni di Lavoro > ########################## > > From aleax at aleax.it Tue Nov 4 10:20:39 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 04 Nov 2003 15:20:39 GMT Subject: nearest neighbor in 2D References: Message-ID: Andrew Dalke wrote: > Ron Adam >> for point in p: >> distance = math.sqrt((new_point[0]-point[0])**2 \ >> +(new_point[1]-point[1])**2) > >> I really don't know how you can make this faster. There might be a Hmmm, that's what math.hypot is for, isn't it...? [alex at lancelot Lib]$ timeit.py -c -s'import math; p=1.6,2.5; np=2.4,1.3' 'math.sqrt((np[0]-p[0])**2 + (np[1]-p[1])**2)' 100000 loops, best of 3: 3 usec per loop [alex at lancelot Lib]$ timeit.py -c -s'import math; p=1.6,2.5; np=2.4,1.3' 'math.hypot(np[0]-p[0], np[1]-p[1])' 100000 loops, best of 3: 1.9 usec per loop >> library that has a distance between two points function that could >> speed it up. > > An easy way is to move the math.sqrt call outside the loop, since > sqrt(d1) < sqrt(d2) iff d1 < d2 (when d1,d2>=0) Yes, omitting the math.sqrt gives the same speed as calling math.hypot, and it's the classic solution to speed up minimum-distance problems. I vaguely suspect you could shave some further fraction of a microsecond by saving those differences as dx and dy and then computing dx*dx+dy*dy -- since another classic tip is that a**2 is slower than a*2. Let's see...: [alex at lancelot Lib]$ timeit.py -c -s'import math; p=1.6,2.5; np=2.4,1.3' 'dx=np[0]-p[0]; dy=np[1]-p[1]; disq=dx*dx+dy*dy' 1000000 loops, best of 3: 1.39 usec per loop ...yep, another small enhancement. Ain't measuring _FUN_?-) Alex From emile at fenx.com Tue Nov 11 10:25:14 2003 From: emile at fenx.com (Emile van Sebille) Date: Tue, 11 Nov 2003 07:25:14 -0800 Subject: module import performance question References: <729b56c7.0311102210.4869d4f6@posting.google.com> Message-ID: "Jeff Sykes" wrote in message news:729b56c7.0311102210.4869d4f6 at posting.google.com... > I have a cgi script that imports modules based on a user config file. > I am suffering some performance problems when I import these modules. > Some logging revealed that it seems to be taking about 1.3 seconds to > import these modules. This is running on a Windows 2000 box with a > Pentium II 400 processor, Python 2.1, Apache 1.3.19 as the web server. > I don't need screaming performance numbers, but this time is > excessive. Is it me, or does that number seem kind of slow? How many modules are being imported? > Any code > optimizations or recommendations? Don't append to sys.path. Try sys.path.insert(0,addlpath). Then the import will get an immediate hit and always the right module rather than stepping through all the preceeding directories. HTH, Emile van Sebille emile at fenx.com From exarkun at intarweb.us Mon Nov 10 12:45:53 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 10 Nov 2003 12:45:53 -0500 Subject: Strange infinite recursion in metaclass's __new__ Message-ID: <20031110174553.GA10076@intarweb.us> Due to some bizarre constraints placed on me, I've written the following metaclass: import types def remove(t, o): return tuple([e for e in t if t not in o]) class BizarreMetaclass(type): def __new__(klass, name, bases, attrs): if name == 'BaseClass': return type.__new__(klass, name, bases, attrs) return types.ClassType(name, remove(bases, [object]), attrs) class BaseClass(object): __metaclass__ = BizarreMetaclass class Foo(BaseClass): pass The solution is extremely hacky (but I've already tried and discarded about a dozen more straightforward attempted solutions). It is also broken, but it is broken in a way that I do not understand. Can anyone explain the unbounded recursion that occurs? Jp From chris_mahan at yahoo.com Fri Nov 14 17:50:18 2003 From: chris_mahan at yahoo.com (Christopher Mahan) Date: 14 Nov 2003 14:50:18 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> Message-ID: <857b782c.0311141450.64916aea@posting.google.com> "Thomas Guettler" wrote in message > Me, too. I like python very much. But most people > who use computers since 1996 use either java, perl, C or bash. > > They know their language and don't want to change. > > One reason could be: python is too simple. If you write > code that nobody understands (perl) you are a guru. > thomas I think also that when people get paid per hour, the longer the project, the more they make. Subconsiously I think, people don't necessarily want computer languages that are written fast. Now, if you're a consultant and bill "for the job" then in fact it is in your best interest to use a language that can be written quickly to do a particular set of tasks. Chris Mahan From kurt at etool.com Mon Nov 3 17:16:09 2003 From: kurt at etool.com (Kurt) Date: 3 Nov 2003 14:16:09 -0800 Subject: Simple scipy question F-distribution Message-ID: Okay, This should be a really beginner question. I'd like to calculate the cutoff value for the F-distribution given for example F(x)=0.95 and m=2, n=9 which should be about 4.26. Is there an easy way to this in python with say scipy? Thanks! -kurt http://schwehr.org/ From dw-google.com at botanicus.net Sun Nov 9 18:49:35 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 9 Nov 2003 15:49:35 -0800 Subject: raw string from mmap.read() possible? References: Message-ID: <99dce321.0311091549.10e4962d@posting.google.com> Dan Jones wrote in message news:... > rgbframe = yuv.yuv2rgb(WIDTH, HEIGHT, "\0\0\0\0") > > but if I send it a raw string it doesn't complain: > > rgbframe = yuv.yuv2rgb(WIDTH, HEIGHT, r"\0\0\0\0") > > I'm assuming this is happening because C interprets NULL as the end of > the string. Is there a way to get a raw string directly from the > mmap.read() call or do I have to do a conversion after the read? I think you're suffering from a little confusion here: "\0\0\0\0" results in the byte sequence: 00 00 00 00 r"\0\0\0\0" results in the byte sequence: 5c 30 5c 30 5c 30 5c 30 This of course doesn't solve your problem, I know nothing about imaging in python. :P HTH, David. From fumanchu at amor.org Sun Nov 30 16:07:46 2003 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 30 Nov 2003 13:07:46 -0800 Subject: Need some advice Message-ID: Francis Avila wrote: > (That said, never use 'from x import y', ... Unless you're using packages. FuManChu From adalke at mindspring.com Sat Nov 8 08:16:52 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 08 Nov 2003 13:16:52 GMT Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> <2259b0e2.0311012219.73aa445f@posting.google.com> <55tgqvol2vmn2kn64tji81ooqlbpgq7ook@4ax.com> Message-ID: <816rb.2168$nz.725@newsread2.news.pas.earthlink.net> Stephen Horne > >>The brain really does change during sleep. In a way, you literally are > >>not the same person when you wake up as when you went to sleep. Some ways are more meaningful than others. I obviously breath, providing oxygen to burn parts of my body and thus provide energy to survive. Therefore I 'literally' am not the same person. Similarly, the me of time T experiences events which happened at time T-1, which the me of time T-2 does not know, so the state of my neurons and muscles have changed. Is that a useful of "me"? In some cases, yes. In most cases, no. > And yet consciousness itself changes dramatically, sometimes from > second to second, and we still feel a sense of continuity. > > How can we explain this sense of continuity? > > One way is to appeal to the 'god of the gaps' - to claim some > currently unknown entity which we cannot yet observe must provide the > real experience of consciousness. > > The other way is to look at the pragmatics of social behaviour. A huge > amount of social behaviour depends on that sense of continuity - that > feeling that (me today) == (me tomorrow) == (me yesterday). Only two ways? Perhaps there just are no gaps? Consider evolution. We do not have every fossil for every ancestor of, say, a horse, so there are always gaps in the record (what is the gap between you and your father?) But the prediction that there is something in between has fit nicely with both traditional cladistics and sequence-based phylogenies. Plus, you are shaking the wrong end of the stick. The opposite is likely more true; people have a strong sense of continuity so we have developed social structures which reflect that. If, for example, personalities were randomally exchanged during sleep then we would have ended up with a quite different culture. (I'm an avid science fiction reader but I can't recall a story built around this. There are stories where one or a small number of people change bodies, but not the whole culture. It would be even harder if the full personality of a body changed every day to a new one -- how would we, as personality-centered creatures, identify with a being which every day had a new personality? The closest I can think of is Vinge's packs in 'A Fire Upon the Deep', where the personality can change as pack members join and leave the pack, or Brin's ... the waxy ring people in the Uplift stories.. where each ring contributes to the full personality and, ahem, one ring can rule them all.) > Having a sense of continuity of self is, in other words, pretty > directly linked to the practical information processes involved in > maintaining a reputation and social status. Again, I'll argue it's the other way around. > Yes, and so long as you can keep your theory in the gaps and well away > from scientific probing, no-one can prove it wrong, can they? You suggested people fill in the gaps of consciousness. You said they exist because, for example, electrical stimulation of part of the brain would cause movement, and asking the person why that movement occurs would get a post hoc reason along the lines of "well, I wanted to move my arm." That doesn't necessarily mean that there was no consciousness, only that parts of actions are always not under direct conscious control. Stimulate my eye lids to blink and ask me why I blinked. I'll say "because my eyes were dry?" That doesn't mean that there was no sense of consciousness at that time. Or ask someone to stop tapping a pencil and that person might respond with "I'm sorry, I didn't realize I was doing that." Or when I drove across country along you might ask me what I did during that time and I'll repond "I don't remember; just zoned out." Was I not conscious during that time or did I simply decide it wasn't worth remembering? > Lets consider the 'alters' in multiple personality disorder. This has > been studied under a brain scanner. When alters switch, the activity > in the hippocampus changes dramatically. If the 'primary' personality > is active, the hippocampus is more active. This work is deeply conjectural. I have no training at all in the subject (err, I do know some of the theory behind brain scanning) but I just recently read a "Straight Dope" article http://www.straightdope.com/columns/031003.html which says Multiple personality disorder, now officially known as dissociative identity disorder (DID), remains the object of bitter controversy. One thing's clear, though--it's not nearly as common as people thought just a few years ago. ... The question remains: Are multiple personalities ever real? The debate still rages. Skeptics claim that alters are invariably induced by the therapist; the more respectable defenders of DID agree that many are, but not all. The controversy has been complicated by disagreement over the nature of personality. The common understanding of DID is that the alters are independent of one another and don't share memories and other cognitive processes, but demonstrating this has proven difficult. Speech and behavior are under conscious control, so changes can readily be faked. Even things like brain-wave patterns may vary not because of a genuine personality switch but because alleged alters cultivate different emotional states and different ways of acting out. (Note those last two lines ;) > Does this really satisfy your need for the mind to be something more > than information processing? One interpretation of Bengt's statements is that this higher-level structure may be modeled in its own right, like phonons, or Cooper pairs in supercondutors, or boolean logic gates created out of analog silicon with impurities, or the Great Red Spot on Jupiter. This doesn't make them 'something more', only something distinct. And there's no reason these can't be studied with an information processing model as well. (However, my reading suggests that his statements are too vague to know which interpretation is correct, and I'm leaning towards agreeing that he meant what you thought it to mean.) > The information processing theory can take MPD in its stride, of > course. If you keep your memories in several self-consistent but > distinct chunks then, even if the same neural machinery handles the > processing, you get a different 'self' by simply switching which sets > of memories are active. But if MPD really is as rare as Uncle Cecil says, then informational processing theory is not a useful *predictor* of human behaviour, because it makes no statements about the likelyhood of a given event. Why don't I have acraphobia today, arachnaphobia tomorrow, and agoraphobia the next? Why doesn't everyone have strong MPD? And a requirement for being a useful theory is that it be able to make predictions. (Off this off-topic thread; in 'Call of Cthulhu' as I recall there was a Latinate word for 'the fear that gravity would reverse'. I can't find a reference to it. Any pointers?) > Basically, as I said before, you seem to be appealing to the 'god of > the gaps'. You find the idea of the mind as an information processor > unapalatable, but - as with many people who claim not to be religious > per se - you don't want to appeal to an actual god or soul. So instead > you appeal to an undiscovered type of physics. Suppose some day there is artificial intellegence which requires so much computer power that it takes in 1 second of input then spends 10 minutes processing it. That makes for very large gaps. >From an information processing model, these gaps do not exist because time does not come into play in those models (that I've seen). But it does occur and does not require a 'god of the gaps'. (Again, I suspect that I am arguing a different viewpoint than Bengt.) > Can I explain why people shouldn't be comfortable with being a part of > the physical world, and of having minds that are explainable in > information processing terms? Obviously there's the sense of agency > and illusion of free will, but while they might explain a > misinterpretation they don't explain a continuing strong conviction, > so what else? What's information? The definitions I know of come from Shannon, the definition of entropy in thermodynamics, and the surface area of the event horizon of a black hole, and as I recall it's philosophically appropriate to wonder if (or that) they are the same thing. How then do you turn these definitions into a useful model for intelligence? I suspect you do so by first assuming a boolean algebra. It requires a lot of entropy to process one bit (because of the need for certainty), so you are already using a higher level approximation of the underlying physics. And as Michele pointed out, some things can be explained well with a higher level field equation which does not accurately model the smaller scale behaviour. > There is a concept called the 'expanding circle' which relates to who > is and who is not considered a 'person'. I put that in quotes because > it is far from literal - humans are often excluded, and (particularly > in modern times) animals etc are very often included. > > Basically, it refers to an intuitive sense of who has rights, who you > can empathise with, etc. When you can torture and kill 'the enemy' > without being traumatised yourself (assuming you are not simply a > sociopath) it is a clear sign that 'the enemy' are outside of your > circle, for instance. It is difficult for me to throw a book away, break its spine, or otherwise destroy it. I wanted to get rid of a few and ended up telling a friend of mine to do it for me, because I couldn't do it myself. These books were given to me by family, but I was not going to reread them. Does that make the books a 'person'? Does that extend my relative's personhood into my books? Suppose someone it told to destroy a work of art which took that person 10 years of devotion to create. It's likely that that would cause trauma. Does that make the work of art a person to that artist? > This intuitive sense has clear practical evolutionary value - being > willing to kill others in your tribe without batting an eyelid would > obviously not suit a social species, yet it would be hard to carry out > intertribal warfare if you empathised with your enemies. And this is > complicated by the fact that it seems tribes did make both short and > longer term alliances - you couldn't rely on an individual being a > stranger, but needed to make more flexible classifications. You have a naive view of what sociobiology might do, biased no doubt by being brought up in this culture. The restriction for 'survival of the fittest' is to increase the chances that your genes will be propogated. There's no reason that cannot happen in a social species. Newly dominant gorillas, as I recall, will kill the infants which aren't his. (No references though; I should reread my Gould books.) And in Jared Diamond's "Guns, Germs and Steel" he mentioned a woman he met in New Guinea, from a tribe only recently out of the hunter/gather stage whose 2nd husband was killed by his brother, so that he could be her 3rd husband. Or consider Shakespeare's McBeth, where the king's brother killed the king to become the new king. We don't immediately and instinctively reject that as condition which cannot occur under human relationships, meaning that it isn't prohibited by a million years of Darwinistic evolution. Consider the Medici or Borgia families, or for that matter much of the ruling Europeans. Just how many of them died from the hand of family than from outsiders. (Or consider Prince Caspian from the Narnia book of the same name. :) Wild dogs are social creatures. This page http://www.szgdocent.org/aa/a-wildog.htm says that "wounded members have been known to be killed by their pack" which is in contradiction to your direct statement that "being willing to kill others in your tribe without batting an eyelid would obviously not suit a social species." In the Bible, Abraham almost sacrificed his son Isaac, http://en.wikipedia.org/wiki/Near_sacrifice_of_Isaac and of course Cain killed his brother Abel. There are plenty of cases where one family member killed another, making it hard to argue that the prohibition comes from evolutionary reasons. Plus, as a male it is evolutionary advantageous to impregnate non-tribal women instead of killing them, so you'll need to modify that clause as well. > This isn't the only intuitive classification the mind makes, of > course. There appear to be clear intuitive distinctions between > animals, plants, and inanimate objects for instance. These > distinctions seem to be innate and instinctive, though there is > flexibility in them. That's very culturally biased. Consider some Native American languages which have different conjugations for things which are alive vs. things which are not. (I think Navajo is one such.) As I recall, clouds are alive. In any case, that intuition breaks down because some things are not animals, not plants, and not inanimate. Eg, for living things we must also include bacteria and archeobacteria, there's also viruses in the grey area. For animate vs. inanimate, when does an animate volcano become an inanimate mountain? Is the Moon animate? What about a waterfall? A tornado? > If these are general intuitive principles, it is no surprise that when > you introspect you find it hard to accept that your mind is not > distinct from an information processing machine. Your mind naturally > classifies your self in the intuitive category of 'person'. Again, a culture bias. It's hard for many people to accept that they are animals, or that humans and other hominds had a common ancestor. Yet so far there is much more evidence for evolution than there is that an "information processing theory" gives a similarly useful model for understanding the brain. To expand upon that, as a good reductionist and (ex-)physicist, I think in principle the human body, including the brain, can be modeled from first principles using quantum mechanics. However, that cannot be done in realistic time so we must use approximations, and those approximations may be extremely good (as in 99.99%+) because the higher levels have an appropriate 'field theory'. Eg, weather prediction doesn't require an atomic theory. You have postulated such an "information processing theory" but not stated what that theory means .. and given yourself an out by saying that it can be expanded to include new behaviour. Without explanation, it's hard to judge if your idea is correct or not. Without explanation, I can see that "information processing theory" is identical to the laws of thermodynmics (where entropy == information) and then point out that you are omitting many parts of physics, > Basically, it would be surprising if most people didn't resist the > idea of being, in principle, little different to a computer. Basically, it would be surprising if most people didn't resist the idea of being, in principle, little different to another person. Or little different to a bonobo monkey, or little different than a dog, or little different to yeast. But under some definitions these are little enough. > As for me, well perhaps those classification systems don't work so > well in people with autism spectrum disorders. Maybe that is why we > are overliteral in applying moral rules as well as other areas - we > don't really have the same intuitive sense that everyone else has of > the differences in how people, animals and inanimate objects should be > treated. But those classifications systems are invalid, and the determination of the boundaries between classes are culturally determined. (Hence the rejection of the idea of a platypus when it was first presented in Europe, but the full acceptance of it now) I suspect it's more a matter of not knowing enough about animal behaviour and evolutionary biology. You may want to read some of the Gould books. There are several others I could suggest, but it's been about 10-15 years since I read them and I can't recall them now. > Maybe that is a part of the 'theory of mind' issue. That's too, but you are using evoluationary arguments and need a better background in evolution both theoretical and as observed. (Eg, insects pull off just about every evolutionary trick in the book, and bacteria can pull off almost all of the rest. Humans, though, have learned a few new ones ;) > So when I introspect, it doesn't particularly bother me to see myself > as a (broken) machine designed and built to carry genes from one > generation to the next, and neither does it particularly bother me to > see my mind and consciousness as a product of information processing. "A chicken is an egg's way of making more eggs." Again, the problem with both those views is that they don't provide much predictive power. I have no problems seeing myself as a self-organized meta-stable collection of atoms living in a collapsing wave function, but for just about everything I do that knowledge doesn't help me much. Oh, and the definition of "broken" in an evolutionary sense means your genes aren't passed on -- even if you don't have children, if you help ensure that two or more of your nieces and nephews do reproduce then you are an evolutionary success. Plus, you should drop the "designed" because that implies a designer. Saying "as a machine to carry genes" would be just fine. > To put it another way, when looking at a picture you may feel that you > are aware of the whole picture, but you are not. Big changes can be > made to the picture without you noticing, as long as they don't effect > the precise detail that you are focussing on at that precise moment. > It is called change blindness. Here's a neat Javas-based demo of change blindness. http://www.usd.edu/psyc301/ChangeBlindness.htm One of them (with the sphinx) I got right away. Another, with the couple eating dinner, I didn't get even though I was looking at the spot that change -- I just though "something changed... but what?" And with the cemetary one I figured it out because the scene was wrong. But why deal with change blindness? Close one eye. Do you see your blind spot? (I spent hours in high school practicing to see it. I think I annoy optomitrists when I say 'and now the pointer has entered my blind spot' ;) > A big part of the sense that something is 'conscious' is actually > illusory in itself - things that can be immediately brought into > consciousness tend to be classified by the mind as currently conscious > because, in the practical sense, they may as well be. So with change > blindness, you 'experience' the whole picture mainly because you > intuitively know that you can focus on any part of it in an instant. What you say doesn't necessarily follow from that. Consider this image processing model. The eye does image processing which is not under direct conscious control. This reduces the scene into a simplified model, and access the brain's internal model of how things should be to fill in details, like fill in the blind spot. We do have some ability to influence things, but it isn't under full control. We are conscious of this model, but don't realize that it's only an approximation to the actual data coming in. Isn't this just as valid as your description, but leading to a different conclusion? (What I did here was pull a Chinese room on the problem, and redefine that consiousness takes place after image processing. Personally I'm fine with saying that part of my consciousness exists at times even outside my head, as with a dog to wake me up if there are intruders, or even other people, to provide insight I find hard on my own.) > The 'whole soup experience' is basically an illusion, or maybe a > 'collective noun' for the lower level perceptions that you had (or > didn't have) while eating the soup. A problem I have with your definition is that you can say "illusion" but have no way to define what is anything besides an illusion. That makes the word useless in terms of descriptive power, and could just as easily use the word "interpretation", which doesn't have the connotations that it's false. Plus, if you push "illusion" too much you end up in solipsism, which is just plain boring. > Pick up a pencil and run it over a rough surface. Most people will > quite quickly start experiencing the bumps as being at the tip of the > pencil, as if the pencil were an extension of the body. > > Phantom limbs also have some significance to this. The pencil *is* an extension of the body, no? So is putting gloves on. Or driving a car. I'm having a problem with your use of the phrase "as if". In your list of significance, consider also prosthetic limbs, and limbs which have "fallen asleep." > Basically, there is nothing here which I don't see as information > processing. What in the universe *don't* you consider as information processing? Why not? Eg, if information is entropy then everything in the Universe is information processing, meaning your model has no more predictive power than thermodynamics. > You might like to read some Rita Carter stuff - this is my easiest > reference because, as I mentioned before, I'm currently reading her > book "consciousness". Based on the statements you've made, I have distrust in what you've been reading, or at least your interpretation of that data. So I was biased in my search and found a page critical of one of her books, at http://human-brain.org/mapping.html It says of her some of the same things I've complained about here, like a problem with definitions, and a tendency to give only one interpretation when many are possible and equally likely. This may be okay for a general science book, on the justification that it provides a possible world view, but it doesn't mean that that's correct. (Ain't 2nd hand put downs fun? :) > Body language is quite distinct from the kind of gesture that occurs > in sign language. As I understand it, most body language is not > generated by Brocas area. I personally don't know. I know evolution much better than I do neural models. Google found http://cogweb.ucla.edu/ep/GestureLanguage.html ] Brain imaging has shown that a region called Broca's area, which ] is important for speech production, is active not only when we ] speak, but when we wave our hands. Conversely, motor and ] premotor areas are activated by language tasks even when those ] tasks have been robbed of their motor aspect--during silent ] reading, for instance--and particularly by words that have a ] strong gestural component, such as verbs and tool names. ] ] Impairments of language and coordination are closely related, ] too. People with a condition called Broca's aphasia can put ] names to things but have trouble stringing sentences together. ] They show similarly impoverished gestures, indulging less in ] hand movements that relate to the flow or rhythm of the ] accompanying speech than to those that convey its content. > Also, the use of muscles isn't what this is about. Even when you here > a word, or think about the concept, your brain generates the > associated action potentials - but inhibits the actual muscular > actions. As far as I can tell, you haven't said what an 'action potential' is. I assumed it was something related to synapse signalling, which the brain must do to work. Now it appears to be something else because some words, like "star" or "python programming language" or "tastes of anise" have no corresponding muscular actions. > >>This makes good sense. Evolution always works by modifying and > >>extending what it already has. The mental 'vocabulary' has always been > >>in terms of the bodily inputs and outputs, so as the capacity for more > > >"Always" is a way to prune your thought tree. Careful ;-) > > It is also very much the right word in this case. Sophisticated useful > abilities in complex organisms do not arise through fluke mutations, > much as broken fragments of china do not suddenly join themselves into > a perfect vase and leap up onto your wobbly shelf. It's called the law > of entropy. There are too many things going on here. First, assume the Universe is a closed system. Evolution works in the Universe, so of course it always 'modifies and extends' things in the Universe -- it cannot do otherwise. Second, 'it' can mean a single organism or species, when things like gene transfer between bacteria show that evolution doesn't quite fit that nice categorization. Third, 'evolution' doesn't modify things, things like errors during {D,R}NA copying, chemical mutagens, and radation modify things. Evolution describes how the local ecological landscape can have different effects on the different mutations can cause speciation or extinction. This is less personified than you use. And finally, YES MOST DEFINITELY "sophisticated useful abilities in complex organisms DO arise through fluke mutations." THAT IS A FUNDAMENTAL IDEA OF EVOLUTIONARY THEORY! Random mutations + ecological pressures => evolution The reference to entropy (by which you likely mean the second law of thermodynamics) is for a closed system and a TOTALLY INAPPROPRIATE METAPHOR. Locally we have this thing called the Sun, which makes the Earth be an open system. (My apologies for the yelling, but I wanted to get my point across that what you said was absolutely counter to evolutionary theory.) > Evolution doesn't throw away what it already has and start again from > scratch. It seeks local maxima - it cannot anticipate long term > advantages. Stop anthropomorphising. Abilities are definitely lost due to evolution, unless you can indeed breath underwater? As to "start again from scratch", I don't know enough give a good example, but what about dolphins? They like us were derived from a fish, but lost many of the sea going abilities of a fish, which have now been regained. It cannot be that these were all done in the same way, because dolphins are not fish, and it's almost certain that there was parallel evolution for some of the traits. (I also seem to recall some legless lizards first losing then regaining then losing legs, but again I don't know enough of the details.) What to you would qualify as "starting from scratch"? Here's one theoretical model: the parent has gene X which undergoes a gene duplication event, so there are now two copies of X. X is important so one of those genes remains unmodified while the other is free to mutate into Y. While once useful, Y is no longer needed, and when a retrovirus comes in it inserts itself into Y with no ill effects. Conditions change again so that the X->Y transition is helpful and prefered. During that time, X undergoes another duplication event and the new X is free to follow evolutionary pressures to be a new version of Y. I see no reason this couldn't happen, and it's exactly the case where a gene was thrown away then recreated. Andrew dalke at dalkescientific.com From andrew-pythonlist at puzzling.org Mon Nov 17 19:44:24 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 18 Nov 2003 11:44:24 +1100 Subject: Too much builtins (was Re: Python's simplicity philosophy In-Reply-To: References: <653b7547.0311112220.2b2352e7@posting.google.com> <653b7547.0311121826.65b6b2d4@posting.google.com> Message-ID: <20031118004424.GA12240@frobozz> On Mon, Nov 17, 2003 at 02:55:11PM +0000, Alex Martelli wrote: > Terry Reedy wrote: > > >> len > > unless made a method, keep in > > A method of every sequence and container on Earth? Eeek. Like __len__, you mean? -Andrew. From buzzard at urubu.freeserve.co.uk Thu Nov 20 10:10:54 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Thu, 20 Nov 2003 15:10:54 -0000 Subject: Props to numpy programmers! References: <9ed149b8.0311191728.117b4566@posting.google.com> Message-ID: "Andrew Felch" wrote in message news:9ed149b8.0311191728.117b4566 at posting.google.com... > So I wanted to matrixmultiply > > [[a,b], > [c,d]] > > * > > [e,f] > > Of course this is impossible, because the number of columns in the > first factor is not equal to the number of rows in the second. Wrong! > It is impossible because the second matrix is rank1! So numpy > happily converts it to a column vector so the multiplication will > work, and converts the answer back into a rank1 vector!!!! > > I love NUMPY!!!!!!!!!!! > > I was reading my code and thought I had a bug, I couldn't figure out > why the code was still working right! It's because the numpy people > are geniouses! > > Hooray numpy!!!!!!!!!! Numpy is smarter than me! I love Numpy too. But I wouldn't want this multiplication to work if the second array was a row vector (and there's no explicit distinction because of the array's shape). >>> a array([[0, 1], [2, 3]]) >>> b array([4, 5]) >>> Numeric.matrixmultiply(a,b) array([ 5, 23]) >>> Numeric.matrixmultiply(b,a) array([10, 19]) One of these multiplications should fail, depending on whether b is a column or row vector. Make it a column vector by reshaping, >>> b = Numeric.reshape(b, (2,1)) >>> b array([[4], [5]]) and it does the right thing. >>> Numeric.matrixmultiply(a,b) array([[ 5], [23]]) >>> Numeric.matrixmultiply(b,a) Traceback (most recent call last): File "", line 1, in -toplevel- Numeric.matrixmultiply(b,a) File "C:\Python23\lib\site-packages\Numeric\Numeric.py", line 335, in dot return multiarray.matrixproduct(a, b) ValueError: matrices are not aligned >>> Much safer IMHO. Duncan From nomail at hursley.ibm.com Thu Nov 20 23:04:30 2003 From: nomail at hursley.ibm.com (Derek Fountain) Date: Fri, 21 Nov 2003 12:04:30 +0800 Subject: Details on exceptions References: <3fbd7509$0$1749$5a62ac22@freenews.iinet.net.au> <3fbd7c7c$0$1746$5a62ac22@freenews.iinet.net.au> Message-ID: <3fbd8e56$0$1755$5a62ac22@freenews.iinet.net.au> > Actually, that's the back end: except is part of the try: except: syntax, > and the second argument is extracting things from the exception > object. > > They were put there originally either by the routine that created the > exception object, or by the raise statement. One thing you may be > missing is that an exception object is no different from any other > object, and the creator can stuff any attributes into it that it wants. No, I got the "exception is just an object idea". What I don't understand is the assignment of a tuple in the except clause. I thought the thing after the exception name is an optional variable name to assign a reference to the exception object to. The O'Reilly Nutshell book says "The optional target is an identifier that names a variable that Python binds to the exception object just before the exception handler executes". This doesn't make sense in this case: except IOError, (errno, strerror): The target is a tuple of 2 variable names so how can it bind "the exception object" to them? The documentation for try/except says that "the exception's parameter is assigned to the target". So what, exactly, is an "exception's parameter"? From daniels at dsl-only.net Fri Nov 14 09:51:33 2003 From: daniels at dsl-only.net (sdd) Date: Fri, 14 Nov 2003 06:51:33 -0800 Subject: Access sql with python, please. I'm desperate In-Reply-To: References: <3fb31f7a$1@nntp0.pdx.net> <3fb46bdc$1@nntp0.pdx.net> <3fb472b5$1@nntp0.pdx.net> Message-ID: <3fb4f9e7$1@nntp0.pdx.net> Alex Martelli wrote: > sdd wrote: >> SELECT * FROM (SELECT age, weight FROM personnel) >> WHERE age IN (SELECT age FROM retirees) > > ...I'm not sure why you want the FIRST of the two nestings here -- > why not just one nesting, as in: > SELECT age, weight FROM personnel > WHERE age in (SELECT age FROM retirees) > ? There is no value to the nesting; I was simply trying to echo the pattern the original poster's nested query in a syntactically correct way. The fillip was in adding the plausibly reasonable second subquery. -Scott David Daniels Scott.Daniels at Acm.Org From leroybt at rocketmail.com Wed Nov 26 13:40:05 2003 From: leroybt at rocketmail.com (leroybt.rm) Date: Wed, 26 Nov 2003 18:40:05 -0000 Subject: Shell: run script Message-ID: Can someone tell me how to run a script from a interactive shell I type the following: >>>python filename >>>python filename.py >>>run filename >>>run filename.py >>>/run filename >>>/run filename.py and in all cases I get errors. I can't believe I can not run a script from the shell. What am I doing wrong????? Help!!!!!!!!! From __peter__ at web.de Wed Nov 19 05:38:37 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Nov 2003 11:38:37 +0100 Subject: logging: repeated messages References: Message-ID: Peter Otten wrote: > How about (untested): > > def log(level, message, data=[]): > if len(data) == 0: > logging.basicConfig() > logger = loggin.getLogger('name') > hdlr = logging.StreamHandler() > hdlr.setLevel(logging.WARN) > logger.addHandler(hdlr) > data.append(hdlr) Oops, no need to store the StreamHandler, if data: ... data.append(1) should have the same effect. As you don't use the newly created handler in subsequent calls, I would recommend to move the code inside the if statement into another function that is only called once at startup. Peter From mark at hahnca.com Wed Nov 26 14:16:36 2003 From: mark at hahnca.com (Mark Hahn) Date: Wed, 26 Nov 2003 11:16:36 -0800 Subject: Is there a .tolower() for a string?? References: <7b1fa3cb.0311261057.ecb7325@posting.google.com> Message-ID: > I have a string say > > a = "Hello how are YOU" > > I want to end up with > > a = "hello how are you' > > Isn't there a built in method for changing a string to lowercase? > >>> 'aBc'.lower() 'abc' From suzuki611 at oki.com Mon Nov 17 02:55:29 2003 From: suzuki611 at oki.com (SUZUKI Hisao) Date: Mon, 17 Nov 2003 16:55:29 +0900 Subject: Python's simplicity philosophy In-Reply-To: References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <653b7547.0311121826.65b6b2d4@posting.google.com> Message-ID: <3FB87EF1.2050407@oki.com> All in all, I agree with you. You have pointed out precisely what has been making Python more attractive than, say, Perl. In , you, Douglas Alan, wrote: > The argument that some programmers might be too lazy to want to learn > powerful, simple, and elegant features that can be taught in seconds, > is no good reason to remove such features from Python and bloat Python > by replacing them with a plethora of less powerful, less elegant > features. In , you also wrote: > I like Python because it is a very simple, generic, easy-to-learn > programming language, where I didn't have to learn much of anything > new. It was just like all the other myriad of programming > languages I have programmed in, only less cluttered than most, and > "light-weight" in its implementation and accessibility. So do I. As to sum(), when learning string addition (concatenation), one may wonder why sum() does not handle it: >>> sum(['a', 'b', 'c']) Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for +: 'int' and 'str' while general reduce() does it just as _expected_: >>> reduce(str.__add__, ['a', 'b', 'c']) 'abc' It may be sum() that is more difficult to learn... For this particular problem, it is better to use ''.join(['a', 'b', 'c']), you know. However, it is important for Python to have an easy and generic way to do things. If we have to read the manual through to solve anything, what is the point to use Python instead of Perl (or Ruby, to some extent)? > I having nothing against learning new stuff, by the way, but when I > want to learn new stuff, I'm not particularly interested in the > idiosyncrasies of Python -- I'd spend my effort learning something a > bit more exotic, like OCaml, or Haskell, that might stretch my brain a > bit. Learning a bunch of idiosyncratic detail is just tedious. This > is one of the most important reasons that Perl sucks so badly. Again in > And as I have pointed out, it goes against the principle of simplicity > and expressiveness to remove an easy to use and easy to learn simple > and powerful feature with a slew of specific, tailored features. If > reduce() can be relegated to a library or for the user to implement > for himself, then so can sum(). If the language is to only have one, > it should be reduce(). I agree with you. However, It may be better to give reduce() some nice notation. Someone (sorry, but I do not remember) suggested such one: [s: s+c for c in ['a', 'b', 'c']] or [s='': s+c for c in ['a', 'b', 'c']] though it may not be the nicest. -- SUZUKI Hisao From peter at engcorp.com Wed Nov 26 00:23:06 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 Nov 2003 00:23:06 -0500 Subject: Creating a Python installer in win32 References: <2XVwb.40137$Fv8.32356@twister01.bloor.is.net.cable.rogers.com> Message-ID: <3FC438BA.EBD59EC9@engcorp.com> martin z wrote: > > Hey, all. I'll get to the point: project for class, got most of my needs > figured out, just unsure about one detail: this is a large-scale design > course, so it has to be a complete win32 app. That means a standalone > installer. I can't just say "go fetch Python, then run this .py file". > Anybody know how to set such a thing up? Py2exe plus any freely available installer (InnoSetup?) does the job. -Peter From jbublitzno at spamnwinternet.com Sun Nov 9 15:45:41 2003 From: jbublitzno at spamnwinternet.com (Jim Bublitz) Date: Sun, 09 Nov 2003 20:45:41 GMT Subject: ANN: PyKDE now does KDE plugins References: <87sml01hgc.fsf@pobox.com> <87llqrgiva.fsf@pobox.com> <9y9rb.3612$xr.997430341@twister2.starband.net> <87wuaainlg.fsf@pobox.com> <6Ilrb.3754$yd6.1052428423@twister2.starband.net> <87oevlfqye.fsf@pobox.com> Message-ID: John J. Lee wrote: > Jim Bublitz writes: >> John J. Lee wrote: >> >> > Have you seen GCC-XML and pyste (part of Boost Python)? >> I've looked at both just out of curiousity, but not in enough >> detail to say anything intelligent about either. I'm very >> comfortable with sip, and from that bias didn't see anything >> that would make me want to switch methods. > [...] > I was thinking of it as a way to generate sip files, not to > replace sip. Wouldn't work for me (directly). I need an intermediate format for both the h files AND the previous version's sip files to generate the new version's sip files. I need to read in PyQt's sip files too. That's both for versioning (change detection) and to transfer forward any handwritten code, doc markup, ignored methods (like the "virtualHook" stuff that's everywhere in KDE), auxiliary code like mapped types, etc. The same parser builds a symbol table for each set of files (the other two above wouldn't handle sip syntax) and then merges the two symbol tables and spits out the sip files. I also need to build some kind of hierarchy so I can scope names - sip needs fully-qualified names in a lot of places C++ will allow implicit scope (eg namespaces). It took me 8-10 hours to do just scoping manually last time I did it that way - the whole KDE generation run takes 2-3 minutes now (everything except new handwritten code that's needed, and those are flagged). Jim From bokr at oz.net Sat Nov 29 18:03:37 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Nov 2003 23:03:37 GMT Subject: Graph algorithms - DFS, generators callbacks, and optimisation References: Message-ID: On Sat, 29 Nov 2003 10:54:49 +0000, Paul Moore wrote: >I'm trying to check a graph (represented in the usual Python adjacency >list format) for loops. This is dead simple - you use a depth-first >search, and look out for "back edges" (edges from a vertex "back" to >one you've already seen). > >I already have a DFS algorithm which generates each edge in turn. It's >great for what it does, but it ignores back edges. > >def DFS(graph, start, seen = None): > if not seen: > seen = {start: 1} > for v in graph[start]: > if v not in seen: > seen[v] = 1 > yield start, v > if v in graph: > for e in DFS(graph, v, seen): > yield e > >I could code a variation on this, just for this one problem, but that >sort of cut and paste coding offends me (and DFS is *just* fiddly >enough that I'm not confident of getting it right each time I >reimplement it). So what I'd rather do is enhance my existing code to >be a bit more general. > Not very tested, but how about (borrowing Robin's example data): ====< PaulMoore.py >============================================= def DFS2(graph, start, rlevel=0, seen = None): if seen is None: seen = {} seen[start] = 1 # allow for jumping into arbitrary subtrees with # same seen dict in new generator ? for v in graph[start]: is_back = v in seen seen[v] = True # ok if redundant yield (start, v), is_back, rlevel if not is_back: if v in graph: for e in DFS2(graph, v, rlevel+1, seen): yield e if __name__ == '__main__': G = { 1: (2,3), 2: (3,5), 3: (4,), 4: (6,), 5: (2,6), 6: (1,), } for e, is_back, level in DFS2(G, 1): print '%s%s -> %s%s' %(level*' ',e[0], e[1], ('',' (back)')[is_back]) ================================================================= The output is: [15:15] C:\pywk\clp>PaulMoore.py 1 -> 2 2 -> 3 3 -> 4 4 -> 6 6 -> 1 (back) 2 -> 5 5 -> 2 (back) 5 -> 6 (back) 1 -> 3 (back) > >Can anybody think of a good way of making the DFS code above a little >more generic, without losing the efficient and simple (from the >caller's POV) approach of the current version? > My .02 above ;-) Regards, Bengt Richter From adalke at mindspring.com Sat Nov 1 12:39:54 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 01 Nov 2003 17:39:54 GMT Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <8nlnpvcsgodtmlpfng7rtf27r1s7hi56ph@4ax.com> <87d6cjope5.fsf@pobox.com> <87he1vsopi.fsf@pobox.com> <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> Message-ID: Anton Vredegoor" : > The more territory modern science covers, the more it becomes clear > that the known parts of the universe are only a small part of what is > "out there". But as Stephen pointed out, the new things we find are new in terms of arrangement but still following the same laws of physics we see here on Earth. (There *may* be some slight changes in cosmological constants over the last dozen billion years, but I haven't followed that subject.) These arrangements may be beyond our ability to model well, but there's little to suggest that in principle they couldn't be. (Eg, QCD could be used to model the weather on Jupiter, if only we had a currently almost inconceivably powerful computer. Running Python. ;) > So "objectively" science gains more knowledge, but > relatively speaking (seeing it as a percentage of that what is > currently known to be not known, but knowable in principle) science is > loosing ground fast. Also an even greater area of the universe is > supposed to exist that we will not even have a chance *ever* to know > anything about. That's a strange measure: what we know vs. what we know we don't know. Consider physics back in the late 1800s. They could write equations for many aspects of electricity and magnetism, but there were problems, like the 'ultraviolet catastrophe'. Did they consider those only minor gaps in knowledge or huge, gaping chasms best stuck in a corner and ignored? Is the gap between QCD and general relativity as big? Hmmmm... > Trough out the centuries there has been evidence placing humanity > firmly *not* in the center of the universe. First the earth was proven > to rotate around the sun and not the other way around, next our sun > was not in the center of the galaxy and so on. You use this as an argument for insignificance. I use it to show that the idea of "center of" is a meaningless term. If I want, I can consider my house as the center of the universe. I can still make predictions about the motion of the planets, and they will be exactly as accurate as using a sun-centered model. The only difference is that my equations will be a bit more complicated. > Maybe now it is time to accept the fact that all the things we know > taken together are only a small fraction of what can be known, and > even more that that fraction is not even in a central position in the > larger universe of the knowable, and that the knowable is just > disappearingly small compared to the great abyss of the unknowable > where everything is embedded in. Why? I mean, it's true, but it seems that some knowledge is more useful than others. It's true because even if there were a quadrillion people, each one would be different, with a unique arrangement of thoughts and perceptions and a unique bit of knowledge unknowable to you. > How come then that the sciences have been so uncanningly effective > given that they are such an arbitrary choice within the knowable? The > answer is of course that there are a lot of other possible sciences, > completely unrelated to our own that would have been just as effective > as -or even more effective than- our current sciences, had they been > pursued with equal persistence during the same amount of time over a > lot of generations. I don't follow your argument that this occurs "of course." It's not for a dearth of ideas. Humans did try other possible sciences over the last few millenia. Despite centuries of effort, alchemy never became more than a descriptive science, and despite millenia of attempts, animal sacrifices never improved crop yields, and reading goat entrails didn't yield any better weather predictions. On the other hand, there are different but equivalent ways to express known physics. For example, Hamiltonian and Newtonian mechanics, or matrix vs. wave forms of classical quantum mechanics. These are alternative ways to express the same physics, and some are easier to use for a given problem than another. Just like a sun-centered system is easier for some calculations than a "my house" centered one. On the third hand, there are new theoretical models, like string theory, which are different than the models we use. But they are not "completely unrelated" and yield our standard models given suitable approximations. On the fourth hand, Wolfram argues that cellular automata provide such a new way of doing science as you argue. But my intuition (brainw^Wtrained as it is by the current scientific viewpoint) doesn't agree. > The effectiveness of the current natural sciences is a perceptual > artifact caused by our biased history. From a lot of different > directions messages are coming in now, all saying more or less the > same: "If asking certain questions, one gets answers to these > questions in a certain way, but if asking different questions one gets > different answers, sometimes even contradicting the answers to the > other questions". > > This might seem mystic or strange but one can see these things > everywhere, if one asks that kind of questions :-) Or it means that asking those questions is meaningless. What's the charge of an electron? The bare point charge is surrounded by a swarm of virtual particles, each with its own swarm. If you work it out using higher and higher levels of approximation you'll end up with different, non-converging answers, and if you continue it onwards you'll get infinite energies. But given a fixed approximation you'll find you can make predictions just fine, and using mathematical tricks like renormalization, the inifinities cancel. For a simpler case .. what is the center of the universe? All locations are equally correct. Is it mystic then that there can be multiple different answers or is simply that the question isn't well defined? > One example would be the role the observer plays in quantum mechanics, > but something closer to a programmer would be the way static or > dynamic typing influence the way one thinks about designing a computer > program. The latter argument was an analogy that the tools (formalisms) affect the shape of science. With that I have no disagreement. The science we do now is affected by the existance of computers. But that's because no one without computers would work on, say, fluid dynamics simulations requiring trillions of calculations. It's not because the science is fundamentally different. And I don't see how the reference to QM affects the argument. Then again, I've no problems living in a collapsing wave function. > In a certain sense all science reduces the world to a view of it that > leaves out more than that it describes, but that doesn't preclude it > being effective. For a last example, what about the mathematics of > curved surfaces? Sciences have had most of their successes using > computations based on straight lines, and only recently the power of > curves is discovered as being equal or more predictive than linear > approaches. Yes, a model is a reduced representation. The orbit of Mars can be predicted pretty well without knowing the location of every rock on it surface. The argument is that knowing more of the details (and having the ability to do the additional calculations) only improves the accuracy. And much of the training in science is in learning how to make those approximations and recognize what is interesting in the morass of details. As for "straight lines". I don't follow your meaning. Orbits have been treated as curves since, well, since before Ptolomy (who used circles) or since Kepler (using ellipses), and Newton was using parabolas for trajectories in the 1600s, and Einstein described curved space-time a century ago. > Abstractness doesn't preclude effectiveness, but to try to use > abstractions to understand the world is foolish since it doesn't work > the other way around. You have a strange definition of "effectiveness." I think a science is effective when it helps understand the world. The other solution is to know everything about everything, and, well, I don't know about you but my brain is finite. While I can remember a few abstractions, I am not omnipotent. Andrew dalke at dalkescientific.com From peter at engcorp.com Mon Nov 10 10:15:57 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Nov 2003 10:15:57 -0500 Subject: win32.com problem to unprotect a word document References: <48bafd6d.0311100646.687f043d@posting.google.com> Message-ID: <3FAFABAD.5F9DB608@engcorp.com> Christian Lehmann wrote: > > I?m trying to unprotect a word document with python for reading all form fields. > But it doesn?t work. > > Here?s a simple code sample: > > wordapp = win32com.client.Dispatch("Word.Application") > docfile = wordapp.Documents.Open(file) > > protecttype = docfile.ProtectionType # protected delivers 2 > docfile.Unprotect > protecttype = docfile.ProtectionType # anyway 2 > > # do some work > > docfile.Protect > protecttype = docfile.ProtectionType # anyway 2 > > So someone please tell me, whats my fault? Is it possible you should actually be *calling* Unprotect and Protect, instead of just retrieving their values? To do that, make sure you include the parentheses as in docfile.Unprotect() Python is not VB... -Peter From jfranz at neurokode.com Wed Nov 12 20:19:24 2003 From: jfranz at neurokode.com (Jon Franz) Date: Wed, 12 Nov 2003 20:19:24 -0500 Subject: Access sql with python, please. I'm desperate References: Message-ID: <005501c3a984$2cc808b0$7401a8c0@voidmk9> Have you tried using the adodbapi module? It wraps ADO on win32 platforms, and exposes the DBAPI 2.0 spec, thus you can use the same sort of calls as you did using MySQLdb. See: http://adodbapi.sourceforge.net/ If you still want to go the COM route, I'd suggest at least using ADO and not DAO. ~Jon Franz NeuroKode Labs, LLC ----- Original Message ----- From: "DD" To: Sent: Wednesday, November 12, 2003 6:07 PM Subject: Access sql with python, please. I'm desperate > Hello, > > Could anyone please help me?? > Is there somebody who could explain me how to make a connection to a access > database with a python cgi script. > I would like to use common sql commands in my python scripts as I can with > MySQLdb. > But I cannot even connect to the access database (see below). > Could anyone explain it to me as simple as possible please. I'm using > Windows XP, ActivePython 2.3.2 build 230 and Microsoft access(XP?) > I normally use Linux, but this has to be in MS office > > >>> import win32api > >>> import win32com.client > >>> engine = win32com.client.Dispatch("DAO.DBEngine.35") > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python23\Lib\site-packages\win32com\client\__init__.py", line 95, > in Dispatch > dispatch, userName = > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) > File "C:\Python23\Lib\site-packages\win32com\client\dynamic.py", line 84, > in _GetGoodDispatchAndUserName > return (_GetGoodDispatch(IDispatch, clsctx), userName) > File "C:\Python23\Lib\site-packages\win32com\client\dynamic.py", line 72, > in _GetGoodDispatch > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, > pythoncom.IID_IDispatch) > com_error: (-2147221230, 'Klasse is niet gelicenseerd voor gebruik', None, > None) > > thank in advance, > > Arjen > > > > From aleax at aleax.it Wed Nov 5 06:00:20 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 05 Nov 2003 11:00:20 GMT Subject: Using debug print routine inside assert References: <8765i072jh.fsf@titan.staselog.com> <0cPpb.91638$e5.3380437@news1.tin.it> <87k76f1672.fsf@titan.staselog.com> Message-ID: <8L4qb.95522$e5.3515038@news1.tin.it> Edvard Majakari wrote: > Alex Martelli writes: > >> def debug(msg, *args): >> if not must_do_some_output: return >> >> if args: >> msg = msg % args[0](*args[1:]) >> >> # proceed to output msg >> >> and called as > > Gee - I'm impressed to receive answer to my original problem from > Martellibot himself :) :-) > This is an excellent solution. I just realised it is backwards compatible > with my current system - calling debug('foo bar baf %s' %method_call()) > works just fine with Alex's version; it just works the same as before, and > doesn't get any advantage from deferred parameter list evaluation. Yes, the deferred evaluation above is just optional. > Of course there's still minor overhead in calling the method instead of > completely skipping it like with assert(), but usually that doesn't matter > at all. Usually not. When it does (you've got lots of calls to debug that you'd rather not just comment out and the overhead even just for debug checking a flag and returning is annoying) the fastest approach is debug = noop.noop where noop is a do-nothing C-coded callable that accepts any args at all and returns None... (also make sure the name 'debug' is local to the function doing the calls, else the name lookup overhead is being paid:-) Alex From NoixeTOGLIMI at hotmail.com Sat Nov 8 16:27:36 2003 From: NoixeTOGLIMI at hotmail.com (Noixe) Date: Sat, 08 Nov 2003 21:27:36 GMT Subject: Help for unicode Message-ID: Hello, I'm italian and i not speak a good english. My problem is this: Why this istruction: print u"\u00" + str(41) generate an error and this: print u"\u0041" no? Can I use all 65536 symbols of unicode in my program? For example, I need to use the mathematic symbol of void set. It has a 0198 number in a table of symbol that there is in Windows. Thanks -- Noixe From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Fri Nov 21 09:15:19 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Fri, 21 Nov 2003 17:15:19 +0300 Subject: Empty list as default parameter In-Reply-To: References: Message-ID: Alex Panayotopoulos wrote: > On Fri, 21 Nov 2003, anton muhin wrote: > > > Was there any reason that this sort of behaviour was not implemented? > > It was discussed several times (search for it, if you're interested), but I don't remeber details. >>Mutable defaults are better avoided (except for some variants of memo >>pattern). Standard trick is: >> >> def __init__(self, myList = None): >> if myList is None: >> self.myList = [] >> else: >> self.myList = myList > > > Thank you. I shall use this in my code. (Although I would have preferred a > trick that uses less lines!) > if you wish a one-linear, somehting like this might work: self.myList = myList or [] regards, anton. From nomail at hursley.ibm.com Thu Nov 20 21:16:33 2003 From: nomail at hursley.ibm.com (Derek Fountain) Date: Fri, 21 Nov 2003 10:16:33 +0800 Subject: Details on exceptions Message-ID: <3fbd7509$0$1749$5a62ac22@freenews.iinet.net.au> Are the details of the builtin exceptions laid out anywhere? I was looking though the O'Reilly Nutshell book, which informs me that errors with file objects raise the builtin exception IOError. However, it doesn't describe this exception in the same way it describes, for example, the OSError exception. How do I get the actual error code from IOError of what went wrong? I did a search on the Python docs, and couldn't find the information either. So either the information is well hidden for some reason, or I've missed some very important information on the standardisation of exception handling techniques. From bokr at oz.net Sun Nov 9 15:20:34 2003 From: bokr at oz.net (Bengt Richter) Date: 9 Nov 2003 20:20:34 GMT Subject: Bad docs for os.path.isabs() References: Message-ID: On Sun, 9 Nov 2003 11:32:46 -0800, "Ben Allfree" wrote: >The docs for os.path.isabs() state: > > isabs( path) > >Return True if path is an absolute pathname (begins with a slash). > >This is false becase os.path.isabs("C:\\foo") == True > >It should read: > > isabs( path) > >Return True if path is an absolute pathname (begins with a slash or drive >letter). While you're at it, better take this into account also ;-) >>> import os >>> os.path.isabs("C:\\foo") True >>> os.path.isabs("C:foo") False >>> os.path.isabs("\\foo") True For that last one, I think you could argue that it's false, since it does not absolutely specify what the meaning is in a multi-drive system. The whole drive letter file path thing is soo lame it makes me incoherent ;-/ Regards, Bengt Richter From ramen at lackingtalent.com Thu Nov 13 02:26:25 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Thu, 13 Nov 2003 07:26:25 -0000 Subject: Books I'd like to see Message-ID: David Mertz Functional Programming in Python Using the Xoltar Toolkit Steve Holden Python Web Services Alex Martelli Metaprogramming in Python Guido van Rossum My secret addiction to comp.lang.python A biography Tim Peters The Python Philosophy Eric S Raymond Python for the Working Hacker Gerson Kurz Designing Obfuscated Languages With Python Parser/Generators Tim Peters and Doug Bagley The Zen of Computer Programming Bill Venners Selected Interviews -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From ramen at lackingtalent.com Mon Nov 3 14:04:39 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 03 Nov 2003 19:04:39 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Nov 3) References: Message-ID: In article , John Roth wrote: > > "Dave Benjamin" wrote in message > news:slrnbqcu85.u0o.ramen at lackingtalent.com... >> In article , Emile van Sebille wrote: >> > QOTW: "...I want to reserve .var for the "with" statement (a la VB)." >> > --Guido van Rossum >> >> I saw this, too! Is this a joke? It seems to contradict the FAQ entry: >> > http://www.python.org/doc/faq/general.html#why-doesn-t-python-have-a-with-statement-like-some-other-languages >> >> It does seem like the .dot .prefix would disambiguate the variable scope > as >> long as it is used consistently, but I must say it was a surprise to read >> this... > > Aparently Guido has a number of directions he'd like to take Python, > and some kind of *optional* typing is on the list. That's no secret, > I've seen references to it a number of times. Hmm! Well, if it's any indication of the future, ActionScript 2.0 (in effort to follow JavaScript 2.0) and Perl 6 support some degree of optional typing. As long as it doesn't feel "tacked on" or syntactically cumbersome, I'm for it. I'd be especially interested in seeing some sort of type inference. > Every few months, someone brings up a 'with' statement. The FAQ > points out a number of problems with it, however, if you're willing > to give up some dynamism and insert the needed type declarations, > then it's not only eminently doable, but (if done right) would help > demonstrate program correctness. In ActionScript, there is a "with" statement, but its use is discouraged for several reasons. First, it's confusing trying to figure out which scope the names are coming from; even *writing* code with a "with" can be guesswork, so reading the code isn't much better. Second, it's inefficient, since it extends the scope chain temporarily, requiring an additional level of indirection for any non-local variable lookup. But I think the dot-prefix would solve this problem, since it would be unambiguous from the syntax whether you're referring to the "with"-ed object or something else. -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From richie at entrian.com Wed Nov 5 12:23:25 2003 From: richie at entrian.com (Richie Hindle) Date: Wed, 05 Nov 2003 17:23:25 +0000 Subject: Rekall not longer available from theKompany.com - a fabrication In-Reply-To: <3fa6a75e$0$12666$fa0fcedb@lovejoy.zen.co.uk> References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <3fa6a75e$0$12666$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <0jbiqvkl64bu000plfhr9oq0cct9ec18ja@4ax.com> [John] > Rekall is to be released under the GPL Your website (http://www.totalrekall.co.uk) says "The GPL version would be free for non-commercial use", which is a contradiction. GPL'd code can be used commercially. The Open Source Definition (http://opensource.org/docs/definition.php) makes this clear: ------------------------------------------------------------------------- 6. No Discrimination Against Fields of Endeavor The license must not restrict anyone from making use of the program in a specific field of endeavor. For example, it may not restrict the program from being used in a business, or from being used for genetic research. Rationale: The major intention of this clause is to prohibit license traps that prevent open source from being used commercially. We want commercial users to join our community, not feel excluded from it. ------------------------------------------------------------------------- Needless to say, the GPL meets the conditions of the Open Source Definition. (I don't have an axe to grind over any of the issues here - I'm just pointing out a factual inaccuracy.) -- Richie Hindle richie at entrian.com From 2002 at weholt.org Wed Nov 5 10:48:40 2003 From: 2002 at weholt.org (Thomas Weholt) Date: Wed, 5 Nov 2003 16:48:40 +0100 Subject: Template-engine References: Message-ID: Or you can try SimpleTal/es, available at http://www.owlfish.com Thomas "Miika Keskinen" wrote in message news:pan.2003.11.05.14.20.42.473860 at utu.fi... > Hi all > > I was in need for a simple template engine (like PEAR::IT.php) and didn't > find any suitable. Yes, there is many templating engines available but > most are far too complex or does implement some additional features in > their syntax. > > So I created following and I'm asking comments - and yes I know there is > couple not so pythonistic sides in code. Most of all accessing inner dict > B straight. This is however first working version (started it hour ago) > and I'm asking if any of you have something in mind that could help me > making that better. > > This engine is non only for html ( in fact I don't use it for html but > email-templates and some configuration-templates ). > > the beast can be found from http://users.utu.fi/mikrke/index.html > (includes example how to use it) > > -- > Miika From mikit at zoran.co.il Mon Nov 17 16:23:18 2003 From: mikit at zoran.co.il (Miki Tebeka) Date: 17 Nov 2003 13:23:18 -0800 Subject: line number var like perl's $.? References: Message-ID: <6250403b.0311171323.722461aa@posting.google.com> Hello Matthew, > linenum = 0 > for line in open('blah.txt'): > linenum += 1 > print linenum, ". ", line In 2.3 you can use "enumerate" for lnum, line in enumerate(open("blah.txt")): print lnum, ".", line HTH. Miki From joconnor at cybermesa.com Sat Nov 29 13:16:28 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Sat, 29 Nov 2003 11:16:28 -0700 Subject: Printing dots in single-line In-Reply-To: <7xu14nhwzk.fsf@ruckus.brouhaha.com> References: <3fb39e32$1_1@nova.entelchile.net> <8J4yb.249740$mZ5.1858603@attbi_s54> <7xu14nhwzk.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >"Rainer Deyke" writes: > > >>Yes: the print statement is an abomination. It is a special-case syntax for >>a task that requires no special syntax, and will hopefully be deprecated in >>the future, the sooner the better. >> >> > >Are you kidding? The example I keep asking about is the addition >operator (+). Why does anyone need to say 2+2 when they can say >2-(-2)? The addition operator is a special case syntax for the >subtraction operator where none is needed. Should we deprecate it? >I'd rather say that a practical language needs to make concessions to >the way users actually think. > > Well, okay then :) Personally, print bothers me because there is no receiver. As an OO developer, I'm used to thinking usually iin terms of "object.method" and the fact that print is just sorta this standalone thing out there with no receiver doesn't match the way I think. However, it's not really a function either as it doesn't use function syntax. It's just sorta there. It really doesn't fit in with any of the basic idioms I use when thinking about developing software From nikolai.NOJUNK at micon.no Thu Nov 27 18:45:18 2003 From: nikolai.NOJUNK at micon.no (Nikolai Kirsebom) Date: Fri, 28 Nov 2003 00:45:18 +0100 Subject: Word2000 to wxPython conversion.... Message-ID: <823dsvsklcdtharcqkj5a3aoci4f181t1k@4ax.com> I've made a small utility which converts the content of a Microsoft Word2000 document to wxPython code. For some time I've used wxPython in small projects. I always have to look up old examples when writing 'sizer' code, and I tend to spend quite some time before getting it correct. Some time ago I was going to implement a copy of a MFC based dialog in wxPython. The MFC dialog did not have dynamic sizing. In order to identify how the sizers should be implemented in wxPython, I ended up drawing a "grid" identifying the various sizers. Then the idea of using tables in tables was quite apparent, and the result is the word2wx.py script and a small class-layer on top of wxPython. Utility can be downloaded from http://www.micon.no/PythonPage.asp Any comments / help on improving coding (in particular the parsing system which is rather ad-hoc) will be appreciated. Nikolai From adalke at mindspring.com Sat Nov 15 03:41:57 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 15 Nov 2003 08:41:57 GMT Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> <2u1tb.25127$hV.934365@news2.tin.it> <2259b0e2.0311142313.62a73078@posting.google.com> Message-ID: Michele Simionato: > I lived < 50 meters from Barnes & Noble, still I bought my Python books > from Amazon.com. For instance "Python in a Nutshell" was available on-line > before than in the libraries, with 30% discount and free shipping. It > arrived in a couple of days. Try also bookpool.com for technical books. PiaN is 43% off. With 3-4 day UPS ground it's $24.12, which for a book with list price of $34.95 means it's 31% off. And you can get cheaper shipping if you are willing to wait longer. Andrew dalke at dalkescientific.com From rmunn at pobox.com Wed Nov 19 16:39:43 2003 From: rmunn at pobox.com (Robin Munn) Date: Wed, 19 Nov 2003 21:39:43 GMT Subject: What do you think of this Python logo? References: <8g12rvo9nagi57vng3s00gdg6er9pq4ktu@4ax.com> <3FB10CF8.61CB72FD@engcorp.com> Message-ID: Peter Hansen wrote: > John Roth wrote: >> >> "G.A." wrote in message >> news:8g12rvo9nagi57vng3s00gdg6er9pq4ktu at 4ax.com... >> > On 11 Nov 2003 20:26:08 +1100, Tim Churches >> wrote: >> > >> > >> > >Much better to stick to a Monty Python-inspired theme, incorporating a >> > >> > I understand the desire to incorporate fun into Python, but I fear that >> any >> > Monty Python inspired logo will connote frivolity. I don't think that's >> > the image that should be conveyed. >> > >> > My initial take on the logo in the base note is that I like the cleaness >> of >> > it. However, it took too much effort to recognize the outer loop as a >> > snake, let alone a python. I kind of like the idea of a snake wrapped >> > around the P. >> >> A snake wrapped around a failed project would be even better, but >> I will admit that I can't figure out a good, immediately recognizable icon >> for a failed project... > > Maybe the Netscape logo? (ducks and runs) ^^^^^^^^ I think you misspelled "Micro$oft"... :-) -- Robin Munn rmunn at pobox.com From usenet at soraia.com Wed Nov 26 12:31:35 2003 From: usenet at soraia.com (Joe Francia) Date: Wed, 26 Nov 2003 17:31:35 GMT Subject: libmysqld.dll - any working example? In-Reply-To: References: Message-ID: JZ wrote: > Does anybody know any working example of using embedded MySQL library > for Win32 (libmysqld.dll)?That example from MySQL manual does not > work for me. I am looking for Python API to libmysqld.dll... You may want to consider this, which doesn't require you to ship any external DLLs: http://sourceforge.net/projects/mysql-python Joe From dave at pythonapocrypha.com Tue Nov 11 17:32:37 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 11 Nov 2003 15:32:37 -0700 Subject: Python's simplicity philosophy References: <3fbqb.97878$e5.3584611@news1.tin.it><3FAB8399.687F2021@alcyone.com><1pQqb.432528$R32.14304849@news2.tin.it><3FAC19F0.284DCB03@alcyone.com> Message-ID: <008b01c3a8a3$b6495260$891e140a@YODA> > >> Of course I am not joking. I see no good coming from the mantra, when > >> the mantra should be instead what I said it should be: > > >> "small, clean, simple, powerful, general, elegant" > > > It's really a matter of taste - both "versions" mean about the same to me > > (and to me both mean "get rid of reduce()" ;-) ). > > No, my mantra plainly states to keep general and powerful features > over specific, tailored features. And I disagree that that's necessarily a Good Thing. Good language design is about finding that balance between general and specific. It's why I'm not a language designer and it's also why I'm a Python user. > reduce() is more general and > powerful than sum(), and would thus clearly be preferred by my > mantra. Yes, and eval() would clearly be preferred over them all. > The mantra "there should be only one obvious way to do it" apparently > implies that one should remove powerful, general features like > reduce() from the language, and clutter it up instead with lots of > specific, tailored features like overloaded sum() and max(). I completely disagree - I see no evidence of that. We're looking at the same data but drawing very different conclusions from it. > I can already see what's going to happen with sum(): Ultimately, > people will realize that they may want to perform more general types > of sums, using alternate addition operations. Not gonna happen - this _might_ happen if Python was a design-by-committee language, but it's not. > Yes, there are other parts of The Zen of Python that point to the > powerful and general, rather than the clutter of specific and > tailored, but nobody seems to quote them these days, 'not quoting' != 'not following' and 'what gets debated on c.l.py' != 'what the Python developers do' > > Having said that though, part of the appeal of Python is that it hits the > > nail on the head surprisingly often: if you don't know (from prior > > experience) how to do something in Python, your first guess is very often > > correct. Correspondingly, when you read someone else's Python code that uses > > some feature you're not familiar with, odds are in your favor that you'll > > correctly guess what that feature actually does. > > All of this falls out of "clean", "simple", and "elegant". Not at all - I cut my teeth on 6502 assembly and there is plenty that I still find clean, simple, and elegant about it, but it's horrible to program in. > > And that is why I wouldn't be sad if reduce() were to disappear - I don't > > use reduce() and _anytime_ I see reduce() in someone's code I have to slow > > way down and sort of rehearse in my mind what it's supposed to do and see if > > I can successfully interpret its meaning (and, when nobody's looking, I > > might even replace it with a for-loop!). > > C'mon -- all reduce() is is a generalized sum or product. What's > there to think about? It's as intuitive as can be. To you, perhaps. Not me, and not a lot of other people. To be honest I don't really care that it's in the language. I'm not dying to see it get deprecated or anything, but I do avoid it in my own code because it's non-obvious to me, and if it were gone then Python would seem a little cleaner to me. Obviously what is intuitive to someone is highly subjective - I was really in favor of adding a conditional operator to Python because to me it _is_ intuitive, clean, powerful, etc. because of my previous use of it in C. As much as I wanted to have it though, on one level I'm really pleased that a whole lot of clamoring for it did not result in its addition to the language. I *like* the fact that there is someone making subjective judgement calls, even if it means I sometimes don't get my every wish. A good programming language is not the natural by-product of a series of purely objective tests. > And taught in > every CS curiculum. Doubtful, and if it were universally true, it would weaken your point because many people still find it a foreign or awkward concept. Besides, whether or not something is taught in a CS program is a really poor reason for doing anything. -Dave From grzegorz at ee.ualberta.ca Sat Nov 29 18:53:11 2003 From: grzegorz at ee.ualberta.ca (Grzegorz Dostatni) Date: Sat, 29 Nov 2003 18:53:11 -0500 Subject: cygwin tcltk 8.3 Message-ID: Does anyone have tcltk 8.3 packages for cygwin? I spend the last 6 hours searching for them on the net. Could you please check your cygwin archive? Greg "Many a man may look respectable, and yet be able to hide at will behind a spiral staircase." - Pelham (Plum) Grenville Wodehouse From mwh at python.net Wed Nov 5 09:13:31 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 5 Nov 2003 14:13:31 GMT Subject: dictionary keys, __hash__, __cmp__ References: <7h3fzh3hsb7.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h3sml2hpoz.fsf@pc150.maths.bris.ac.uk> Jan-Erik Meyer-L?tgens writes: > Michael Hudson wrote: > > Jan-Erik Meyer-L?tgens writes: > >> > >> 3. "If a class does not define a __cmp__() method it > >> should not define a __hash__() operation either." > >> > >> > >>Can I asume that: > >> -- I can savely ignore the 3rd statement, because python > >> falls back to cmp(id(obj1), id(obj2)), if __cmp__() > >> is not defined. > > Don't understand. > > > > Ok, let me ask the following question: What is the reason > for that rule? Well, the idea is that dictionary lookup is done by equality. If you don't define __cmp__ then equality is in fact identity (well, that's very nearly true...) so the default implementation of __hash__ (based on the pointer address) is as good as it can get (you have hash equality iff you have object equality). I think. Cheers, mwh -- Every now and then, Google doesn't throw up what I need so I start checking Altavista, Yahoo, etc. In almost every single case, I am brutally reminded why I use Google in the first place. -- John Riddoch, asr From cpgray at library.uwaterloo.ca Tue Nov 18 10:10:03 2003 From: cpgray at library.uwaterloo.ca (Chris Gray) Date: Tue, 18 Nov 2003 10:10:03 -0500 Subject: Looking for an http proxy server written in Python Message-ID: Is there such a beast? In particular, I'm looking for a production-quality proxy server fully compliant with HTTP/1.1 written in Python. If there isn't, is there anything that comes close? Thanks for any help you can throw my way, Chris Gray "Okey dokey.. free my mind. Right, no problem, free my mind, free my mind, no problem, right... " -The Matrix From mfranklin1 at gatwick.westerngeco.slb.com Mon Nov 3 04:22:23 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 03 Nov 2003 09:22:23 +0000 Subject: Two naive Tkinter questions In-Reply-To: References: Message-ID: <1067851343.1105.7.camel@m-franklin> On Sun, 2003-11-02 at 21:32, Andrew Koenig wrote: > > In the specific example, you could just *know* that setcolor deals > > with self.b1. In the more general example, you can create dynamic > > callback functions: > > > > self.b1 = Button(self, bg = "red", > > command = lambda: self.b1.config(bg="blue")) > > > > This uses a number of tricks: the lambda function has no arguments, > > yet it uses self - so it is a nested function. Also, inside a lambda > > function, you can have only expressions, so self.b1['bg']='blue' would > > not be allowed. In the general case, and not assuming nested > > functions, you would write > > > > def createWidgets(self): > > def b1_setcolor(self=self): > > self.b1['bg']='blue' > > self.b1 = Button(self, bg = "red", command=b1_setcolor) > > I worked out something similar, but I must confess that it appears > needlessly complicated. I was hoping for a simpler solution, such as a > variation of the "command" attribute that would cause its associated > argument to be called with the button rather than its parent. > > Your first suggestion, knowing that setcolor deals with self.b1, doesn't > work with my application because I'm going to have lots of these buttons, > and I want to be able to set their colors independently. > For this I would use a callback class and it's __call__ method (untested) class Callback: def __init__(self, button, colour): self.button = button self.colour = colour def __call__(self): self.button.config(background = self.colour) self.b1 = Button(self, background = "red") self.b1.config(command = Callback(self.b1, "blue")) self.b1.pack(.....) Regards Martin -- Martin Franklin From matthew at newsgroups.com Wed Nov 5 03:57:05 2003 From: matthew at newsgroups.com (Matthew) Date: Wed, 5 Nov 2003 21:57:05 +1300 Subject: Stuck on inheritance Message-ID: > > Hi, > > > > I'm trying to learn python and actually do something usefule with it at the > > same time. I'm unclear how you correctly pass arguments to a superclass when > > initing the subclass. Below is a short code fragment. What's wrong? > def print_message(): > print "I am a message" > > class call_me(object): > def __init__(self, func, *args, **kw): > self.func = func > self.args = args > self.kw = kw > def __call__(self,*args,**kw): > print "Executing..." > return self.func(*self.args, **self.kw) > > class funct(call_me): > def __init__(self, func, name='', info = []): # description, authour, etc > super(funct, self).__init__(func,name,info) Not sure about this. Why do you pass name and info to the superclass? I thought these attributes were stored in the subclass. If not, why the two following lines? > self.name = name > self.info = info > > > I am not sure what you are trying to do. Well, basically I have a dictionary of lists containing unnamed callable functions to which I wish to add some further info such as an readable name, description, authour, etc. So help me here... Using composition I'd have > class funct(call_me): > def __init__(self, func, name='', info = []): # description, authour, etc > self.func = func > self.name = name > self.info = info using a_call_me = call_me(print_message) my_func = funct(a_call_me, 'fred', []) Using inheritance I'd have > class funct(call_me): > def __init__(self, func, *args, **kw, name='', info = []): # description, authour, etc > super(call_me, self).__init__(func,*args, **kw) > self.name = name > self.info = info using my_func = funct(print_message, None, None, 'Fred', []) Is this right or am I *horribly* wrong?! Thanks for the help. matthew. From des.small at bristol.ac.uk Thu Nov 27 06:15:49 2003 From: des.small at bristol.ac.uk (Des Small) Date: Thu, 27 Nov 2003 11:15:49 GMT Subject: invert dictionary with list &c References: Message-ID: John Hunter writes: > >>>>> "Des" == Des Small writes: > > def count(l): > d = {} > [d.setdefault(w, 0) += 1 for w in l] > return d > > This code raises a SyntaxError. So it does. Whatever it was I had working yesterday wasn't that, then. > The standard idiom for counting all the elements in a list with a > dictionary is > > def count(l): > d = {} > for w in l: d[w] = d.get(w,0) + 1 > return d > > I think the basic rule of thumb is to use the setdefault approach for > mutable objects (list, dict) and the get approach for immutable > elements (strings, ints, floats, tuples). What I really want is a generic pattern that constructs dictionary from iterators in a clean way, while allowing mutation of the dictionary entry as necessary. > Also, many here would find using list comprehensions while ignoring > their return value, as you did in '[d.setdefault(w, 0) += 1 for w in > l]' to be an abuse of list comps. At least I've been admonished for > doing so, and so I must now admonish you to continue the cycle of > violence. I shall be breaking the cycle by not caring, although if and when generator comprehensions allow me to comply with your preferences I'll probably do so. [...] Des -- "[T]he structural trend in linguistics which took root with the International Congresses of the twenties and early thirties [...] had close and effective connections with phenomenology in its Husserlian and Hegelian versions." -- Roman Jakobson From http Thu Nov 27 15:26:03 2003 From: http (Paul Rubin) Date: 27 Nov 2003 12:26:03 -0800 Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> <7xwu9svyny.fsf@ruckus.brouhaha.com> <7xvfpcowjt.fsf@ruckus.brouhaha.com> <653b7547.0311222346.b4d9e98@posting.google.com> <653b7547.0311231952.5abe71ab@posting.google.com> <23891c90.0311240320.6960d468@posting.google.com> Message-ID: <7xwu9lh82s.fsf@ruckus.brouhaha.com> Tim Churches writes: > Stubbornness notwithstanding, thank goodness we have curmudgeons like > RMS in the world. He has a philosophical position which he knows to be > correct (and he is essentially correct), and he refuses to budge a > millimetre from it. May bless his cotton socks. I've seen RMS's socks. I don't know whether they're made of cotton, but I can attest that they are hole-y. ;-) From rcs333 at online.no Fri Nov 28 12:40:47 2003 From: rcs333 at online.no (RCS) Date: Fri, 28 Nov 2003 18:40:47 +0100 Subject: omniORB 4.0.3 and omniORBpy 2.3 available References: <466c2$3fc32080$51604868$12088@nf2.news-service.com> <15235$3fc7292f$51604868$25838@nf2.news-service.com> Message-ID: "Duncan Grisby" skrev i melding news:15235$3fc7292f$51604868$25838 at nf2.news-service.com... > First, as another poster suggested, make sure you have nothing to do > with omniORB on your path before you try the new compile. I did that, and tough luck, the same unresolved 632 external symbols. > If that still fails, please subscribe to the omniORB mailing list, and post > details of the missing symbols to there. Well, I have tried earlier to post to the mailing lists, but what I always get as a response is this: "Your mail to 'omniORB-list' with the subject Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list" and some time later I recieve an email that the message was not accepted due to my not being a member, even if I have registered as a member (and recieve mails every day from the list). So I excpect it this time also not to pass through to the members of the mailing list. Anyway, here are some of the unresolved external symbols (from among those I could capture in the DOS window): * CosNaming::NamingContext::CannotProceed::insertToAnyFn ... referenced in function CosNaming::NamingContext::CannotProceed:: scalar deleting destructor * CosNaming::NamingContext::CannotProceed::_NP_repoId ... referenced in function CosNaming::NamingContext::CannotProceed::CannotProceed * CosNaming::NamingContext::NotFound::_NP_typeId ... * CosNaming::NamingContextExt_Helper::release ... * CosNaming::NamingContext_Helper::release * CosNaming::NamingContext::AlreadyBound::~AlreadyBound * CosNaming::NamingContext::NotEmpty::_NP_marshal * CosNaming::NamingContext::InvalidName::_NP_repoId Regards RCS From peter at engcorp.com Tue Nov 4 10:47:08 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 04 Nov 2003 10:47:08 -0500 Subject: Using debug print routine inside assert References: <8765i072jh.fsf@titan.staselog.com> <3FA7AA9D.A2028E2D@engcorp.com> <87ism05iil.fsf@titan.staselog.com> Message-ID: <3FA7C9FC.80D4A9B3@engcorp.com> Edvard Majakari wrote: > > Personally, I think you're right. I've become fascinated with the idea of > unit testing myself, but the problem is that > > a) you often have to find out bugs from somebody else's code True, and for that I do throw in a few prints or resort to pdb.set_trace(), but only temporarily. > b) you've developed system using testing, but the bug didn't appear in > your tests and now you don't know what causes the problem Same as above, but of course you also would add a test that does catch the bug, so you know you've fixed it. > c) you didn't do unit testing yet when you coded the module or I think the OP was talking about code he was developing, so this is sort of a moot point... > d) you don't believe in unit testing > > to which we'd say d is the wrong answer, c is more likely and a and b just > happen. All true. And the fix for c is obvious. :-) -Peter From nicolas.lehuen at thecrmcompany.com Thu Nov 20 12:32:03 2003 From: nicolas.lehuen at thecrmcompany.com (Nicolas LEHUEN) Date: Thu, 20 Nov 2003 18:32:03 +0100 Subject: Suggestion for a new regular expression extension References: <3fbce8a0$0$25040$afc38c87@news.easynet.fr> Message-ID: <3fbcfa98$0$13741$afc38c87@news.easynet.fr> Hi Skip, Well, that's what I am doing now, since I cannot hold my breath until my suggestion gets implemented :). But in my case, it forces me to duplicate each alternative in the big regexp in my normalisation function, which causes quite tedious maintenance of the whole piece of code. It would feel pretty much more natural just to say to the RE engine "if you match B(?D|LD|VD|OUL(?:EVARD)) within this big ugly regexp, just return me BD, please". Anyway, I think I'm going to try using sre.Scanner, we'll see if it's stable enough for that. I'll build 3 scanners that I'll call in sequence (each one reusing the part of the string that was not scanned, handily returned in the second part of the returned sequence of the 'scan' method) : - one for the number (or numbers) within the street : "14", or numbers like "14-16" or "14/16" or whatever separator the person entering the address could imagine. - one for the number extension : "B" or "BIS", "T" or "TER" or "TRE" (misspelled, but that's the way some people write it...) - one for the street/place type : most of the tricky regexp are there, most of the rewriting will be performed by actions defined in the Scanner's lexicon - and the rest of the string is the street/place name. This way the address will be processed in one pass without code duplication. But still, this (?PR<...>...) notation would be handy. I had a look at the sre source code, in hope that I would be able to implement it myself, but it's a bit too much for me to handle right now ;). Regards, Nicolas "Skip Montanaro" a ?crit dans le message de news:mailman.931.1069347639.702.python-list at python.org... > Nicolas> re_adresse = re.compile(r''' > ... [big, ugly re snipped] ... > Nicolas> ''',re.X) > > Nicolas> Note for example the many abbreviations (correct or not) ouf > Nicolas> "boulevard" : BD, BLD, BVD, BOUL, BOULEVARD. For normalisation > Nicolas> purposes, I need to transform all those forms into the only > Nicolas> correct abbreviation, BD. > > Nicolas> What would be really, really neat, would be a regular > Nicolas> expression extension notation that would make the RE engine to > Nicolas> return an arbitrary string when a substring is matched. > > Why not just use named groups, then pass the match's groupdict() result > through a normalization function? Here's a trivial example which > "normalizes" some matches by replacing them with the matched strings' > lengths. > > >>> import re > >>> pat = re.compile('(?Pa+)(?Pb+)') > >>> mat = pat.match("aaaaaaaabbb") > >>> def norm(d): > ... d['a'] = len(d['a']) > ... d['b'] = len(d['b']) > ... > >>> d = mat.groupdict() > >>> d > {'a': 'aaaaaaaa', 'b': 'bbb'} > >>> norm(d) > >>> d > {'a': 8, 'b': 3} > > Skip > From python at meyer-luetgens.de Wed Nov 5 08:24:00 2003 From: python at meyer-luetgens.de (=?ISO-8859-1?Q?Jan-Erik_Meyer-L=FCtgens?=) Date: Wed, 05 Nov 2003 14:24:00 +0100 Subject: Template-engine In-Reply-To: References: Message-ID: Miika Keskinen wrote: > Hi all > > I was in need for a simple template engine (like PEAR::IT.php) and didn't > find any suitable. Yes, there is many templating engines available but > most are far too complex or does implement some additional features in > their syntax. > Try Cheetah: http://www.cheetahtemplate.org/ $title #for $client in $clients #end for
$client.surname, $client.firstname $client.email
------------------------------------------------------ from Cheetah.Template import Template class Client: def __init__(self, surname, firstname, email) self.surname = surname self.firstname = firstname self.email = email clients = [ Client('Meyer-L?tgens', 'Jan-Erik', 'un at kown.de'), Client('Keskinen', 'Miika', 'un at known.fi'), ] tpl = Template(file='path_to_tpl_file') tpl.title = 'The Title' tpl.clients = clients print tpl -- Jan-Erik From FBatista at uniFON.com.ar Tue Nov 4 12:40:37 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 4 Nov 2003 14:40:37 -0300 Subject: prePEP: Decimal data type Message-ID: Paul Moore wrote: #- >> When passing floating point to the constructor, what #- should happen? #- >> #- >> j. ``Decimal(1.1) == Decimal('1.1')`` #- >> k. ``Decimal(1.1) == #- >> Decimal('110000000000000008881784197001252...e-51')`` #- > #- > Clearly, j is the correct answer. It's not all that hard #- to do, either. #- #- No way. Consider: #- #- >>> 1.1 #- 1.1000000000000001 #- >>> 1.1==1.1000000000000001 #- True #- #- So what should Decimal(1.1000000000000001) evaluate to? It can't be #- Decimal('1.1'), as that contradicts your statement that j "clearly" #- applies. But it *also* can't be #- Decimal('1.1000000000000001'), as then #- we have the *same number* converting to two *different* Decimal #- values. This is really the problem. Option (j) seems to be correct but is not. Option (k) *is* correct, but not what you want to do, :( Maybe the more natural solution is not to accept float (you always can write that *same* number as a string, and it'll be correct, and sure i'll be doing what you expect). #- into :-) Having a special method, say Decimal.round_float(f, digits), #- is probably OK, though... Mmmm. Digits in the first meaning or the second? Should round or truncate? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 newsgroups at jhrothjr.com Wed Nov 5 02:58:47 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 5 Nov 2003 02:58:47 -0500 Subject: New to Python; Command equivalents References: <8f43ba42.0311042330.7eaa6e10@posting.google.com> Message-ID: "Code_Dark" wrote in message news:8f43ba42.0311042330.7eaa6e10 at posting.google.com... > Hi, I'm new to the Python programming language, and eager to learn. I > know C and C++, but I'm sure you all know that feeling when you just > _need_ a new language. I chose python because I'd heard good things > about it. I have python 2.3 installed on my computer, and I am glad to > say that I've created a "Hello, World" program. Right, the only > problem is that the only command I've been able to figure out is > 'print'. That's quite a problem. I was just wondering if someone could > give me the command for 'cin' or 'scanf' in the C-based languages, > and if it is required to define variabled before using them as in the > C based languages (such as ;int numbofPizza' in the beginning of the > program). Sorry for asking such newbieish questions, but I am, in > fact, a newbie. Please reply to this, or email me at > dshaw858 at hotmail.com ... the email address I use for my newsgroups > (rooting_j00 at hotmail.com) isn't regularly checked because of spam... > meh. > > Thanks in advance, > > - Code Dark Presumably, you're not on a Windows machine, since the install packages for Windows come with the complete documentation. Go to the Python web site at www.python.org, and download the documentation package. Start reading at the tutorial. You can even do this on the web. John Roth From pf_moore at yahoo.co.uk Mon Nov 17 17:00:38 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Mon, 17 Nov 2003 22:00:38 +0000 Subject: PEP 321: Date/Time Parsing and Formatting References: Message-ID: Gerrit Holl writes: > Python 2.3 added a number of simple date and time types in the > ``datetime`` module. There's no support for parsing strings in various > formats and returning a corresponding instance of one of the types. > This PEP proposes adding a family of predefined parsing function for > several commonly used date and time formats, and a facility for generic > parsing. I assume you're aware of Gustavo Niemeyer's DateUtil module (https://moin.conectiva.com.br/DateUtil)? I'm not 100% sure how the parser functionality fits in with this PEP. It seems to me that this PEP is more focused on parsing specifically formatted data (not something I need often) whereas Gustavo's function is about parsing highly general "human input" formats. As most of my date parsing need is for user input parameters and the like, I prefer Gustavo's module :-) [After reading through this PEP and commenting, I'd say that my preference (which may not be Gustavo's!) would be to add dateutil to the standard library, with the following changes/additions: 1. Add a dateutil.RFC822_FORMAT for output of RFC822-compliant dates. 2. Extend dateutil.parser.parse to handle additional (CVS-style) possibilities - today, tomorrow, yesterday, things like that. 3. Add dateutil.parser.strptime as a wrapper round time.strptime. I think that's all.] > * Formats commonly written by humans such as the American > "MM/DD/YYYY", the European "YYYY/MM/DD", and variants such as > "DD-Month-YYYY". UK format DD/MM/YYYY is worth adding (in my UK-based opinion :-)) But you can get all of these via strptime (wrapped to return a datetime value). > * CVS-style or tar-style dates ("tomorrow", "12 hours ago", etc.) That would be nice. I assume it should be combined with a highly flexible parser, so that the same function that handles "tomorrow" will also handle "12-dec-2003". This would basically be like Gustavo's parser, but with extended functionality (Gustavo's doesn't handle things like "tomorrow"). > 3) Add a separate module (possible names: date, date_parse, parse_date) > or subpackage (possible names: datetime.parser) containing parsing > functions:: > > import datetime > d = datetime.parser.parse_iso8601("2003-09-15T10:34:54") I'd go for this option. Actually, I'd support including Gustavo's dateutil module in the standard library. This PEP then involves adding a number of additional (specialised) parsers to the dateutil.parser subpackage. > * What exception to raise on errors? ValueError, or a specialized exception? ValueError seems perfectly adequate. > * Should you know what type you're expecting, or should the parsing figure > it out? (e.g. ``parse_iso8601("yyyy-mm-dd")`` returns a ``date`` instance, > but parsing "yyyy-mm-ddThh:mm:ss" returns a ``datetime``.) I don't think that the functions should return a type which depends on the input (I'd push that as a general rule, but I've probably missed an obvious counterexample - nevermind, I think it applies here regardless). > Should there be an option to signal an error if a time is provided > where none is expected, or if no time is provided? I think that returning a datetime always, with a zero time component when no time is specified, should be enough. You can use the date() method of datetime instances to get just the date part if you want it. But this is something that should be prototyped - real-world use is far more important here than theoretical considerations. > * Anything special required for I18N? For time zones? Scary. Do we need to parse "21-janvier-2001"? Only if in a French-speaking locale? > Generic Input Parsing > ======================= > > Is a strptime() implementation that returns ``datetime`` types sufficient? > > XXX if yes, describe strptime here. Can the existing pure-Python > implementation be easily retargeted? Not sufficient, but very useful. It effectively covers all of the fixed-format cases (with a suitable format string). And it does I18N, I believe (hard to tell in a UK locale...) Options: * class methods on the 3 datetime classes. This might be hard, because datetime is a C extension, and strptime is Python. * Modify strptime to return a datetime value rather than a struct_time. But this isn't backward compatible, and so is probably not on. Shame, as it feels like the right answer. * Have a new function in the time module. Either just a wrapper round strptime, or a modified strptime, with strptime changed into a wrapper round the new function. But a good name is going to be hard to come up with. * Add a new parameter to strptime (datetime=True or something). Ugly, and violates my "functions shouldn't return different types depending on their arguments" comment above. * A function in a new module - something like dateutil.parser.strptime, as a wrapper round time.strptime. (Excuse the subliminal advertising for Gustavo's module - change the name if you prefer :-)) > Output Formats > ======================= > > Not all input formats need to be supported as output formats, because it's > pretty trivial to get the ``strftime()`` argument right for simple things > such as YYYY/MM/DD. Only complicated formats need to be supported; RFC2822 > is currently the only one I can think of. An *output* format for RFC2822 compliant dates shouldn't be too hard, surely? Ah, I see what you mean. It's possible, but hard to *remember*, so it's best to define it somewhere. Good point. > Options: > > 1) Provide predefined format strings, so you could write this:: > > import datetime > d = datetime.datetime(...) > print d.strftime(d.RFC2822_FORMAT) # or datetime.RFC2822_FORMAT? This is what I'd prefer. A module-level constant in a dateutil module would be fine for me, too. > 2) Provide new methods on all the objects:: > > d = datetime.datetime(...) > print d.rfc822_time() Seems overkill. And I'd rather just have strftime for all date output formatting - one way of doing things, and all that. Paul. -- This signature intentionally left blank From tweedgeezer at hotmail.com Mon Nov 17 13:12:36 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 17 Nov 2003 10:12:36 -0800 Subject: asyncore/asynchat References: <698f09f8.0311141355.2430c07b@posting.google.com> Message-ID: <698f09f8.0311171012.6ff8d365@posting.google.com> "F.G.Testa" wrote in message news:... > But how do you keep it updated since we don't receive any notifications of > closing/removing channels from asyncore/asynchat? > I've found this: asyncore.socket_map (asyncore.py:62). It is a map of your > inherited asynchat class and I'm using it to search for a specific channel > and send data to it, but having my own dictionary would be more elegant, I > think. For my purposes I didn't need to keep it updated. Why why do you need access to such a dictionary? Is the channel itself unable to decide when it needs to send information? Jeremy From bokr at oz.net Sat Nov 22 21:43:23 2003 From: bokr at oz.net (Bengt Richter) Date: 23 Nov 2003 02:43:23 GMT Subject: Empty list as default parameter References: Message-ID: On Fri, 21 Nov 2003 13:26:13 +0000, Alex Panayotopoulos wrote: >On Fri, 21 Nov 2003, anton muhin wrote: > >> Really common mistake: lists are _mutable_ objects and self.myList >> references the same object as the default parameter. Therefore >> a.myList.append modifies default value as well. > >It does?! >Ah, I've found it: listHolder.__init__.func_defaults > >Hmm... this behaviour is *very* counter-intuitive. I expect that if I were >to define a default to an explicit object... > > def process_tree1( start=rootNode ) > >...then I should indeed be able to process rootNode through manipulating >start. However, if I define a default as a new instance of an object... > > def process_tree2( myTree=tree() ) > >...then the function should, IMHO, create a new object every time it is >entered. (By having func_defaults point to tree.__init__, or summat.) > >Was there any reason that this sort of behaviour was not implemented? Yes. The bindings of default values for call args are evaluated at define-time, in the context of the definition, not at execution time, when the function is called. If you want to specify what to call at execution time, you have to call it at execution time, so you either have to pass a reference to the thing to call ('tree' in this case) or have it otherwise visible from inside the function, e.g., the interface could be something like def process_tree2(treemaker=tree): myTree = treemaker() ... Now if you wanted to pass a pre-existing tree to this kind of process_tree2, you'd have to pass a callable that would execute to produce the tree, e.g., call it like temp_treemaker = lambda: rootNode process_tree2(temp_treemaker) # or just put the lambda expression right in the call More likely, you'd want to be able to accept a tree, or make one if nothing was passed. E.g., def process_tree3(myTree=None): if myTree is None: myTree = tree() # here tree must be visible in an enclosing scope ... # -- usually global, but not necessarily a variant would be to have a default value of a single particular tree, as in your first example, and then test whether something executable, like tree (not tree()) was being passed, e.g., def process_tree1( start=rootNode ): if callable(start): start = start() # e.g., if called like process_tree1(tree) Of course, if a node object is also callable, you have to make a different check ;-) > >> Mutable defaults are better avoided (except for some variants of memo >> pattern). Standard trick is: >> >> def __init__(self, myList = None): >> if myList is None: >> self.myList = [] >> else: >> self.myList = myList > >Thank you. I shall use this in my code. (Although I would have preferred a >trick that uses less lines!) > How about two less? I usually do it (with no trick ;-) like: def __init__(self, myList = None): if myList is None: myList = [] self.myList = myList Regards, Bengt Richter From jgoerzen at complete.org Wed Nov 26 11:19:32 2003 From: jgoerzen at complete.org (John Goerzen) Date: Wed, 26 Nov 2003 10:19:32 -0600 Subject: Best SOAP library? References: <87y8u432u2.fsf@heinrich.complete.org> Message-ID: <873ccbxfu3.fsf@heinrich.complete.org> "Diez B. Roggisch" writes: >> Which Python-based SOAP implementation is preferred today? Which ones >> are still being actively developed? > > ZSI just had a new release - IMHO its the most complete implementation. I > was quite satisfied with it, however I encountered problems with a > moderately complex apache-axis-based WSDL - but I didn't investigat > further, instead I used the generated axis-client and jython :) How would you say ZSI compares to SOAPpy? I've heard that SOAPpy is easier to use for some cases. Are there things that ZSI does that SOAPpy doesn't (or not as well)? Thanks, John From radam2 at tampabay.rr.com Thu Nov 13 19:31:56 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Fri, 14 Nov 2003 00:31:56 GMT Subject: case-sensitivity References: <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> Message-ID: On Thu, 13 Nov 2003 15:58:49 GMT, Alex Martelli wrote: >Ron Adam wrote: > ... >> 4: The editor or IDE matches what I enter to the names and then >> substitutes the proper case of the name at some definitive point. >> This ensures that the case is correct and the program compiles and >> runs normally. If I choose a different editor then see #1 or #2. > ... >> correcting while editing. Number 4 is possible to do now, but I >> don't know of any editors that currently do it. It would be a nice >> option to include in one I think. > >Yes, looks like a nice idea for a middling-difficulty project with >IDLE, and it would be useful even if made _particularly_ unintrusive >(spelling correction would be done only on specific request, and >only when feasible without ambiguity regarding e.g. standard library >modules and names therein -- a really minimal part of [4], yet it >would STILL save quite some trouble/hassle to those using it...). > > >Alex Maybe someone will try it. I've only just started with Python about a month ago. However I did pick up your 'Python in a Nutshell' last night and have already read though the first 4 chapters. Great book Alex! I've programmed lightly in c, c++, java, several basics, and even a little assembly. Took a course in fortran, although I don't remember any of it. Also learned pascal once upon a time. Python addresses many if not most of the complaints I've had with those other languages. Most of which were either low level languages that lacked high level functionality, or high level languages that were difficult to extend. And then there are the visual stuff that requires 3/4 of the code just to initialize everything. ack! What surprises me most is why I haven't found Python sooner? _Ron Adam From FBatista at uniFON.com.ar Tue Nov 18 10:48:34 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 18 Nov 2003 12:48:34 -0300 Subject: faqomatic Message-ID: Dan Stromberg wrote: #- Is there anything like faqomatic written in python? Depends. What is faqomatic? . Facundo From andymac at bullseye.apana.org.au Thu Nov 20 17:17:00 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Fri, 21 Nov 2003 09:17:00 +1100 (EST) Subject: Analyse of PDF (or EPS?) In-Reply-To: <3fbcc67e$0$9836$edfadb0f@dread14.news.tele.dk> References: <3fbcc67e$0$9836$edfadb0f@dread14.news.tele.dk> Message-ID: <20031121091453.Q68118@bullseye.apana.org.au> On Thu, 20 Nov 2003, Johan Holst Nielsen wrote: > Is there any Python packages to analyse or get some information out of > an PDF document... > > Like where the text are placed - what text are placed - fonts, embedded > PDFs/fonts/images etc. I believe that Ghostscript can be used to print PDFs on Postscript printers; you would then need to find tools to analyse Postscript files. -- 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 huzzah at tampabay.rr.com Sun Nov 2 08:32:24 2003 From: huzzah at tampabay.rr.com (Todd Stephens) Date: Sun, 02 Nov 2003 13:32:24 GMT Subject: It's still I, Miville References: Message-ID: On Sat, 01 Nov 2003 22:08:58 -0500, Fran?ois Miville-Dech?ne wrote: > You say in the definition of mappings that at present Python has only > You say Python is an evolving language, prove it. > To take on another subject, an object-oriented language such as yours > should > Your language appears in a calculator fashion, the user is reassured Your 'suggestions' walk a fine line between constructiveness and trolling with the 'your language' and 'you say' references. -- Todd Stephens From mark at hahnca.com Mon Nov 17 12:29:08 2003 From: mark at hahnca.com (Mark Hahn) Date: Mon, 17 Nov 2003 09:29:08 -0800 Subject: No limit! (was: pickle complexity limit?) References: Message-ID: Was your reply directing me to an example of how to write something that works around the recursion limits of pickle, or was it something that could be used directly to do pickling without the limits? I thought it was the former. In either case I apologize for my curt reply to your well thought out answer. I didn't realize that I had pissed you off until I finally parsed "thanks for no further replies -- chris" as "shut up" (which is kind of rude by the way). One reason I had trouble parsing that is you asked me a non-rhetorical question in the same post, which is a bit of a contradiction. "Mark Hahn" wrote in message news:vPVtb.6951$iS6.1812 at fed1read04... > "Christian Tismer" wrote ... > > > Mark Hahn wrote: > > > > > No thanks. I'd rather spend my time finding a tool that works or even > > > creating a new tool rather than working around a bad tool. > > > > Sorry? What exactly is the bad tool you are referring to? > > The bad tool is pickle. It cannot handle arbitrary graphs, which to me is a > bug. > > > I'm slightly unhappy with the time that I spent with > > this message, in order to get *that* answer. > > > > I didn't mean to be unappreciative of your help. Hopefully someone reading > this group will be helped by your message. I just don't want to try to work > around pickle's problems. > > > thanks for no further replies -- chris > > I don't know what you mean by this. > > From bellman at lysator.liu.se Tue Nov 11 12:52:48 2003 From: bellman at lysator.liu.se (Thomas Bellman) Date: Tue, 11 Nov 2003 17:52:48 +0000 (UTC) Subject: True, False, None (was re. Pruss's manifesto) References: <20031110065915.07735.00000461@mb-m07.aol.com> Message-ID: Alex Martelli wrote: > You are heartily welcome to perform the dynamic whole-code analysis > needed to prove whether True (or any other built-in identifier) may > or not be re-bound as a side effect of functions called within the > loop -- including the calls to methods that can be performed by just > about every operation in the language. There are other ways. Ways that do change the semantics of the language somewhat, making it somewhat less dynamic, but my understanding is that Guido is actually positive to doing so. It is quite easy to determine whether some code modifies a specific binding in its own local or global scope. (The use of 'exec' would of course make the analyzer assume that the binding *is* changed.) You could then add the restriction that a module may not change the bindings in another modules global or builtin namespace. > It seems a very worthy > research project, which might take good advantage of the results > of the pypy project (there is plenty of such advanced research that > is scheduled to take place as part of pypy, but there is also surely > space for a lot of other such projects; few are going to bear fruit, > after all, so, the more are started, the merrier). It almost sounds as if you are implying that doing analysis of the entire program is something that is almost unheard of. I don't think you are actually meaning that, but for the benefit of others, it might be worth noting that there have been compilers that *do* data flow analysis on entire programs available for several years now. The MIPS C compiler, or rather the linker, did global register allocation more than a decade ago, and since then other compilers have done even more ambitious analysis of entire programs. I am under the impression that some LISP compilers have done this too. (But, yes, I do realize that it is more difficult to do this in a dynamic language like Python than in a statically typed language like C.) If you, as I suspect, really mean that to implement this kind of code analysis in Python is lots of hard work and involves lots of trial-and-error testing to determine what is worth-while, then I heartily agree. > As there is really no good use case for letting user code rebind the > built-in names None, True, and False, making them keywords has almost > only pluses (the "almost" being related to backwards compatibility > issues), Note that I have no quibbles with this reasoning. -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "You cannot achieve the impossible without ! bellman @ lysator.liu.se attempting the absurd." ! Make Love -- Nicht Wahr! From joconnor at cybermesa.com Fri Nov 21 11:08:44 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Fri, 21 Nov 2003 09:08:44 -0700 Subject: Question about Objects In-Reply-To: References: Message-ID: SBrunning at trisystems.co.uk wrote: >>From: campbell95 [SMTP:campbell95 at cox.net] >>I've been hacking visual basic for several years and understand the basic >>concepts of OOP. That said, I'm stumped here with the Python Class. >> >>Here is the Class... >> >> >> >>>class Test: >>> def __init__(self, something): >>> self.something = something >>> >>> def getSomething(self): >>> return self.something >>> >>> >>This is what I get when I test it. Why does not return the >>value of ? is obvious that has a value. I fear this >>is a simple oversight but I've racked my brain for hours looking at online >>doc's and examples. Thanks for any help!! >> >> >> >>>Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on >>> >>> >>win32 >> >> >>>Type "copyright", "credits" or "license()" for more information. >>>**************************************************************** >>>IDLE 1.0 ==== No Subprocess ==== >>> >>> >>>>>>x = Test("Microsoft Sucks") >>>>>>x.getSomething >>>>>> >>>>>> >>>>> >>> >>0x00C01940>> >> >> >>>>>>x.something >>>>>> >>>>>> >>>'Microsoft Sucks' >>> >>> > >getSomething *will* return something - but you have to *call* it. > >See, a function (or method, a.k.a a bound method) is also an object. >"x.getSomething" with no brackets at the end just *refers* to this object. >To call the function, try "x.getSomething()". > >This can be very useful at times, 'cos it allows you to pass functions >around the same way you do with any other object types. But it also confuses >VBers. ;-) > > To help illustrate the point: >>> class Test: def __init__(self, something): self.something = something def getSomething(self): return self.something >>> x = Test("Microsoft Sucks") >>> y = x.getSomething >>> y() 'Microsoft Sucks' This is the same as the OP except it assigns x.getSomething to a variable. y now holds the function, and can be called with y() From gmuller at worldonline.nl Thu Nov 27 14:49:54 2003 From: gmuller at worldonline.nl (GerritM) Date: Thu, 27 Nov 2003 20:49:54 +0100 Subject: pymat and Matlab6.5 References: Message-ID: <3fc65537$0$41749$5fc3050@dreader2.news.tiscali.nl> "John Hunter" schreef in bericht news:mailman.1148.1069942761.702.python-list at python.org... <...snip...> > If you want to use scipy on win32, I recommend the enthought edition > of python, which comes with scipy, wxpython, vtk and other goodies > built in > > http://enthought.com/python/ > > They do have a version for python2.3. > > I was surprised not to see a win32 python2.3 binary for scipy on the > scipy site. > > John Hunter > This distribution sounds very promising. At this moment it appears to be rather disjunct to the ActiveState distro, where the windows specific packages are prominent Thank you for bringing this distribution to my attention! kind regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From hungjunglu at yahoo.com Mon Nov 17 16:35:36 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 17 Nov 2003 13:35:36 -0800 Subject: Origin of the term "first-class object" Message-ID: <8ef9bea6.0311171335.356a7af6@posting.google.com> Hi, Does anybody know where this term comes from? "First-class object" means "something passable as an argument in a function call", but I fail to see the connection with "object class" or with "first-class airplane ticket". I just find the name a bit strange. Also, if there are first-class objects, what would the second-class objects or economy/tourist class objects be? :) Just wondering, Hung Jung From fBechmann at web.de Sun Nov 9 05:25:13 2003 From: fBechmann at web.de (Frank Bechmann) Date: 9 Nov 2003 02:25:13 -0800 Subject: how to get a list of available drives (partitions) in windows Message-ID: yes, that's the simple question: is there some python standard or 'Python for Windows Extensions' functionality to iterate or list-return the available drives ('A:', 'B:', 'C:', ...) on a machine running windows? Thx in advance. From newsgroups at jhrothjr.com Fri Nov 14 14:43:58 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 14 Nov 2003 14:43:58 -0500 Subject: for what are for/while else clauses References: Message-ID: "David C. Fox" wrote in message news:nr9tb.200590$Fm2.189136 at attbi_s04... > Diez B. Roggisch wrote: > > > Hi, > > > > today I rummaged through the language spec to see whats in the for ... else: > > for me. I was sort of disappointed to learn that the else clauses simply > > gets executed after the loop-body - regardless of the loop beeing entered > > or not. > > I didn't realize that for...else existed, but according to the language > reference, the else clause gets executed unless the loop body exited due > to a break statement. Yep. It's one of the three termination conditions for a loop. The problem is that it's a really bad name, and the termination condition I'm most interested in catching is the one where the loop didn't execute at all. John Roth > > David > From gandalf at geochemsource.com Wed Nov 26 14:25:26 2003 From: gandalf at geochemsource.com (Gandalf) Date: Wed, 26 Nov 2003 20:25:26 +0100 Subject: Shell: run script References: Message-ID: <3FC4FE26.80109@geochemsource.com> > > > > >>>>python filename >>>>python filename.py >>>>run filename >>>>run filename.py >>>>/run filename >>>>/run filename.py >>>> >>>> From your separator, I guess you are using UNIX. Please ensure that the first line is something like this: #!/usr/bin/env python Very important: you should not have CR+LF at the end of the line, only LF. Otherwise the shell will think that the CR is the part of the program and it will be searching for an interpreter with this name: 'python' + CR :-/ L 1.0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjl at pobox.com Sat Nov 8 08:07:48 2003 From: jjl at pobox.com (John J. Lee) Date: 08 Nov 2003 13:07:48 +0000 Subject: Scripting on windows 2000 References: Message-ID: <87islv9fff.fsf@pobox.com> "Ryan Smith" writes: > I am new to the list and python community as well. I was wondering if anyone > knows of any good python books emphasizing Windows 2000? I am a network > engineer in an Active Directory environment and I have found serveral uses > for python, and I need to find a book that emphasizes features of python 2.2 > and programming in this type of environment. I apologize for the rather > basic question, but I wasn't sure exactly were to ask. Other than the stuff Alex mentioned, the Python Cookbook (edited by Alex himself, and David Ascher) contains some Windows recipes. But it's well worth having in itself (and is certainly complementary to the online Python Cookbook from whence it came). One thing that Hammond and Robinson doesn't cover, and that you might eventually need, is ctypes. Always make sure that win32all doesn't cover what you need first, though. http://starship.python.net/crew/theller/ctypes/ win32all is available separately or bundled with Python in ActiveState's distribution: http://starship.python.net/crew/mhammond/ http://www.activestate.com/Products/ActivePython/ Samples from Hammond & Robinson: http://www.oreilly.com/catalog/pythonwin32/chapter/ John From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Nov 18 13:24:59 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 18 Nov 2003 19:24:59 +0100 Subject: spec file parsing In-Reply-To: <20031118190353.1a1fba93.mjancar@suse.cz> References: <20031118190353.1a1fba93.mjancar@suse.cz> Message-ID: <3fba63fb$0$58700$e4fe514c@news.xs4all.nl> Marian Jancar wrote: > Is there a module for parsing spec files available? What are spec files? --Irmen From john at rygannon.com Tue Nov 4 06:35:35 2003 From: john at rygannon.com (John Dean) Date: Tue, 4 Nov 2003 11:35:35 GMT Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0310312008.ce341ea@posting.google.com> <87r80sdyb1.fsf@pobox.com> <7xn0bg6njb.fsf@ruckus.brouhaha.com> <7x7k2jpti9.fsf@ruckus.brouhaha.com> <3fa6a66a$0$12690$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <3fa78ee1$0$12706$fa0fcedb@lovejoy.zen.co.uk> On 4-Nov-2003, GrayGeek wrote: > Are there other, licensed technologies combined with ReKall, such as > database drivers, etc., which would cripple a GPL version of ReKall? I would say not. We include drivers for MySQL, PostgreSQL and xBase. We do have drivers for DB2, Oracle, Informix, Sybase, and ODBC, but I suppose they would have to be sold as commercial plugins, much as we don't want to -- Best Regards John From R.Brodie at rl.ac.uk Tue Nov 4 11:33:07 2003 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 4 Nov 2003 16:33:07 -0000 Subject: Using debug print routine inside assert References: <8765i072jh.fsf@titan.staselog.com> <0cPpb.91638$e5.3380437@news1.tin.it> Message-ID: "Alex Martelli" wrote in message news:0cPpb.91638$e5.3380437 at news1.tin.it... > Richard Brodie wrote: > ... > > def defer(f, *args): > > f(*args) > > Hmmm, this doesn't defer anything -- the moment you call defer, it in > turns calls f _at once_. Yeah, I was just sketching out a pattern on how to write the debug routine but overedited it to omit the if (debug) part. Then compounded my error by conflating the two debug implementations later. Thanks for expressing more clearly and correctly what I was thinking. On the unittest vs. logging debate: logging can be useful at the level, where you couldn't deduce from the code what should be happening. For example, if you have to interoperate with third-party, possibly buggy clients. "What requests have been rejected as malformed?" is a question unit tests can't address. OTOH if you are adding debug code to find how an individual unit works, that probably is bad practice. From messageboardfan1 at yahoo.com Tue Nov 25 09:02:55 2003 From: messageboardfan1 at yahoo.com (ataraxia2500) Date: Tue, 25 Nov 2003 15:02:55 +0100 Subject: wxpython and telnet newbie Message-ID: <3fc36157$0$4361$79c14f64@nan-newsreader-01.noos.net> I found that little howto on the wxpython wiki: http://wiki.wxpython.org index.cgi/WxHowtoSmallTelnetClient I copied the whole thing and past it as is then I tried to run it but I got an error. this is the error message I got: /usr/share/themes/Geramik/gtk-2.0/gtkrc:25: error: unexpected identifier `GtkButton', expected character `}' Traceback (most recent call last): File "wxtelnet.py", line 70, in ? frame = TelnetFrame(None, -1, sys.argv[1]) IndexError: list index out of range maybe I should modify some lines, I'm not sure. thanx in advance From frithiof.jensen at removethis.ted.ericsson.dk Wed Nov 5 04:33:11 2003 From: frithiof.jensen at removethis.ted.ericsson.dk (Frithiof Andreas Jensen) Date: Wed, 5 Nov 2003 10:33:11 +0100 Subject: best GUI toolkit for python: tkinter, wxPython or what? References: <3fa13dd3.2565248@news.dsl.pipex.com> <87he1j52yc.fsf@theasylum.dyndns.org> Message-ID: "Tim Lavoie" wrote in message news:87he1j52yc.fsf at theasylum.dyndns.org... > Perhaps this might help: > http://vtcl.sourceforge.net/ Yeah it might, Thanks! PS; Q: Why does Mike Tyson cry while making love? A: It's the pepper spray! From aahz at pythoncraft.com Sat Nov 15 09:54:33 2003 From: aahz at pythoncraft.com (Aahz) Date: 15 Nov 2003 09:54:33 -0500 Subject: Books I'd like to see References: Message-ID: In article , Scott Chapman wrote: > >I'd like to see a good introduction to Python for brand new programmers >that starts with Python's object orientation (at least as the >assumption, if not explicitly dealing with objects at the beginning). > >I've looked over every book on the market and the Net that is >introductory to Python and none of them emphasize Python's uniqueness >and power. It is not possible to rightly understand Python without >understanding that virtually everything except the keywords are >objects. This is the year 2003 and books are still introducing >Structured Programming paradigms and then re-teaching by introducing >Object Oriented later. This is Wrong! :-) Hmmmm.... Could you give a bit of detail about what kind of approach would work? Without adding mental clutter to the explanations? I was thinking about this a bit, and I find it difficult to explain even what an object *is* without some prior background in computers and programming. There's also the issue that Python methods are functions, so it's necessary to cover functions and modules before classes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From a.schmolck at gmx.net Fri Nov 7 18:32:30 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 07 Nov 2003 23:32:30 +0000 Subject: binary string question References: Message-ID: Dan Jones writes: > Hello, > > I'm trying to figure out how to get bit operators to work on a binary > string. More below, but are you sure you really need to do this? > This is what I'm trying to do: > > list(frame) #where frame is a binary string This has no effect (apart from wasting ressources). You create a new list from the string frame, but don't use it any further. You presumably intended frame = list(frame) > y = frame[x] << 8 > > It gives me a TypeError. Whats the best way to get around that? Well see below (not that I can see how rightshifting by 8 is going to make much sense if you want to treat a string as collection of bytes). > I think the struct module may be what I'm looking for, You want to treat each item in the string the same, right? In that case use array. > if so could someone give me an example? Here you go: >>> import array >>> frame = "abcde" >>> frameAsArray = array.array('b', frame) >>> frameAsArray[0] >>= 1 >>> frameAsArray.tostring() '0bcde' > Also, is there a better way to be able to access individual bytes than > converting the string to a list? see above 'as From kylotan at hotmail.com Wed Nov 26 00:27:08 2003 From: kylotan at hotmail.com (Kylotan) Date: 25 Nov 2003 21:27:08 -0800 Subject: Treestructure in SQL References: Message-ID: <153fa67.0311252127.1449df70@posting.google.com> "Thomas Weholt" <2002 at weholt.org> wrote in message news:... > Now I need either a SQL-statement compatible with SQLite or some code > snippet that will give me : > > Games > Games, Counter-strike > Games, Boardgames > Programming > Programming, Python > Programming, Python, Web > Programming, XML Is it a big problem to make several SELECTS in a loop? The first select gets all rows where parent_id = 0. Then print that node, and then for each row in that SELECT result, search for all nodes that have parent_id equal to this one, and so on. You probably want to do it recursively rather than iteratively if you want depth-first traversal as shown in your example. Alternatively, if I was always showing the entire list of nodes, I'd just do one SELECT and create their tree order in code. -- Ben Sizer From mis6 at pitt.edu Thu Nov 20 23:16:13 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 20 Nov 2003 20:16:13 -0800 Subject: controlling method execution References: Message-ID: <2259b0e2.0311202016.3fa2c734@posting.google.com> "mic" wrote in message news:... > Is it possible to control method exectution using similiar mechanism as with > get/setatrribute special methods for attributes? I'd like to have every (or > some of ) method of class instance run common code defined outside the class > without making any explicit references to it. > To give an example, I'd like to prepare secure environment, in which users > could execute only methods that can be accessed by them. IMO the most > universal way to do it would be to run automatically authorisation routine > before every method execution. > > Regards, > > Michal setattr/getattr work with methods just as with attributes, provided you define your setattr/getattr in the right place, i.e. in the metaclass. Google for "simionato frozen" in c.l.py (first hit) and you will see an example of how to make methods "safe" under accidental overriding with this trick. Also, you may want to look at properties. For what concern your problem (securing method execution) here I show you another metaclass based solution, which is the less intrusive solution (i.e. you don't change the original class). Of course, the password mechanism I show in this example is ridicolous from the point of view of security, but you can replace the password step with any kind of "secure" identification mechanism you want. Needless to say, security goes to zero if people have access to Python and they know how to use its dynamical capabilities. Still, the method may prevent accidental method calls: ### protecting methods from execution #### PASSWD="xxx" class ProtectionError(Exception): pass def securecall(func,*args): know_the_passwd=raw_input("Password required to use this method:")==PASSWD if know_the_passwd: return func(*args) else: raise ProtectionError("Wrong password given") class Secure(type): def __init__(cls,n,b,d): for k,v in d.iteritems(): if hasattr(v,"__doc__") and v.__doc__=='protected': setattr(cls,k,lambda self,*args: securecall(v,self,*args)) class C(object): __metaclass__=Secure def f(self,*args): "protected" print "Doing something if the user know the password" C().f() # END Here you protect your methods by using a docstring containing the word "protected". It is easy to try variations of this idea. HTH, Michele From try_vanevery_at_mycompanyname at yahoo.com Fri Nov 14 20:48:19 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Fri, 14 Nov 2003 17:48:19 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> <2u1tb.25127$hV.934365@news2.tin.it> Message-ID: Maxim Khesin wrote: > Or perhaps Pythonistas are smarter than other people :) and buy their > books online. That wouldn't make me smarter. I live 5 blocks away from Barnes & Noble downtown. Lotsa other people are similarly well situatated according to where they work. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA Brandon's Law (after Godwin's Law): "As a Usenet discussion grows longer, the probability of a person being called a troll approaches one RAPIDLY." From op73418 at mail.telepac.pt Tue Nov 25 12:56:22 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Tue, 25 Nov 2003 17:56:22 +0000 Subject: Bug or Feature? References: <2259b0e2.0311240603.549943b3@posting.google.com> <9cf48f3e1bcf524ab4ad581a061d1852@news.teranews.com> <07279b32fe8f5b18377a1df8467647b6@news.teranews.com> Message-ID: <2e57svo4jd15chvs9cfqr3ninoade836ng@4ax.com> On Tue, 25 Nov 2003 16:04:57 +0100, Stephan Diehl wrote: [snip] > >You might have noticed, I was talking about Mathematics, not the imperfect >implementation of it in computers :-) >To have division as a meaningfull operation, the set in question must be a >group under the '*' operation (See for example >"http://en2.wikipedia.org/wiki/Group_(mathematics)" ) >The point is, that division is the reverse operation to multiplication. But when talking of "numbers" a group is not enough, you want a field - a set with two operations (in some situations something weaker, like integral domains, is enough). In fields, such as real numbers, complex numbers, p mod integers, p-adic fields, etc. every number has a multiplicative inverse *except* the zero. Pedantically yours, G. Rodrigues From francisgavila at yahoo.com Mon Nov 3 17:37:55 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 3 Nov 2003 17:37:55 -0500 Subject: EIBTI References: Message-ID: "Mike Rovner" wrote in message news:mailman.395.1067896584.702.python-list at python.org... > Emile van Sebille wrote: > > What does this mean? > > Explicit Is Better Than Implicit > There's more than a little bit of irony in this exchange.... -- Francis Avila From info at kandidates.com Sun Nov 30 22:19:59 2003 From: info at kandidates.com (Kandidates.com) Date: Mon, 01 Dec 2003 03:19:59 GMT Subject: Python and Zope Jobs Yahoo Group Message-ID: Python and Zope Jobs Yahoo Group http://groups.yahoo.com/group/pythonzopejobs From CousinStanley at hotmail.com Sun Nov 23 12:55:49 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Sun, 23 Nov 2003 10:55:49 -0700 Subject: PythonMagick_writeImages References: Message-ID: Achim .... This problem doesn't seem to be unique to JPG files and also shows up with the wxPython/PythonMagick example in the current tutorial posted at .... http://www.procoders.net/moinmoin/PythonMagick python wxp_pm.py Magick: Failed to close module ("UnregisterPNGImage: The operation completed suc cessfully. "). Magick: Failed to close module ("UnregisterRGBImage: The operation completed suc cessfully. As with most of the simple examples from the original PythonMagick tutorial, with the exception of the writeImages function noted in my original post and a different problem with example4.py , this wxp_pm.py program seems to do the desired image processing as expected in spite of the Failed to close module error .... The versions of the original PythonMagick tutorial that I use along with their output images can be found at .... http://fastq.com/~sckitching/Python/PythonMagick_tut_0.zip [ 248 KB ] It would be interesting to know if these run OK with the Standard Python 2.3 distribution in order to determine if there might be some quirk with the Enthought Edition or with my setup .... In the meantime, I will look for the GraphicsMagick API mailing list .... -- Cousin Stanley Human Being Phoenix, Arizona From ajs at optonline.net Sat Nov 22 23:40:59 2003 From: ajs at optonline.net (Arthur) Date: Sat, 22 Nov 2003 23:40:59 -0500 Subject: Python's simplicity philosophy Message-ID: <001401c3b17b$fe40f6f0$1c02a8c0@BasementDell> Alex wrote: >Arthur wrote: >> Rainer writes - >> >>>In one line: >>>x = sum(seq) >>>And that is why 'sum' is a worthwhile part of the Python >standard library > >> The issue that concerns me is the analysis, decision-making on this kind >> of issue on what is essentially an "as if" basis - as if Numeric and its >> line of descent were not defacto standard library for numeric processing >> in Python. >Oh, they are -- particularly for _advanced_ array processing involving >multi-dimensional arrays. That's why I covered Numeric in the Nutshell. [snip] >I'm not sure what you're objecting to. Is it the fact that the same >name (built-in or within module Numeric) is used for very similar (but >not identical, due to implementation optimizations -- as well as to >multidimensional array issues) functionality? To me, that seems a >very good thing (that's part of why I never even considered other names >for sum, such as add or total, when I first proposed it as a builtin). Somebody was concerned enough to file a bug report on the naming of the "sum" built-in: http://mail.python.org/pipermail/python-bugs-list/2003-June/018314.html I am far removed from an indepth understanding of all the factors that led to the decision. The net result confuses me, though. The simplicity philosophy, to me, says "what one naively might expect, is normally one gets". The "sum" built-in does not violate that principle directly, But does, indirectly, IMO. IDLE 1.0 >>> a=[1,2,3] >>> a*2 [1, 2, 3, 1, 2, 3] >>> a/2 Traceback (most recent call last): File "", line 1, in -toplevel- a/2 TypeError: unsupported operand type(s) for /: 'list' and 'int' >>> sum(a) 6 >>> "sum" standalone is fine. But is unintuitively standalone. When one steps back from the trees a bit. IMO. Art From tjreedy at udel.edu Thu Nov 6 22:47:19 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Nov 2003 22:47:19 -0500 Subject: System Clock References: <9SBqb.8942$R13.490724@ursa-nb00s0.nbnet.nb.ca> Message-ID: "James Harriman" wrote in message news:9SBqb.8942$R13.490724 at ursa-nb00s0.nbnet.nb.ca... > Hi, > > I need to be able to measure a time interval in milliseconds on a windows > machine. I have tried using time.clock() but it appears to measure time in > seconds...Is there a way to measure time more precisely? For floats, what matters is the resolution (precision), not the unit. On AMDK2-385, Win 98: >>> a=time.clock(); time.sleep(1); print time.clock()-a 1.01412863105 # correct, seconds >>> time.clock()-time.clock() -3.0171474548978949e-005 >>> time.clock()-time.clock() -3.1847667571582861e-005 >>> time.clock()-time.clock() -3.100957104607005e-005 >>> time.clock()-time.clock() -2.933337799504443e-005 >>> time.clock()-time.clock() -3.0171474577400659e-005 >>> time.clock()-time.clock() -3.100957104607005e-005 >>> time.clock()-time.clock() -3.1009571102913469e-005 >>> time.clock()-time.clock() -2.9333378051887848e-005 This is reproducibly .03+ milleseconds (minus because earlier - later) == 30 microseconds. Now speed up a bit: >>> tc = time.clock >>> tc()-tc() -2.8495281526375038e-005 >>> tc()-tc() -2.7657185000862228e-005 >>> tc()-tc() -3.017147452055724e-005 >>> tc()-tc() -2.6819088532192836e-005 >>> tc()-tc() -2.8495281526375038e-005 >>> tc()-tc() -2.7657185000862228e-005 >>> tc()-tc() -2.8495281526375038e-005 >>> tc()-tc() -2.7657185000862228e-005 >>> tc()-tc() -2.7657185000862228e-005 The average is about 28 microsecs, so time.clock lookup appears to be measurebly about 1 microsecond, but anything much smaller would be lost in the noise on this system. (Oddly, I also get this: >>> tc()-tc(); tc()-tc() -2.84952814126882e-005 -1.4247640820030938e-005 which I have not figured out yet) Terry J. Reedy From jkrepsBEAR at FISHneb.rr.com Tue Nov 11 09:25:57 2003 From: jkrepsBEAR at FISHneb.rr.com (GrayGeek) Date: Tue, 11 Nov 2003 14:25:57 GMT Subject: Rekall and associated software go 100% GPL References: <3fae9c76$0$12714$fa0fcedb@lovejoy.zen.co.uk> Message-ID: John Dean wrote: > Hi > > It gives me great pleasure to inform you that Rekall, the cross-platform > alternative to MS Access, is now totally GPL. So please visit > http://www.totalrekall.co.uk and download download a copy for yourself. In > order for you to be able to download you must register with the Total > Rekall Portal. The reason we have have made this a requirement is because > we would like to be able to notify everybody when a new version becomes > available. We are presently working on V2.2.0 and I am sure you would not > like to miss out. > > You should also be aware that in order for for us to continue the future > development of Rekall we will have to charge for technical support, > customisation, training and consulting, therefore, now that we have gone > wholly GPL, you will have to take out a technical support subscription. I > will post information relating to support levels and pricing once we > worked out the detail. In the meantime may I suggest that you sign up to > our mailing list. Instructions can be found at the bottom of the home > page. > mmm, either the registration process is overloaded, or it is not functioning. After registering I failed to receive the confirmatory email. (Yes, my data was correct). Anyone else notice this? I see that all the previous msgs are on the 9th, but none after that. -- - GrayGeek From M.Waack at gmx.de Mon Nov 10 12:51:30 2003 From: M.Waack at gmx.de (Mathias Waack) Date: Mon, 10 Nov 2003 18:51:30 +0100 Subject: Restarting a process References: <0actqvs0gfg14ustm77lg6cvl4svr5fflo@4ax.com> Message-ID: <2qv481-dv3.ln1@valpo.de> Simon Faulkner wrote: > I have written a small cgi script which updates the config file for > a www proxy server and I need to restart the service when I save > out the config file. > > /etc/rc.d/init.d/danguardian restart > > will do the trick but I can't run it as the apache user > > Any ideas? Of course: use another user. And another newsgroup. Or, to be more polite: have a look at sudo. This way its easy (and relative secure) to run a command as a different user without a password. Mathias From joconnor at cybermesa.com Wed Nov 12 16:29:58 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Wed, 12 Nov 2003 21:29:58 GMT Subject: Python programmers required (High tax free savings package) References: Message-ID: <3fb2a615.67745913@news.cybermesa.com> On Wed, 12 Nov 2003 22:26:50 +0100, "Jegenye 2001 Bt" wrote: > >tglinternational wrote in message >news:mailman.655.1068634052.702.python-list at python.org... >> Please check details on www.tgl-international.com/jobs.html Send >> your CV / resumes alongwith covering letter to steve at tgl- >> international.com >> >> > >Huh, they have to really pay a lot so that one would work in the Saudi >Arabian desert... ;) If a telecommute would be possible, I'd jump on it. But relocation to Dhahran is probably not in my career path these days From NoixeTOGLIMI at hotmail.com Sun Nov 9 09:04:01 2003 From: NoixeTOGLIMI at hotmail.com (Noixe) Date: Sun, 09 Nov 2003 14:04:01 GMT Subject: Help for unicode References: <3fad6fb5$0$58715$e4fe514c@news.xs4all.nl> <2perb.101236$vO5.3965040@twister1.libero.it> Message-ID: "Martin v. L?wis" ha scritto: > The character U+2205 is EMPTY SET; your terminal is not capable of > displaying that symbol. Ah... and not exist one solution? -- Noixe From mensanator at aol.compost Sun Nov 30 22:19:07 2003 From: mensanator at aol.compost (Mensanator) Date: 01 Dec 2003 03:19:07 GMT Subject: Python Learning Foundation References: Message-ID: <20031130221907.12213.00000936@mb-m26.aol.com> >Subject: Python Learning Foundation >From: rstephens at vectron.com (Ron Stephens) >Date: 11/30/2003 7:40 PM Central Standard Time >Message-id: > >The newly rechristened Python Learning Foundation is a web site >dedicated to the assistance of people learning the Python programming >language. Features include: > >1. Daily lists of new and recent Python-related web articles, >Sourceforge projects, and Vaults of Parnassus listings. These are >generated using Hans Nowak's Python web spider, mygale.py, and are >automatically updated each day. (You can visit Han's interesting blog >at zephyrfalcon ) > >2. Now, there are also daily postings of new and recent web articles, >Sourceforge projects and etcetera for four additional categories, >Zope, Jython, Tkinter, and wxPython, as well as historical listings of >web articles on these subjects. Other specific topics can be covered >regularly upon user request. > >3. Links to 76 online tutorials about Python and Python related >subjects. > >4. More than 28 reviews of books about Python. > >There are many other topics and features covered in the web site, and, >of course, the best is yet to come. > >Please visit the Python >Learning Foundation. Would a URL be too much to ask for? -- Mensanator Ace of Clubs From http Sun Nov 30 03:00:14 2003 From: http (Paul Rubin) Date: 30 Nov 2003 00:00:14 -0800 Subject: Filtering through an external process References: <7xllpyyl1s.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xptfaxp4h.fsf@ruckus.brouhaha.com> "Raymond Hettinger" writes: > The time machine lives! > > ========================= > Add this file: Lib/encodings/pig.py > ---------------------------------------- > "Pig Latin Codec -- Lib/encodings/pig.py" Chuckle :). But I had in mind a more general purpose means of running external processes. From tuanglen at hotmail.com Tue Nov 25 04:27:05 2003 From: tuanglen at hotmail.com (Tuang) Date: 25 Nov 2003 01:27:05 -0800 Subject: Parsing strings -> numbers References: Message-ID: Skip Montanaro wrote in message news:... > tuanglen> I've been looking all over in the docs, but I can't figure out > tuanglen> how you're *supposed* to parse formatted strings into numbers > tuanglen> (and other data types, for that matter) in Python. > > Check out the locale module. From "pydoc locale": > > Help on module locale: > > NAME > locale - Locale support. > > FILE > /Users/skip/local/lib/python2.4/locale.py > > MODULE DOCS > http://www.python.org/doc/current/lib/module-locale.html > > DESCRIPTION > The module provides low-level access to the C lib's locale APIs > and adds high level number formatting APIs as well as a locale > aliasing engine to complement these. > > ... > > FUNCTIONS > atof(str, func=) > Parses a string as a float according to the locale settings. > > atoi(str) > Converts a string to an integer according to the locale settings. > > ... > Thanks for taking a shot at it, but it doesn't appear to work: >>> import locale >>> locale.atoi("-12,345") Traceback (most recent call last): File "", line 1, in ? File "C:\Python2321\lib\locale.py", line 179, in atoi return atof(str, int) File "C:\Python2321\lib\locale.py", line 175, in atof return func(str) ValueError: invalid literal for int(): -12,345 >>> locale.getdefaultlocale() ('en_US', 'cp1252') >>> locale.atoi("-12345") -12345 Given the locale it thinks I have, it should be able to parse "-12,345" if it can handle formats containing thousands separators, but apparently it can't. If Python doesn't actually have its own parsing of formatted numbers, what's the preferred Python approach for taking taking data, perhaps formatted currencies such as "-$12,345.00" scraped off a Web page, and turning it into numerical data? Thanks. From joconnor at cybermesa.com Sat Nov 8 11:12:25 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Sat, 08 Nov 2003 16:12:25 GMT Subject: Pure Aspect-Oriented Program: an example References: <8ef9bea6.0311052119.4f5ab5d6@posting.google.com> <8ef9bea6.0311072237.3f991318@posting.google.com> Message-ID: <3fad15a3.165075860@news.cybermesa.com> On 7 Nov 2003 22:37:27 -0800, hungjunglu at yahoo.com (Hung Jung Lu) wrote: >Richie Hindle wrote in message news:... >> >> Fantastic! That's the best introduction to the concepts of AOP I've seen. >> Many thanks for a very clear and thought-provoking article. >> >> Now please implement it for Python, including your proposed IDE. 8-) > >Yeah, right. :) > >I do realize that people are converging in their ideas. AOP is >becoming more and more clear with each passing day. That's really >exciting. But I believe things have not yet finalized, and I am not a >"marketoid" to go out and sell half-baked ideas. :) > >Java folks have economical resources, but their language puts so much >handcuff on them that AOP there is kind of hard to use. Ruby is >perhaps the language that's easiest to accomodate, and Python comes a >close second. As for IDEs, you can bet Java folks will have something >before anyone else. Although I am not sure why people'd keep investing >effort into such a rigid language. > AFAIK, Aspect Oriented Programming is already available in a few Smalltalk dialects, possibly even support within the IDEs From bgailer at alum.rpi.edu Sun Nov 9 18:02:07 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 09 Nov 2003 16:02:07 -0700 Subject: try...finally is more powerful than I thought. In-Reply-To: <3FABB15C.6BB2C44A@hotmail.com> References: <3faab4e8$0$559$b45e6eb0@senator-bedfellow.mit.edu> <3FABB15C.6BB2C44A@hotmail.com> Message-ID: <6.0.0.22.0.20031109160059.031929c0@66.28.54.253> At 07:51 AM 11/7/2003, Alan Kennedy wrote: >[Brian Kelley] > > How is [try..finally] working internally? Does > > the finally get executed when try code block goes out of scope? This > > would happen during a return or an exception which could explain the > > magic. > > >From the Python Language Reference > >http://www.python.org/doc/current/ref/try.html > >""" >The try...finally form specifies a `cleanup' handler. The try clause >is executed. When no exception occurs, the finally clause is executed. >When an exception occurs in the try clause, the exception is >temporarily saved, the finally clause is executed, and then the saved >exception is re-raised. If the finally clause raises another exception >or executes a return or break statement, the saved exception is lost. >A continue statement is illegal in the finally clause. (The reason is >a problem with the current implementation - this restriction may be >lifted in the future). The exception information is not available to >the program during execution of the finally clause. >""" Which is followed by """When a return, break or continue statement is executed in the try suite of a try...finally statement, the finally clause is also executed `on the way out.' A continue statement is illegal in the finally clause. (The reason is a problem with the current implementation -- this restriction may be lifted in the future).""" which is what applies to the examples cited above. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.537 / Virus Database: 332 - Release Date: 11/6/2003 From donn at u.washington.edu Thu Nov 13 12:49:33 2003 From: donn at u.washington.edu (Donn Cave) Date: Thu, 13 Nov 2003 09:49:33 -0800 Subject: program surgery vs. type safety References: <9a6d7d9d.0311120822.553cd347@posting.google.com> Message-ID: In article , Alex Martelli wrote: ... > I _know_ I'd feel differently if e.g. management didn't LET > me do TDD and systematic testing because of deadline pressures. > But I don't think I'd stay long in a job managed like that;-). Nice for you. Depending on the application, that's an option for me too - but unlikely to be combined with the option to write in Python. Sometimes I believe a lot of the disparity of reactions to programming languages comes from the fact that we live in different worlds and have no idea what it's like to work in other collaborative models, development tools, etc. It makes little difference here anyway, since as far as I can tell no language remotely like Python could productively be adapted to static typing. In my world, the applications I write and the free open source software I get from elsewhere and have to modify, static type analysis looks like more help than burden to me. See you next time around. Donn Cave, donn at u.washington.edu From a.schmolck at gmx.net Thu Nov 20 07:40:51 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 20 Nov 2003 12:40:51 +0000 Subject: beeping under linux References: <99dce321.0311191545.228fffbd@posting.google.com> Message-ID: dw-google.com at botanicus.net (David M. Wilson) writes: > Alexander Schmolck wrote in message news:... > > > This is only partly a python question, but what is the easiest way to get > > python to (reliably) beep under linux? By reliably I mean that ``print > > "\b"`` won't do because it depends on the terminal settings -- so I guess > > I'm looking for some simple way to more or less directly access the > > internal speaker (maybe writing to something in /dev/). > > If by 'reliably', you mean 'override the users choice of having the > speaker on or off', then I think you need a rethink. :) Being the (sole) user (and not suffering from multiple personality disorder), such an override seems unlikely. As I mentioned in my reply to Ben Finney, apart from the fact that I simply have no idea how to configure comint (or kterm for that matter -- cerainly not via settings-bell) for (audible) beeping, for this particular scenario (notification of myself when I'm not necessarily in front of my computer) the standard terminal bell preference settings are not really that relevant anyway. > > There are several utilities about that can do the beeping (and music) > for you, and IIRC even ones that work across platforms. Great, do you know one for linux (that uses the internal speaker and that ideally would be preinstalled or come as a Mandrake rpm)? > > > > [The usage scenario is simply to have an effective way of signalling that a > > long running-process finshed, without me having to constantly look at the > > screen] > > Suggestion: allow a configurable command to be called, so that users > can choose their own notification method, eg. /usr/bin/play (a part of > 'sox'). Sure, I just don't know any suitable command/program. 'as From FBatista at uniFON.com.ar Tue Nov 4 15:57:26 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 4 Nov 2003 17:57:26 -0300 Subject: prePEP: Decimal data type Message-ID: John Roth wrote: #- I can see how what I said could be interpreted that way, but #- I certainly #- didn't mean it for strings. If you understand one thing and I understand another, one of both of us is wrong, :p. Who? In my last example, what do you think that happens? #- It is. I was thinking in terms of a type, not a class. All #- the builtin #- types start with lower class names. OK, so it stays uppercase (as long it's a class). #- What you propose? #- #- - the configuration (precision, flags, etc) is on by-instance basis #- - you have different contexts, and a group of instances with each #- context. #- #- [John Roth] #- More likely the second. My concern here is the usual one with #- singletons and globals. Processing gets very messy when you #- have to operate in several different modes or areas. See the #- difficulties people get into with internationalization when they #- have an application that has to operate in several different #- jurisdictions at once, etc. In another mail, Aahz explains (even to me) that the idea is to have a "context per thread". So, all the instances of a thread belongs to a context, and you can change a context in thread A (and the behaviour of the instances of that thread) without changing nothing on the thread B. So, I think your proposal has future, as long I could finish the Aahz work, ;) #- So we're planning #- on doing a software implementation of a *draft* standard, #- including very complicated facilities that I most #- respectfully think are going to be of marginal #- utility. But is that or is making a Money data type and reinventing the wheel for all its arithmetic behaviour. I can't assure you if somebody ever will use the "not a number" capabilities of Decimal (I think a lot of people will). But that's the specification, :p . Facundo From eltronic at juno.com Mon Nov 10 00:42:19 2003 From: eltronic at juno.com (eltronic at juno.com) Date: Mon, 10 Nov 2003 00:42:19 -0500 Subject: Leo + Python: the ultimate scripting tool: Conclusion Message-ID: <20031110.004438.-163841.2.eltronic@juno.com> On Sun, 9 Nov 2003 21:29:35 -0500 "Terry Reedy" writes: > > "Edward K. Ream" wrote > [lots of stuff about the benefits of Leo over several posts] > > Edward K. Ream email: edreamleo at charter.net > > In response to this series, I sent you a friendly note saying a) I am > considering Leo as a base for a future project and > b) I think there is a problem with a couple of > lines in the code you posted. NameError: name 'c' is not defined? I wondered about that too...(if that was it) but I think the exuberance of being able to script the find/change is totally justified. you can't have too much automation, too many examples or enough right click menus for me. > In response, you sent me the > > ---------- > You recently sent a message to me at the email address > edreamleo at charter.net. To help cope with the ever increasing volume > of > junk e-mail, I am using ChoiceMail, a permission-based e-mail > filtering tool. Your original e-mail is being held by ChoiceMail > until > you complete the following simple one-time process. > Please click on the link > [Click here to request approval] > When your browser opens, fill in your name and a short reason for > wanting to send e-mail to me. If your reason is acceptable, your > first > email and all subsequent e-mails from you will be delivered to me > normally. > ------------ > > I will not beg you to read my bug report. Such a request is *NOT* > a > legitimate 'anti-junk-mail' measure. personal email to an author is rarely welcome as a bug report! although in this case a tossup. if you've checked the sourceforge forums, you would see the nature of the response time to problems of any kind including wild eyed spitballing of ideas is nearly immediate. > > Being unable to communicate directly with you makes > Leo less inviting to me. If I were > to adopt Leo for a project anyway, > I would warn users to not email the above address. not wanting the job of channeling EKR, you must realize the level of spam a project like Leo generates would render any email address unusable in short time. really, it's a painless few clicks & keystrokes, if you can get over your initial reaction. since spam isn't going away, you have to admit this is one of few good solutions. there are additional bug reports and a diary of the Leo dev cycle in LeoPy.leo and LeoDocs.leo and an active forum on sourceforge. http://sourceforge.net/forum/?group_id=3458 e please forward all spam to "me" ________________________________________________________________ The best thing to hit the internet in years - Juno SpeedBand! Surf the web up to FIVE TIMES FASTER! Only $14.95/ month - visit www.juno.com to sign up today! From newsgroups at jhrothjr.com Tue Nov 18 07:54:03 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 18 Nov 2003 07:54:03 -0500 Subject: PEP 321: Date/Time Parsing and Formatting References: <2ae25c6b.0311172147.65058189@posting.google.com> Message-ID: "Paddy McCarthy" wrote in message news:2ae25c6b.0311172147.65058189 at posting.google.com... > I am in favour of there being an intelligent 'guess the format' > routine that would be easy to use, but maybe computationally > inefficient, backed up by a computationally efficient routine where > you specify the format. The trouble with "guess the format" is that it's not possible to do it correctly in the general case from one sample. Given enough samples of one consistent format, it's certainly possible. However, that's a two pass process. John Roth > > Cheers, Paddy. From alanmk at hotmail.com Fri Nov 21 06:07:19 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 21 Nov 2003 11:07:19 +0000 Subject: jython lacks working xml processing modules? References: Message-ID: <3FBDF1E7.5ADB00B2@hotmail.com> [Jane Austine] > I'm trying to parse an xml file with jython (not through java parsers > like xerces). > > I tried minidom in jython 2.1 and 2.2a but all failed. It's quite likely that your documents contained namespaces. The only parser supported in jython is "xmlproc", because it is pure python. However, "xmlproc" has some significant bugs in relation to namespace processing, IIRC from the last time I looked at it. > What can I do? 1. Use a Java SAX2 parser, write a jython ContentHandler for it, build a Minidom from the events. 2. Use a Java DOM processor (DOM4J, JDOM, etc), and let it build a DOM for you. It would probably be easier if you could give an outline of what you are trying to achieve. For example, do you really need to build an object model? Do you need to use xpath? Do you need to validate structures? Etc, etc. > The last resort would be using java parsers. Then how > can I use them like python xml parsers? It seems like javadom and > javasax has something to do, but I don't know how. If you want to know about using SAX events to build object models, check this old thread on c.l.py. http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=mailman.1058894673.16506.python-list%40python.org If you have any specific questions or face any specific problems, post some details. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From aahz at pythoncraft.com Fri Nov 7 19:10:33 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Nov 2003 19:10:33 -0500 Subject: prePEP: Decimal data type References: Message-ID: In article , Jp Calderone wrote: >On Thu, Nov 06, 2003 at 03:37:52PM -0500, Aahz wrote: >> >> Both are too inconvenient for casual users. I think that for the Money >> subclass, it'll probably make sense to require users to specify an >> explicit Context before the first operation (raising an exception if not >> initialized). For Decimal, using the same defaults as Rexx will >> probably work just fine. > > That sounds like it would work, if you are forced to specify the context >on a per-instance basis. Otherwise, I don't see how two different modules >which wanted to treat Money differently could ever be used together. That doesn't make much sense to me. Can you provide an actual use case? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From jcb at iteris.com Mon Nov 17 19:48:36 2003 From: jcb at iteris.com (MetalOne) Date: 17 Nov 2003 16:48:36 -0800 Subject: Can this be written more concisely in a functional style Message-ID: <92c59a2c.0311171648.6360213d@posting.google.com> 1) def f(xs): for x in xs: if test(x): return True return False I know that I can do (2), but it operates on the whole list and the original may break out early. I want the efficiency of (1), but the conciseness of (2). 2) return True in map(test,xs) From scott_list at mischko.com Thu Nov 13 10:22:48 2003 From: scott_list at mischko.com (Scott Chapman) Date: Thu, 13 Nov 2003 07:22:48 -0800 Subject: Books I'd like to see In-Reply-To: References: Message-ID: <200311130722.48843.scott_list@mischko.com> I'd like to see a good introduction to Python for brand new programmers that starts with Python's object orientation (at least as the assumption, if not explicitly dealing with objects at the beginning). I've looked over every book on the market and the Net that is introductory to Python and none of them emphasize Python's uniqueness and power. It is not possible to rightly understand Python without understanding that virtually everything except the keywords are objects. This is the year 2003 and books are still introducing Structured Programming paradigms and then re-teaching by introducing Object Oriented later. This is Wrong! :-) Guido's Tutorial probably comes the closest. He assumes objects under the hood in his presentation of the material, rather than trying to make Python fit into the old molds. If it had a full set of exercises it would be a good starting text, perhaps needing some fleshing out in areas. Maybe one of the existing books out has exercises at the end of the chapters; another shortcoming IMHO. From http Thu Nov 20 17:30:54 2003 From: http (Paul Rubin) Date: 20 Nov 2003 14:30:54 -0800 Subject: rotor alternative? References: <7x8ymd4hwf.fsf@ruckus.brouhaha.com> <7xptfmyca4.fsf@ruckus.brouhaha.com> <3FBD3C78.3711CF5E@engcorp.com> Message-ID: <7x3cci1xlt.fsf@ruckus.brouhaha.com> Peter Hansen writes: > The docs for Py2.3 say: > """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. """ > > I wonder if the part about "since the first call to this function" would > make this dangerous for your purposes. I don't run Windows and don't want to use something Windows specific. Although, "since the first call to this function" is probably ok. All that's needed is to get a unique number to initialize the internal PRNG with. Hopefully sometime, the Python library will include a C extension to get secure random numbers from the Windows Crypto API. On *nix, they are already generally available from /dev/urandom. From 3seasA at Tthreeseas.DOT.not Mon Nov 10 15:33:14 2003 From: 3seasA at Tthreeseas.DOT.not (3seas) Date: Mon, 10 Nov 2003 20:33:14 GMT Subject: Matrix - Metaphors, Analogies and the REAL References: Message-ID: Scott Chapman wrote: > On Monday 10 November 2003 10:05, 3seas wrote: >> If you are not interested, then don't bitch, its a short message. >> >> http://www.matrixcommunity.org/cgi-bin/ultimatebb.cgi?ubb=get_topic;f-8;t=000918 >> >> I don't know if that link got broken. >> >> -- >> 3 S.E.A.S -- Virtual Interaction Configuration (VIC) >> Changing how we preceive and use computers >> email @ translate not to net, remove capitol letters, one . >> web @ http://threeseas.net > > I just did a whois on the threeseas.net domain and got this back. > I don't know if it's of interest to anyone or not. It's the same guy. > > This email is "short" so according to his criteria, that should make it > Ok, right, regardless of content being on-topic, etc? > > I really don't like email translations. Here's the untranslated version: You knowingly and intentionaly put an email address in a position of beng abused by the viral MS update spam You are guilty of spaming an email address that was protected. -- 3 S.E.A.S -- Virtual Interaction Configuration (VIC) Changing how we preceive and use computers email @ translate not to net, remove capitol letters, one . web @ http://threeseas.net From missive at frontiernet.net Thu Nov 6 17:39:08 2003 From: missive at frontiernet.net (Lee Harr) Date: Thu, 06 Nov 2003 22:39:08 GMT Subject: try...finally is more powerful than I thought. References: <3faab4e8$0$559$b45e6eb0@senator-bedfellow.mit.edu> <3FAABC88.5A696162@engcorp.com> Message-ID: >> def res(): >> try: >> a = 1 >> return >> finally: >> print "do I get here?" >> >> res() >> >> outputs "do I get here?" >> > These results might also be of interest: > >>>> def res(): > ... try: > ... return 1 > ... finally: > ... return 2 > ... >>>> res() > 2 >>>> def res(): > ... try: > ... return 1 > ... finally: > ... return > ... >>>> res() >>>> def res(): > ... try: > ... return 1 > ... finally: > ... pass > ... >>>> res() > 1 >>> def res(): ... print 1 ... try: ... print 2 ... return 3 ... print 4 ... finally: ... print 5 ... >>> res() 1 2 5 3 interesting. From peter at engcorp.com Wed Nov 19 07:49:10 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 19 Nov 2003 07:49:10 -0500 Subject: ANN: PyLogo 0.1 References: <3FBB4345.3020107@domain.invalid> Message-ID: <3FBB66C6.AFAFF104@engcorp.com> user at domain.invalid wrote: > > Just tried it, and this is what I get > ++++++++++++++++++ > Traceback (most recent call last): > File "/usr/bin/pylogo", line 6, in ? > if os.path.basename(os.path.dirname(__file__)) == 'scripts': > NameError: name '__file__' is not defined > ++++++++++++++++++ Probably a sign that it requires Python 2.3 or something... -Peter From alanmk at hotmail.com Wed Nov 26 03:15:28 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 26 Nov 2003 08:15:28 +0000 Subject: Newbi q: show prog References: Message-ID: <3FC46120.67B7B461@hotmail.com> [Christoffer T] > I have tried to write "python file.py" in run, but it just very fast > open and close dos window. So what should I do to get to show the > program. Open a command prompt window in which to execute your script. This can be done in multiple ways: perhaps the easiest is to type "cmd.exe" into the "run" prompt. When the command prompt window appears, change into the directory containing your python source, using the "cd" command. C:\>cd mypythondir And then execute your source as you tried before. In order for the command prompt window to find the python interpreter, you may need to set the environment variable PATH to point at your python installation. For example C:\mypythondir>set PATH=C:\python23;%PATH% As a quick check that this is working, just type "python" at the command prompt: this should bring up the interactive interpreter. Exit this interpreter by typing ctrl-Z and pressing the return key. C:\mypythondir>python Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ^Z Your python script should now run just fine: C:\mypythondir>python file.py but-hey--its-windows-98--anything-could-happen-ly y'rs, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From radam2 at tampabay.rr.com Thu Nov 13 18:47:48 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Thu, 13 Nov 2003 23:47:48 GMT Subject: case-sensitivity References: <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <9l16rv0j7qd0drfap10boab5gsmh7v37o3@4ax.com> Message-ID: On Thu, 13 Nov 2003 14:26:42 GMT, Alex Martelli wrote: >Ron Adam wrote: > ... >> If an option for case insensitivity were implemented it would just be >> a matter of doing a lower() function on all source code as a first >> step in the compile process. Then case in the source code need not >> matter, or you could choose to have it matter if that's what you want. >> It probably isn't that simple. I haven't looked into the source code >> far enough yet. Doing so would probably cause errors in existing >> programs where names do use same spelling/different case for different > >And all uses of standard Python modules such as random and fileinput, >which do exactly that sort of thing systematically. Also it would need to avoid lowering strings and literals too. >> Using a case correcting editor is one way of doing it that doesn't >> change pythons core and lets the programmer choose the behavior they >> want. > >Nope, can't do. Consider: > >>>> import random >>>> x=random.Random() >>>> y=random.random() > >now x and y are two VERY different things: > >>>> x > Is this very common, I tried to find other examples of this. Is there another way to get a base class of an object? Is this different for different modules, or is it a standard? >>>> y >0.93572104869999828 > >...but how would a poor "case correcting editor" distinguish them...? > Something like this where 'word' is a possible name: if word matches any name in both spelling and case: pass # leave it alone elif word matches a single name, but case is incorrect: correct case elif word matches several names spelled the same, but neither in correct case: give a hint get choice from hint >Such a smart editor might HELP a little by SUGGESTING a case-correction >when it appears unambiguous, even just for standard modules and the >functions therein. Maybe a menu-command for "suggest case corrections >if any" WOULD be helpful in IDLE, and offer good cost/benefit ratio as >a fun, not-too-terribly-hard project reducing human misery a bit...:-). > > >Alex I think so, especially for people first starting out or switching from another language. I think there could different levels of correction/suggestion modes. None == turn it off Polite == suggest choices if the case doesn't match, but don't actually correct anything. Assertive == Correct when it's obvious to do so, and suggest when there is more than one choice. What one would choose would be dependant on how well they know python and how accurate they type. _Ron Adam From testa at allos.sytes.net Wed Nov 12 10:14:20 2003 From: testa at allos.sytes.net (F.G.Testa) Date: Wed, 12 Nov 2003 13:14:20 -0200 Subject: asyncore.loop() blocks References: Message-ID: Thank you! "Richie Hindle" wrote in message news:l2i4rv084p81e9tghibbmo8f6qaoamuk51 at 4ax.com... > > [F.G.] > > Is there a way to perform other operations while still looping with > > asyncore.loop() without spawning a new thread? > > while something(): > asyncore.poll(timeout=0.1) # Or other suitable timeout in seconds > doOtherWork() > > -- > Richie Hindle > richie at entrian.com > > > -- > http://mail.python.org/mailman/listinfo/python-list > From aleaxit at yahoo.com Sat Nov 8 19:36:06 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 09 Nov 2003 00:36:06 GMT Subject: recursion vs iteration (was Re: reduce()--what is it good for?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> Message-ID: Anton Vredegoor wrote: ... > find a better example of recursive functions that memoize and which > cannot be made iterative. > > This would generate an important precedent for me because I have > believed for a long time that every recursive function can be made > iterative, and gain efficiency as a side effect. Well, without stopping to ponder the issue deeply, I'd start with: def Ack(M, N, _memo={}): try: return _memo[M,N] except KeyError: pass if not M: result = N + 1 elif not N: result = Ack(M-1, 1) else: result = Ack(M-1, Ack(M, N-1)) _memo[M,N] = result return result M>=0 and N>=0 (and M and N both integers) are preconditions of the Ack(M, N) call. There is a substantial body of work on this function in computer science literature, including work on a technique called "incrementalization" which, I believe, includes partial but not total iterativization (but I am not familiar with the details). I would be curious to examine a totally iterativized and memoized version, and comparing its complexity, and performance on a few typical (M,N) pairs, to both this almost-purest recursive version, and an incrementalized one. Alex From mwilson at the-wire.com Wed Nov 19 11:50:10 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 19 Nov 2003 11:50:10 -0500 Subject: Which of the best choice ? References: Message-ID: In article , "Terry Reedy" wrote: >In some situations, I like a third choice: import math as m, for >instance. (But I would not bother to abbreviate 'sys'.) Typing 'm.' >as in 'm.sin' is quick and a small price for keeping math names >segregated. That's also good for choosing among modules which truly are alternatives, as in if md5_required: import md5 as digest else: import sha as digest ... digester = digest.new() ... and so on. Regards. Mel. From hat at se-126.se.wtb.tue.nl Mon Nov 24 03:12:07 2003 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Mon, 24 Nov 2003 08:12:07 +0000 (UTC) Subject: How best to achieve asynchronous socket input and output? References: <153fa67.0311231821.3c5536cc@posting.google.com> Message-ID: On 23 Nov 2003 18:21:12 -0800, Kylotan wrote: > I'm writing a wxPython telnet-like application that needs to be able > to send and receive data independently of each other. The asyncore > library comes close to what I want, but still requires I have a > blocked thread (the one that calls asyncore.loop() ). It also seems a > little unpredictable; one example of this is that when I based an > example around the sample HTTP client (11.23.1 in the docs), > handle_write never seemed to get called, and I had to call .send() > directly, bypassing any buffering. > > Is there a better way of achieving what I want? Or something I need to > know about the asyncore library to get it to do this? I usually jump immediately to select, which maps almost directly to select(2), giving a lot of control, and lack of portability for non-unix systems. In the context of GUI's, maybe you can get the eventloop of wxpython to wait for file I/O on the sockets, some GUI libraries provide such a hook (GUI handling in the end means waiting for data from the X11 server, ie a select-like thing). Otherwise you must poll, or use a seperate thread. -- Albert -- Unlike popular belief, the .doc format is not an open publically available format. From rainerd at eldwood.com Sat Nov 22 17:33:46 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Sat, 22 Nov 2003 22:33:46 GMT Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> <7xwu9svyny.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > bokr at oz.net (Bengt Richter) writes: >> The question ISTM is whether importing a GPL'd module is enough to >> trigger GPL obligations on the part of the importing module. > > That is a correct statement of the question. According to the FSF, > the answer to the question is yes, that's enough to trigger the > obligations. Either you are misinterpreting the FSF, or the FSF is wrong. The FSF has no legal right to restrict the distribution of any software unless that software contains code which is copyrighted by the FSF. Whether the code may be linked to GPL code at runtime or not is irrelevant. The FSF does have the legal right to restrict the use of its own code, but it chooses not to exercise that right: the only restrictions in the GPL are on the redistribution (not use) of GPL'd code. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From paul_rudin at scientia.com Mon Nov 3 06:55:46 2003 From: paul_rudin at scientia.com (Paul Rudin) Date: 03 Nov 2003 11:55:46 +0000 Subject: Microsoft Access read from linux python References: <3FA63F06.9739C80F@hotmail.com> Message-ID: >>>>> "Alan" == Alan Kennedy writes: > [David ROBERT] >>> I've read a lot of things about mxODBC, iODBC and so on, but >>> I'm still very confused, It looks like it is _not_ possible. > [Ben Finney] >> One thing to be wary of is that there is no ODBC module in >> Python, so you will need to read the copyright license of any >> third-party module you choose to use. >> >> The mxODBC module (as made by eGenix) is certainly not licensed >> as free software: >> >> > I meant to reply to this last week, but forgot. > There is a completely free (in all senses of the word) and > open-source ODBC module for python: It is Brian Zimmer's/Ziclix > zxJDBC. > Of course, you're not going to like that either Ben, because > it's in Java and runs under jython. > But it is a free python ODBC library. There's also an odbc module with the win32all thing, which is free. From s-rube at uselessbastard.net Sun Nov 9 21:20:20 2003 From: s-rube at uselessbastard.net (Eric Williams) Date: Mon, 10 Nov 2003 03:20:20 +0100 Subject: PyQt and DCOP Documentation References: Message-ID: Eric Williams wrote: > I'm actually just trying to get the volume level out of noatun in a python > script, if anyone can help me with an example. What, exactly, does one DO > with a QByteArray in python? > Ok, figured out a workaround for that call; in case anyone else's having a similar problem: ---------------------------------------------- def getvol(self): res = self.rc.call("volume()") if res.isValid(): return ord(res.data.data()[-1]) else: return None ----------------------------------------------- Where rc is a DCOPRef object hooked to noatun. For whatever reason, res.data.data() returns a 4-byte array, so here you take the last byte. Am I doing that correctly, or is there a better way? On to the next problem: ----------------------------------------------- def volup(self): curvol = int(self.getvol()) newvol = curvol + 5 res = self.rc.call("setVolume(%d)" % newvol) print "Setvol: ", res.isValid() ----------------------------------------------- I've tried various mutations of this. This doesn't work at all. Anybody know how to do this? Thanks, Eric -- --- s- should be removed to contact me... From fredrik at pythonware.com Tue Nov 18 08:55:06 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Nov 2003 14:55:06 +0100 Subject: PIL and jpg -> png conversion References: <971323274247EB44B9A01D0A3B424C8503590FEE@FTWMLVEM02.e2k.ad.ge.com> Message-ID: Vincent Raaijmakers wrote: > s = StringIO() > image.save(s,'PNG') > return s.getvalue() > Unfortunately, this seems only to work for GIF and JPEG, but not for PNG. > As a test I try to reconvert the file output to an image again but the > image.verify() throws an fp.seek.tile error. This only happens with PNG files. is this what you get? Traceback (most recent call last): File "PngImagePlugin.py", line 280, in verify self.fp.seek(self.tile[0][2] - 8) AttributeError: 'None' object has no attribute 'seek' if that's the case, the problem is in "verify", not in the file. the "verify" method is only guaranteed to work if you call it on a "freshly" opened image; if you load the image (or do anything that causes the image to be loaded), the result is undefined. (I agree that the error message could be slightly improved ;-) From fbarbuto2002.no at spam.yahoo.ca Sun Nov 9 22:28:59 2003 From: fbarbuto2002.no at spam.yahoo.ca (Fausto Arinos de A. Barbuto) Date: Sun, 9 Nov 2003 20:28:59 -0700 Subject: Help with Apache 2.0.47 and CGI References: Message-ID: Thank you very much Emile -- it is not working yet, although I have already downloaded and installed mod_python. Apache says it can't find the module mod_python.so even though the bloody little thing is right there where it should be, in C:\Apache Group\Apache2\modules. It seems that Python 2.3.2 is the bad guy here. A friend of mine has Apache 2.0.47 + Python 2.2 and everything works like a charm on his system. I guess I'm on the right track now. Many thanks. ---Fausto "Emile van Sebille" wrote in message news:bomu2s$1gc2te$1 at ID-11957.news.uni-berlin.de... > Fausto Arinos de A. Barbuto asks > > I have Apache 2.0.47 installed for a single user on port 8080, > Python > > 2.3.2 on C:\Python23 and ActiveState's Perl on C:\Perl. Everything > seems > > to work fine after the changes I made in httpd.conf, but I can't for > some > > reason run Python scripts that sit on this computer's cgi-bin > directory > > > http://www.modpython.org/ > > http://www.modpython.org/live/mod_python-3.1.2b/doc-html/inst-apacheconfig.html > > LoadModule python_module libexec/mod_python.so > SetHandler python-program > PythonHandler mod_python.cgihandler > > But there was also a problem reported with 2.3: > > http://groups.google.com/groups?threadm=3ef52138%241 at usenet.per.paradox.net.au > > HTH, > > -- > > Emile van Sebille > emile at fenx.com > > --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.537 / Virus Database: 332 - Release Date: 06/11/2003 From grzegorz at ee.ualberta.ca Thu Nov 27 07:38:34 2003 From: grzegorz at ee.ualberta.ca (Grzegorz Dostatni) Date: Thu, 27 Nov 2003 07:38:34 -0500 Subject: Tkinter "Expected boolean value" Message-ID: Good morning. I've got a Tkinter problem: File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 2310, in selection_present return self.tk.getboolean( TclError: expected boolean value but got "" Now a few weeks ago there was a similar problem with the boolean value. That's when the tcl started returning "???" for unknown fields in a callback. This looks to be related. I am running the newest cygwin version of python (Python 2.3 (#1, Aug 5 2003, 09:49:11)) with libtk and libtcl 8.4. Is it possible to fix this without re-compiling? I've got a lot of c-modules/wrappers etc. I'll have to do an installation of my program soon and so far I've been able to use only the stock versions of cygwin. Greg "Many a man may look respectable, and yet be able to hide at will behind a spiral staircase." - Pelham (Plum) Grenville Wodehouse From frank at chagford.com Fri Nov 7 07:43:26 2003 From: frank at chagford.com (Frank Millman) Date: 7 Nov 2003 04:43:26 -0800 Subject: Question re threading and serial i/o References: <246a4e07.0311040705.5f8d9a9@posting.google.com> <3FA7CB03.6B650215@engcorp.com> <246a4e07.0311060251.3a24d5b@posting.google.com> <3FAA5A50.C05D7C0D@engcorp.com> Message-ID: <246a4e07.0311070443.11e85c2d@posting.google.com> > Frank Millman wrote: > > > > This is my Mk 3 version, using select() - > > def scan(): > > p = file('/dev/ttyS0') > > while x: > > ans = select.select([p],[],[],0.1) > > if ans[0]: > > print ord(p.read(1)) > > p.close() > > > > The scanner sends a string consisting of 'code' 'qty' . If I > > scan a code of '1' and a quantity of '1', I would expect the program > > to display 49 9 49 13. The Mk 2 version does this correctly. > > > > The Mk 3 version behaves differently. After the first scan, it > > displays 49. After each subsequent scan, it displays 9 49 13 49. > > > > If anyone can explain what I am doing wrong, I will be most grateful. > > In the meantime I am sticking with Mk 2, as it is doing the job. > Peter Hansen wrote: > Not entirely sure... but what is "x" in the while statement? > "x" is a global variable with a value of 1. It stays 1 until the main thread wants to terminate the program, in which case it sets it to 0 and the secondary thread stops. This works ok. > Another possibility is that you have not opened the file in non-blocking > mode. I don't know what the effect of that would be on the select() > statement, but if you did use non-blocking, you could change the read() > call to get a whole bunch of data at a time, instead of only one byte. > If you did p.read(1024), for example, on a non-blocking file, you should > get back anywhere from 1 to 1024 bytes after select indicates it is > readable. If nothing else, this will speed up your final result, in > either case. (You can't do that on a block read, of course, since > it would then block until all 1024 bytes were available, which might > never happen.) > > -Peter This was indeed the problem. I changed p = file('/dev/ttyS0') p.read(1) to p = os.open('/dev/ttyS0',os.O_RDONLY|os.O_NONBLOCK) os.read(p,1) and it behaved correctly. Out of interest, is there another way to open a serial port in non-blocking mode? Reading chunks of up to 1024 works as you predicted, and should be faster - I will follow this up. Thanks a lot, Peter, I really appreciate your valuable input. Frank From thorsten at pferdekaemper.com Fri Nov 21 10:07:31 2003 From: thorsten at pferdekaemper.com (Thorsten Pferdekämper) Date: Fri, 21 Nov 2003 16:07:31 +0100 Subject: Question about Objects - repost with correct email account References: Message-ID: "bas68" wrote in message news:MGpvb.394$xV6.316 at lakeread04... > I've been hacking visual basic for several years and understand the basic > concepts of OOP. That said, I'm stumped here with the Python Class. > > Here is the Class... > > >class Test: > > def __init__(self, something): > > self.something = something > > > > def getSomething(self): > > return self.something > > This is what I get when I test it. Why does not return the > value of ? is obvious that has a value. I fear this > is a simple oversight but I've racked my brain for hours looking at online > doc's and examples. Thanks for any help!! > > >Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on > win32 > >Type "copyright", "credits" or "license()" for more information. > >**************************************************************** > >IDLE 1.0 ==== No Subprocess ==== > >>>> > >>>> x = Test("Microsoft Sucks") > >>>> x.getSomething > >> > >>>> x.something > >'Microsoft Sucks' > >>>> > > Hi, getSomething is a callable attribute of class Test (i.e. a method), so the expression: x.getSomething evaluates to the method itself, while x.getSomething() calls the method and therefore evaluates to the result of the method. Regards, Thorsten From aaron at reportlab.com Wed Nov 19 13:26:01 2003 From: aaron at reportlab.com (Aaron Watters) Date: 19 Nov 2003 10:26:01 -0800 Subject: deprecation gotchas Re: rotor alternative? References: Message-ID: <9a6d7d9d.0311191026.44da2b19@posting.google.com> hwlgw at hotmail.com (Will Stuyvesant) wrote in message news:... > Deprecation is a very serious matter. I love the Python language but > I have questions about the deprecation decisions. Yea, random changes can do a lot of damage. Examples repr(string) went hex and broke a lot of stuff for interacting with systems that matched the old octal representation (pdf format for example). It's very hard to ferret out all the places where someone assumed that chr(0)=="\000". cgi.environ disappeared and broke every cgi script in the CD ROM in my python book right after it hit the shelves. :(! regex was used pervasively. Why not just provide a translator stub rather than deprecate it (noting in the documentation that it's slower)? More examples on request... arrgh. Please don't break code for cosmetic reasons! -- Aaron Watters === I can't do that, Dave. From nessus at mit.edu Sat Nov 8 17:36:37 2003 From: nessus at mit.edu (Douglas Alan) Date: Sat, 08 Nov 2003 17:36:37 -0500 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: Message-ID: aahz at pythoncraft.com (Aahz) writes: >>> Sounds good. However, I won't try it until there's a shell-based mode; >>> I do too much of my work remotely. >>That's what TightVNC is for. > Ugh. While I love what my new DSL can do, I don't think that running GUI > applications remotely is one of the things it *should* do, especially not > when text works so much better. I do so for hours every day with no problem. That's not to say that an ascii-only version of Leo might not be a good thing, but rather that in this day and age, not having one should hardly be a show-stopper. |>oug From eduardo at consultoria.eti.br Wed Nov 12 11:25:38 2003 From: eduardo at consultoria.eti.br (Eduardo Patto Kanegae) Date: Wed, 12 Nov 2003 14:25:38 -0200 Subject: a python book hint Message-ID: <20031112162538.4199.qmail@hm47.locaweb.com.br> Hello, I have been programming with Visual Basic and PHP in the last 5 years and some folks had recommended Python a free language.... I had looked for a Python book to start up but found many titles... so, my question finally is: what book could be for a Python beginner - but NOT a programming beginner - which intends to develop *windowed* Python programms and intends to develop for Windows and for Linux? for example, look at Thuban software ( http://thuban.intevation.org/ ) which runs on Linux and Win plataforms. thanks in advance. Eduardo Patto Kanegae http://www.consultoria.eti.br - BRASIL F?rum ptMapServer - http://www.consultoria.eti.br/mapserverptforum/ ClickBrasil - http://www.consultoria.eti.br/clickbrasil/ *************************************** ***Fim da Mensagem / End of Message *** *************************************** From alanmk at hotmail.com Mon Nov 3 06:41:58 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 03 Nov 2003 11:41:58 +0000 Subject: Microsoft Access read from linux python References: Message-ID: <3FA63F06.9739C80F@hotmail.com> [David ROBERT] >> I've read a lot of things about mxODBC, iODBC and so on, >> but I'm still very confused, It looks like it is _not_ >> possible. [Ben Finney] > One thing to be wary of is that there is no ODBC module in Python, so > you will need to read the copyright license of any third-party module > you choose to use. > > The mxODBC module (as made by eGenix) is certainly not licensed as free > software: > > I meant to reply to this last week, but forgot. There is a completely free (in all senses of the word) and open-source ODBC module for python: It is Brian Zimmer's/Ziclix zxJDBC. Of course, you're not going to like that either Ben, because it's in Java and runs under jython. But it is a free python ODBC library. kind regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From xtian at toysinabag.com Thu Nov 20 04:27:45 2003 From: xtian at toysinabag.com (xtian) Date: 20 Nov 2003 01:27:45 -0800 Subject: minidom questions Message-ID: Hi - I'm doing some data conversion with minidom (turning a csv file into a specific xml format), and I've hit a couple of small problems. 1: The output format has a header with some xml that looks something like this: As I understand it, this is a valid use of namespaces. If I add this to the start of the document, when I do a .toxml(), I get an exception. Here's a small example: >>> s = """""" >>> doc = minidom.parseString(s) >>> print doc.toxml() Traceback (most recent call last): File "", line 1, in -toplevel- print doc.toxml() File "C:\PYTHON23\lib\xml\dom\minidom.py", line 47, in toxml return self.toprettyxml("", "", encoding) File "C:\PYTHON23\lib\xml\dom\minidom.py", line 59, in toprettyxml self.writexml(writer, "", indent, newl, encoding) File "C:\PYTHON23\lib\xml\dom\minidom.py", line 1746, in writexml node.writexml(writer, indent, addindent, newl) File "C:\PYTHON23\lib\xml\dom\minidom.py", line 811, in writexml _write_data(writer, attrs[a_name].value) File "C:\PYTHON23\lib\xml\dom\minidom.py", line 301, in _write_data data = data.replace("&", "&").replace("<", "<") AttributeError: 'NoneType' object has no attribute 'replace' Doing some debugging, the xmlns attribute (is it really an attribute?) has a value of None, rather than "". I can work around this by replacing the implementation of Element.writexml with one including: value = attrs[a_name].value if value is None: value = "" Is this a bug? Am I doing something wrong? 2: Formatting - I'd like the output xml not to put extra line breaks inside elements that contain only text nodes (which is what .toprettyxml does by default) - the tool that uses the xml treats the line breaks as significant. The .toxml method works, but I'd like to have the output be prettier than this (while not being as pretty as the output of .toprettyxml :). I can see how to get what I want by replacing Element.writexml with one that checks to see whether all the childNodes are text. Is there a better way to do this? Thanks, xtian From pmaupin at speakeasy.net Sun Nov 23 02:46:07 2003 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 22 Nov 2003 23:46:07 -0800 Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> <7xwu9svyny.fsf@ruckus.brouhaha.com> <7xvfpcowjt.fsf@ruckus.brouhaha.com> Message-ID: <653b7547.0311222346.b4d9e98@posting.google.com> Paul Rubin wrote: > "Rainer Deyke" writes: > > Either you are misinterpreting the FSF, or the FSF is wrong. The > > FSF has no legal right to restrict the distribution of any software > > unless that software contains code which is copyrighted by the FSF. > > Whether the code may be linked to GPL code at runtime or not is > > irrelevant. The FSF does have the legal right to restrict the use > > of its own code, but it chooses not to exercise that right: the only > > restrictions in the GPL are on the redistribution (not use) of GPL'd code. > > The FSF does not agree with you, but as they say, it's something only a > court can decide. Well, the FSF certainly _acts_ like they disagree with Rainer. Stallman himself has written that a program which dynamically links with readline violates the GPL even if distributed without readline. (But as others have noted elsewhere, since purely functional API behavior cannot be copyrighted, this seems to put the FSF in the interesting position of saying that if the only implementation of a particular API is provided by GPLed software, then software which uses it must also be GPLed, but that this is not a necessity if at least one other library implements the same API.) Eben Moglen tries very hard to toe this particular party line as well, but being a lawyer he tries to do so in a manner which doesn't tell any explicit lies. For example, in a Slashdot interview he writes: "The language or programming paradigm in use doesn't determine the rules of compliance, nor does whether the GPL'd code has been modified. The situation is no different than the one where your code depends on static or dynamic linking of a GPL'd library, say GNU readline. Your code, in order to operate, must be combined with the GPL'd code, forming a new combined work, which under GPL section 2(b) must be distributed under the terms of the GPL and only the GPL. If the author of the other code had chosen to release his JAR under the Lesser GPL, your contribution to the combined work could be released under any license of your choosing, but by releasing under GPL he or she chose to invoke the principle of "share and share alike." A casual reading of this certainly supports the idea that it is impermissible to write code which uses readline without releasing that code under a GPL-compatible license, but a closer reading may lead to a different conclusion. Moglen admits that the combination of "your code" with GPLed code is "a new combined work" (implicitly acknowledging that "your code" is a separate work with no GPLed code in it and thus is not covered by the GPL until it becomes part of the "new combined work"). He (deliberately IMO) fails to address what happens when the author of "your code" _declines_ to distribute this "new combined work", and the rest of the paragraph assumes and reinforces the idea that OF COURSE the "new combined work" will be distributed intact. Obfuscatory tactics such as writing "in order to operate, must" instead of "will not be as functional unless" are there to keep the reader from noticing that "your code" has transmogrified into "your contribution to the combined work", and then, to drive his point home without resorting to any concrete statements which could be proven false, Moglen concludes with the legally meaningless but morally high-sounding principle of "share and share alike". The FSF's goals of wanting to coerce _authors_ into releasing new code under the GPL, and simultaneously wanting _users_ to enjoy "maximum freedom" have led them into a conundrum in this instance. Since an author is also a user, as long as he is not actually distributing the GPLed software, e.g. readline, he is free to _study_ the software on his system, and he is even free to combine it with his own software (modify it) for his own use as long as he follows sections 2a and 2c of the license (which are not at all restrictive). So it would appear that the FSF has no real legal ability under the GPL to keep someone from writing and distributing a package which uses readline, as long as that person does not simultaneously distribute readline itself. IMO, disallowing a developer from distributing readline along with his non-GPLed program which uses readline is perfectly reasonable and provides gentle guidance to developers that it is much easier to GPL their programs than to force their users to go out and download all the parts themselves, but the specious posturing of trying to claim that any program which could be used in conjunction with readline must be released under the GPL (see Aladdin Ghostscript) is not really all that astute. > They have stated their willingness to go to court over > the question. No one so far has taken them up on it. So far it hasn't been worth it for anybody. There are several reasons for this, such as the "OS exception" in the GPL, and the willingness of the FSF in some specific cases to negotiate special licenses. Basically, for it to be worth it to a company, they would have to be in all of: set "a" -- companies completely dependent on the GPLed software in question (otherwise why waste time and money litigating the issue?) set "b" -- companies big enough to contemplate taking on the direct financial burden of a court battle with the FSF set "c" -- companies which won't be damaged by the bad publicity (or which don't care about the damage) I respectfully submit that the statement "No one so far has taken them up on it" can be easily explained by the fact that the number of companies in the intersection of sets "a", "b", and "c" is vanishingly small... Pat From hungjunglu at yahoo.com Mon Nov 3 04:51:03 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 3 Nov 2003 01:51:03 -0800 Subject: adding attributes to a function, from within the function References: Message-ID: <8ef9bea6.0311030151.159c980@posting.google.com> Shu-Hsien Sheu wrote in message news:... > I think you would need to use a class rather than function. > > >>> class fn(object): > def __init__(self): > self.error = 'Error message' > > > >>> kk = fn() > >>> kk.error > 'Error message' Yes, in Python it's more natural to use a class object for storing attributes. What the original poster wanted was some sort of "closure-like" function, that is, a function object that can carry some data member as well. Also, in C++, you have static variables inside functions. In Python, if you use a function object, you can't insert attributes during the definition of the function. In Python, an class instance can be made callable by implementing the __call__() method. If the function is supposed to be singleton, then you can use: class fn(object): error = 'Error message' def __call__(self, x=None): if x is None: return 1 else: return 2*x fn = fn() # gets rid of the class, this makes fn singleton print fn() # prints 1 print fn(3) # prints 3 print fn.error # prints 'Error message' regards, Hung Jung From frithiof.jensen at removethis.ted.ericsson.dk Wed Nov 5 04:30:17 2003 From: frithiof.jensen at removethis.ted.ericsson.dk (Frithiof Andreas Jensen) Date: Wed, 5 Nov 2003 10:30:17 +0100 Subject: Why no try-except-finally ? References: <20031105040556.29079.00000209@mb-m22.aol.com> Message-ID: "KefX" wrote in message news:20031105040556.29079.00000209 at mb-m22.aol.com... > this idiom unPythonic somehow? (The nested-try thing does look odd...) Or is it > the way we're supposed to do it? Or is there something I'm missing? According to the documentation the purpose of a try...finally statement is to ensure that aquired ressources will be freed again as in self.lock.acquire() try: ..do whatever we are supposed to do; ...it may fail here or in a different module etc. ...exceptions may be caught or not finally: ...but we always end *here* ...and uncaught exceptions are re-raised from here too (i think) ...so that "the right thing" happens self.lock.release() so that the ressource is released regardless of any exceptions etc. that happens between the try: and the finally: The separation is probably because the purpose of try..finally is different from exception handling and mixing the two would obscure that (or maybe there is some wizardry under the hood). From http Sat Nov 22 17:41:58 2003 From: http (Paul Rubin) Date: 22 Nov 2003 14:41:58 -0800 Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> <7xwu9svyny.fsf@ruckus.brouhaha.com> Message-ID: <7xvfpcowjt.fsf@ruckus.brouhaha.com> "Rainer Deyke" writes: > Either you are misinterpreting the FSF, or the FSF is wrong. The > FSF has no legal right to restrict the distribution of any software > unless that software contains code which is copyrighted by the FSF. > Whether the code may be linked to GPL code at runtime or not is > irrelevant. The FSF does have the legal right to restrict the use > of its own code, but it chooses not to exercise that right: the only > restrictions in the GPL are on the redistribution (not use) of GPL'd code. The FSF does not agree with you, but as they say, it's something only a court can decide. They have stated their willingness to go to court over the question. No one so far has taken them up on it. From tjreedy at udel.edu Fri Nov 14 17:31:00 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Nov 2003 17:31:00 -0500 Subject: Python's simplicity philosophy References: <2259b0e2.0311112248.3be2d304@posting.google.com><17lsb.109042$fl1.4548960@twister.southeast.rr.com> <20031112170100.GA32388@godzilla.fibrespeed.net> <8Y7tb.21901$9_.802189@news1.tin.it> Message-ID: "Alex Martelli" wrote in message news:8Y7tb.21901$9_.802189 at news1.tin.it... > Dave Brueck wrote: > ... > >> results = [ func(x) for x in sequence ] > >> ... instead of ... > >> results = sequence.map(func) ?? > > Because I find the first much more readable> > I entirely agree with both points. For this pair, I like the second better. Different aesthetics. > They're even clearer when the contrast is between, e.g.: > results = [ x+23 for x in sequence ] > and: > results = sequence.map(lambda x: x+23) > where using the HOF approach forces you >to understand (and read) lambda too. Here I might take the first. 'lambda' is something I feed 'stuck' with. Would the hypothetical results = sequence.map(func x: x+23) be any better? How about a very hypothetical (post ``==repr deprecation) results = sequence..map(`x+23`) ? Terry J. Reedy From tchur at optushome.com.au Sat Nov 8 16:28:50 2003 From: tchur at optushome.com.au (Tim Churches) Date: 09 Nov 2003 08:28:50 +1100 Subject: ANN: Leo 4.1 beta 1 An outlining editor In-Reply-To: References: Message-ID: <1068326929.1338.40.camel@emilio> On Sat, 2003-11-08 at 02:45, Edward K. Ream wrote: > Leo 4.1 beta 1 is now available at: http://sourceforge.net/projects/leo/ > > This is the first official release of the reorganized 4.1 code base. The > code appears solid, and has not been widely tested. Please use caution when > using this code. A small request: please don't use spaces in directory or files names in your Leo distribution - use dashes or underscores if you need a separator. Spaces annoy the hell out of anyone using a command line interface. Otherwise Leo looks great. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From nospam at nowhere.hu Sat Nov 22 17:29:49 2003 From: nospam at nowhere.hu (Jegenye 2001 Bt) Date: Sat, 22 Nov 2003 23:29:49 +0100 Subject: 2.2.2 Annoyance Message-ID: Caveat: Python 2.2.2 (#37, Oct 14 2002, 17:02:34) Type "help", "copyright", "credits" or "l >>> l = [1,2,3] >>> l[1] 2 >>> l.__getitem__(1) 2 >>> l.__getitem__(slice(1)) Traceback (most recent call last): File "", line 1, in ? TypeError: an integer is required >>> According to the manuals of Python 2.2.2, passing a slice object to __getitem__ is all right and should work... Cost a few (grey) hairs of mine, while debugging a largish program, this is not so. Would someone care to pass on this info to whom this may concern? For Python 2.3 passing a slice object to __getitem__ does work though. Best, Mikl?s From http Tue Nov 11 11:47:01 2003 From: http (Paul Rubin) Date: 11 Nov 2003 08:47:01 -0800 Subject: pickle complexity limit? References: <7x4qxckwdu.fsf@ruckus.brouhaha.com> Message-ID: <7xbrridf96.fsf@ruckus.brouhaha.com> martin at v.loewis.de (Martin v. L?wis) writes: > > I wonder if it's feasible to write a pickler as a C extension that > > works something like a pointer-reversing garbage collector, > > eliminating the need for recursion and still not needing any extra > > storage in the objects. > > You definitely will need storage, to remember the objects you have to > come back to; you won't necessarily need storage *in the objects*. No. I'm talking about a crazy hack that was used in some old-time Lisp systems. The idea is to temporarily reverse the pointers that already exist in the objects to track what's been GC'd, so you don't need more than a constant amount of additional storage. Google for "Deutsch Schorr Waite garbage collection" or look in Knuth vol 1 for more info. From anabell at sh163a.sta.net.cn Sun Nov 2 01:37:03 2003 From: anabell at sh163a.sta.net.cn (anabell) Date: Sun, 2 Nov 2003 14:37:03 +0800 Subject: i18n pot file In-Reply-To: <3F951328.1000501@draigBrady.com> Message-ID: <004101c3a10b$bfce8200$2b00a8c0@sta.net.cn> I was unable to use charset utf-8 because I get this error message when I try to run my localized application: UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: invalid data Finding an alternative, I tried writing a gb2312 codec, which is not availabe initially with Python's package. I downloaded a gb2312 character map and put it in the gb2312.py codec file. It worked well (Simplified Chinese characters are displayed). I wonder though how I can make utf-8 work if it does support any language. I looked into my python23/lib/encodings/ and found there exist utf-8. I edited my .po file to charset utf_8, and generated its .mo file. But when I ran my localized application, python's gettext module can recognize the charset 'utf8', but problem occurs when it starts decoding the .mo file. I opened the utf_8.py codec file, and found no character map. I wonder if it's using a wrong map? > It depends. The best CHARSET to use is UTF-8 > but of course you have to enter UTF-8 data into > the po file. You can write all languages in UTF-8. > There are charsets specific to language (groups) > which you may prefer. For e.g. > Big5 for traditional chinese > gb2312 for simplified chinese > ISO-8859-15 for western European languages > > The ENCODING should be 8bit in all cases > > The handiest thing to do is to look at examples: > http://www2.iro.umontreal.ca/~gnutra/registry.cgi?team=zh_CN > > Maybe you could even practice on my application :-) > http://www2.iro.umontreal.ca/~gnutra/registry.cgi?domain=fslint > > P?draig. > > anabell wrote: > > Hi, I'm trying to localize to Chinese language. In the pot > file header, > > there appears: > > > > "POT-Creation-Date: Thu Oct 16 17:07:14 2003\n" > > "PO-Revision-Date: 2003-10-16 HO:MI+ZONE\n" > > "Last-Translator: Anabell chan > >\n" > > "Language-Team: LANGUAGE >\n" > > "MIME-Version: 1.0\n" > > "Content-Type: text/plain; charset=CHARSET\n" > > "Content-Transfer-Encoding: ENCODING\n" > > "Generated-By: pygettext.py 1.5\n" > > What should i fill in the 'CHARSET' and 'ENCODING' ? > > From pmaupin at speakeasy.net Sun Nov 23 11:04:55 2003 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 23 Nov 2003 08:04:55 -0800 Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> <7xwu9svyny.fsf@ruckus.brouhaha.com> Message-ID: <653b7547.0311230804.760628f5@posting.google.com> Daniel Berlin wrote > On Nov 22, 2003, at 5:33 PM, Rainer Deyke wrote: > ... > > Either you are misinterpreting the FSF, or the FSF is wrong. > > Sigh. > Can't we simply leave legal questions to lawyers and judges? Sure. That's what democracy is all about :) Or the less flippant answer is: there are several areas of the law in which laymen can have a legitimate interest and something to say. This is true about any subject. > The FSF is entitled to their view, and one could argue it and expect > some chance of success. Yes, where "some chance" is an extremely small number. > One could argue the other way, and expect some chance of sucess. > This is because there simply is no settled law, precedent, etc, > on the subject. Repeating this mantra, as you and several others on this thread have done, simply does not make it true. Like most canards, this has a kernel of truth, namely that the FSF itself has not been in litigation over this issue. But if you think that this issue has never been litigated, you have not boiled it down to its most basic elements and then looked for case law. As I understand it, the abstract version of the case would boil down to this: - A company notices that program A is a useful tool for other programs to use, and produces program B, which contains no code from program A, but which invokes and uses program A at runtime. - When this company distributes program B, the makers of program A sue the company for copyright violation. (They do not sue the users who actually combine the two programs together, because a) those users probably have a license to do this, and b) that would be bad for business.) This issue has come up repeatedly and has been litigated extensively, by companies with big budgets and good lawyers. I do not personally know of any cases where the producer of program A has prevailed (absent literal copying of program A), but I _do_ know of more than one case where the maker of program B has prevailed (see Sega vs. Accolade for a start). Note that in these cases, the producer of program B has usually copied program A in the process of reverse-engineering it (which would not even need to happen to use a GPLed program), and this copying has been ruled to be fair use. > So saying they are wrong makes you wrong, because they are correct > in stating that it would have to be decided by a judge. Judges and lawyers are so expensive that, instead of hiring a full set of them to decide a particular issue, people and companies routinely look at similar situations which have come up before, and examine the outcome of those situations before a judge, and then decide to modify their behavior (or not) based on that outcome. If one did that on this issue, one could reasonably come to the conclusion that ON THIS ISSUE the FSF is wrong, and then another could unreasonably come to the conclusion that the one is wrong, because nothing is ever settled until it is brought before a judge (as if judges are never wrong and never overturned). > > The FSF has no legal right to restrict the distribution of > > any software unless that software contains code which is > > copyrighted by the FSF. > > This is, of course, incorrect, unfortunately. > For example, the FSF could own the exclusive right to license some > piece of code. Not saying that they do, but they could, and thus, even > without being the copyright owner, would have the right to enforce it's > license. > Any of the rights granted by copyright can be licensed without having > to transfer the copyright itself. > > I passed copyright law in law school, so i'm at least sure of this much. I didn't even take copyright law, and I'm sure that either a) you are deliberately being unreasonably pedantic, or b) you are exceedingly dense. If you were to read the OP in the full context of the thread, you would find that what he was really saying was that if party X generates a pile of new code all by himself, the fact that the FSF has some OTHER copyrighted code (and in the context, I'm sure the OP means either owns or somehow controls this other code) does not give the FSF any right to restrict what party X does with his own code, so party X is free to give his own code to whomever he cares to, under whatever terms he chooses (but under some circumstances, party X can certainly be enjoined from distributing the FSF's own code alongside party X's own code). This is true EVEN IF party X's code has the ability to make use of the FSF's code. In my opinion, the OP made this point clearly and succinctly, and I'm sure that everybody except you understood him perfectly. > In addition, DMCA grants them the right to prevent distribution of > certain other types of code (code that circumvents effective access > controls). Umm, yeah. I'm thinking real hard here to try to come up with a license that is _less_ compatible with DMCA-style "access controls" than the GPL. I'm drawing a blank here. Can anyone help me out? (Hint: The GPL is the "anti-DMCA". Only use it on code you want to insure is available to anybody, at any time, in any place.) > > > Whether the code may be linked to GPL code at runtime > > or not is irrelevant. > This may or may not be true. > Stating your opinion as fact is not helping. Yes, I find your deliberate misunderstanding of the OP _so_ much more helpful. Throwing in that DMCA red herring was a nice touch as well. Pat From mesteve_b at hotmail.com Sat Nov 29 20:32:05 2003 From: mesteve_b at hotmail.com (python newbie) Date: Sun, 30 Nov 2003 01:32:05 GMT Subject: referencing an object attribute sort of indirectly from within list Message-ID: Is there anything that would get in the way of me being able to reference an object attribute, from within a list. I have: # one class here class BackupSet: fileGroupList = [] # another class here class FileGroup: sourceDir = '' destinDir = '' def __init__(self): self.sourceDir = 'c:\folder' self.destinDir = 'd:\folder' fileGroup = FileGroup() backupSet = BackUpSet() backupSet.fileGroupList.append(fileGroup) # when i try to reference an attribute here, I just get 'none' print bkset.fileGroupList[0].sourceDir or print "%s" % bkset.fileGroupList[0].sourceDir thanks Steve -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at intarweb.us Sun Nov 2 10:43:17 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sun, 2 Nov 2003 10:43:17 -0500 Subject: unittest -- simple question In-Reply-To: References: Message-ID: <20031102154317.GA5421@intarweb.us> On Sat, Nov 01, 2003 at 11:30:20PM -0500, Brian wrote: > Hello; > > I am writing my test modules that are separate from the modules they > test. The test modules can be invoked with if __name__ == "__main__" when > run from a command line. Right now, if __name__ == "__main__", the test > module executes runTests(), which defines a suite of tests. From the > module being tested, I am calling into the test module -- to the function > runTests(), if __name__ == "__main__". > > Is this how people make the tests executable from the module be tested? > I typically decorate my modules with the following preable: # -*- test-case-name: package.test.test_modulename -*- and then hit F9 when I want the tests to run. Jp From tundra at tundraware.com Thu Nov 6 13:13:52 2003 From: tundra at tundraware.com (Tim Daneliuk) Date: 06 Nov 2003 18:13:52 GMT Subject: Unload extension modules when python22.dll unloads... [using C extension interpreter] In-Reply-To: <3f5dc178.0311060931.38491269@posting.google.com> References: <3f5dc178.0311060931.38491269@posting.google.com> Message-ID: Anand wrote: > I have a unexpected issue with python modules (well i kind of know > why, but i am trying to find if there is a way around) > > Intro: > I am allowing an external application to actually run python scripts. > The external application i am taking about is a test sequencer with a > lots of functionality. So the external application has a lot of gui > and all the testing logic is done in python. Things work fine when i > run regular code and i have been running python code successfully > (several thousand lines of code) for over eight months. > > Issue: > Well, now there is an requirement to throw a dialog box from > python. I built a wxpython code and was able to successfully show the > dialog box from python. But when i run the code for the second time, > it wouldnt work.. > > the wxpython's dll probably does some initialization during > dll_process_attach... but i never see the pyd get unloaded ( i > actually unload python22.dll after each run). this is a big problem > now. i did not really consider about this earlier. so i cannot > actually Guarantee proper fuctioning of the python code... > > is there a way for me to *unload dynamically loaded extension module* > each time and then reload it each time when the code is called... > > thanks a lot in advance. Another thought: If you are running on Win32, (iirc) there is a way to present a dialog box directly from a python script using win32all. This method, while not portable, has the advantage of not having to go through all the usual GUI gobbledy-gook to set up and process the dialog ... import win32gui retval = win32gui.DialogBox(....) HTH, ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From joobs at grizo.free-onlineNOJUNK.co.uk Mon Nov 10 22:12:08 2003 From: joobs at grizo.free-onlineNOJUNK.co.uk (John Burns) Date: 11 Nov 2003 04:12:08 +0100 Subject: Matrix - Metaphors, Analogies and the REAL References: Message-ID: <9445252322481252.NC-1.60.joobs@news.free-online.net> On Mon, 10 Nov 2003 18:05:17 GMT, 3seas wrote: > If you are not interested, then don't bitch, its a short message. But it's still Off Topic Tim. From andy47 at halfcooked.com Fri Nov 28 15:21:49 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Fri, 28 Nov 2003 20:21:49 +0000 Subject: Is Python compatible with AIX Unix ? In-Reply-To: References: Message-ID: Limey Drink wrote: > And are there any problems that I should watch out for when installing ? > > Thanks > > You don't even need to download and compile the source. Just get the binary package from http://www-1.ibm.com/servers/aix/products/aixos/linux/download.html Works like a dream for me. Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From richie at entrian.com Thu Nov 20 11:25:16 2003 From: richie at entrian.com (Richie Hindle) Date: Thu, 20 Nov 2003 16:25:16 +0000 Subject: Catching keystrokes under Windows In-Reply-To: References: <7c39ada9.0311190951.20e9221b@posting.google.com> Message-ID: [Olli] > I'm having a little problem catching keystrokes under Windows. > [...] when the program is being run on the background. [Mike] > To do this for all Windows applications, you need to use a systemwide > message hook, which is set with the Windows function SetWindowsHookEx > using the WH_KEYBOARD option. There's an easier way using Windows Hotkeys, as long as you don't expect the keystroke to be delivered to the focussed application (eg. if the feature is something like "Press Ctrl+Shift+S to shut down the reactor"). --------------------------------------------------------------------- import sys from ctypes import * from ctypes.wintypes import * # Define the Windows DLLs, constants and types that we need. user32 = windll.user32 WM_HOTKEY = 0x0312 MOD_ALT = 0x0001 MOD_CONTROL = 0x0002 MOD_SHIFT = 0x0004 class MSG(Structure): _fields_ = [('hwnd', c_int), ('message', c_uint), ('wParam', c_int), ('lParam', c_int), ('time', c_int), ('pt', POINT)] # Register a hotkey for Ctrl+Shift+S. hotkeyId = 1 if not user32.RegisterHotKey(None, hotkeyId, MOD_CONTROL | MOD_SHIFT, ord('S')): sys.exit("Failed to register hotkey; maybe someone else registered it?") # Spin a message loop waiting for WM_HOTKEY. msg = MSG() while user32.GetMessageA(byref(msg), None, 0, 0) != 0: if msg.message == WM_HOTKEY and msg.wParam == hotkeyId: print "Yay!" windll.user32.PostQuitMessage(0) user32.TranslateMessage(byref(msg)) user32.DispatchMessageA(byref(msg)) --------------------------------------------------------------------- -- Richie Hindle richie at entrian.com From anton at vredegoor.doge.nl Tue Nov 11 15:33:41 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 11 Nov 2003 21:33:41 +0100 Subject: Python's simplicity philosophy References: <3FAC19F0.284DCB03@alcyone.com> Message-ID: David Eppstein wrote: >The argument is that reduce is usually harder to read than the loops it >replaces, and that practical examples of it other than sum are sparse >enough that it is not worth keeping it just for the sake of >functional-language purity. One argument in favor of reduce that I haven't seen anywhere yet is that it is a kind of bottleneck. If I can squeeze my algorithm through a reduce that means that I have truly streamlined it and have removed superfluous cruft. After having done that or other code mangling tricks -like trying to transform my code into a one liner- I usually have no mental problems refactoring it back into a wider frame. So some things have a use case because they require a special way of thinking, and impose certain restrictions on the flow of my code. Reduce is an important cognitive tool, at least it has been such for me during a certain time frame, because nowadays I can often go through the mental hoop without needing to actually produce the code. I would be reluctant to deny others the chance to learn how not to use it. Anton From gandalf at geochemsource.com Wed Nov 26 08:19:22 2003 From: gandalf at geochemsource.com (Gandalf) Date: Wed, 26 Nov 2003 14:19:22 +0100 Subject: Where can i get the python source for windows References: <188007e5.0311260450.4d92012b@posting.google.com> Message-ID: <3FC4A85A.2010103@geochemsource.com> > > >i need the source code of python 2.3 for windows. >I looked on ftp.python.org, but i can't find it. > >I need it, because i want to create a visual Mfc >debug application and for that i need >the python*_d.dll and python*_d.lib. > >Can anyone give me a hint, where i can get the sourcecode?? > > Did you try the CVS? http://www.python.org/download/cvs.html L 1.0 From oren-py-l at hishome.net Fri Nov 21 10:01:50 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Fri, 21 Nov 2003 10:01:50 -0500 Subject: Multiple inheritance in Java/C# In-Reply-To: <8ef9bea6.0311182031.38034c10@posting.google.com> References: <8ef9bea6.0311182031.38034c10@posting.google.com> Message-ID: <20031121150150.GA64779@hishome.net> On Tue, Nov 18, 2003 at 08:31:35PM -0800, Hung Jung Lu wrote: > Hi, > > I think Microsoft did look into Python when they designed C#. In C# 2.0 it looks like they copied Python's generator functions: http://dev.r.tucows.com/extdocs/c_sharp_2.0_spec.html#_Toc48187963 Oren From benles at bldigital.com Sun Nov 9 14:29:06 2003 From: benles at bldigital.com (Ben Allfree) Date: Sun, 9 Nov 2003 11:29:06 -0800 Subject: os.path.vnormpath References: Message-ID: Correct. vnormpath() should enforce the same rules web servers resolves a virtual paths on the server side. Example: Virtual root - C:\foo\baz\wwwroot URL -
The above should never resolve to anything higher than C:\foo\baz\wwwroot\grop.html regardless of its position in the web root directory. vnormpath("C:\\foo\\baz\\wwwroot", "..\\grop.html") == "C:\\foo\\baz\\wwwroot\\grop.html" Likewise (here's a catch): Virtual root - C:\foo\baz\wwwroot URL - Should resolve to C:\foo\baz\wwwroot\baz\wwwroot\grop.html I hope that make sense. My code is a start at solving the issue. "Peter Otten" <__peter__ at web.de> wrote in message news:bol2ob$1uv$03$1 at news.t-online.com... > Ben Allfree wrote: > > > Written to normalize web server path names based on a virtual root. I > > propose that something equivalent to this be added to os.path > > The purpose remains unclear to me. Maybe you could expand a little. > For now, I suppose you intend vnormpath() to always return subfolders of > root. > > > ------------------------------------- > > import os.path > > import copy > > > > def vnormpath(root,path): > > """ > > Normalize a path based on a virtual root. > > """ > > r = copy.deepcopy(root) > > p = copy.deepcopy(path) > > Strings are "immutable", i. e. you can't change them once created. You > therefore need not (I'd rather say must not) copy them. > > > > > if os.path.isabs(path): > > return root + path > > This can give you funny paths on Windows like "C:/firstC:/second"; on Unix > you can get anywhere the supplier of *path* wants, > e. g. vnormpath("/home/peter", "/../ben") returns "/home/peter/../ben" which > is equivalent to "home/ben". > > > while os.path.commonprefix([root, > > os.path.normpath(os.path.join(r,p))]) > > <> root: > > r = os.path.join(r,"junk") > > return os.path.normpath(os.path.join(r,p)) > > I tried to break that, too, but must admit I didn't succed so far :-) > By the way, most pythonistas favour != over <>. > > > if __name__ == "__main__": > > print vnormpath("C:\\foo\\baz", > > "..\\..\\..\\..\\foo\\baz\\..\\..\\..\\frob\\glop") > > The above demo is probably a good start, but try to think of a few more > use/test cases. For example, should > vnormpath("/home/ben", "/home/ben/temp") return "/home/ben/home/ben/temp" or > rather "home/ben/temp"? Also, I would compare vnormpath()'s actual against > the expected result instead of just printing it out. For production quality > code, have a look at the unittest module. > > Conclusion: For the moment, be satisfied if you can fix the bugs and your > function serves *your* needs well. If you want to share the results, put it > on a web site. > For your code to make it into the python library, you have to convince > people that *they* need it badly and I dare say that you may face some > strong opposition. > > Peter > > From Kristin.T.Uggen at sintef.no Tue Nov 18 11:12:31 2003 From: Kristin.T.Uggen at sintef.no (Uggen Kristin T) Date: Tue, 18 Nov 2003 17:12:31 +0100 Subject: MS Access with VB for applications and python Message-ID: <26AF0D77A98E09478A577B2248F7233875251A@sintefxch1.sintef.no> For the first time, I am trying to program python in a windows-environment, and now I am having some trouble with combining python and MS Access... This is what I want to do: A MS Access database is started, this database has numerous VB-forms, and one of those forms calls my python-program, so far so good. But before my python-program quits, I want to call one of the VB-forms in the database. This I haven't been able to find out how to do. The database cannot be closed, it has to run all the time while my python-program is working. So, if anyone can help me with this, I'll be very happy! Kristin From sross at connectmail.carleton.ca Wed Nov 19 10:24:27 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Wed, 19 Nov 2003 10:24:27 -0500 Subject: Multiple inheritance in Java/C# References: <8ef9bea6.0311182031.38034c10@posting.google.com> Message-ID: <4WLub.10649$ZF1.1133338@news20.bellglobal.com> "Hung Jung Lu" wrote in message news:8ef9bea6.0311182031.38034c10 at posting.google.com... > Does anyone know how to emulate Python-like MI in Java/C#? Hi. I believe this is usually done using a design pattern - I think its called "the proxy object pattern" or it may be "the delegator pattern", I'm not sure. I know that for doing CORBA programming with Java, you can have tie classes (which I believe use the aforementioned design pattern) generated to help simulate multiple inheritance. The idea is something like this: you have class C which inherits from A but you would like to have a class that inherits from A and B; make a class D that inherits from B, and that keeps an instance of C; D is your class that "inherits" from A and B; when you have an instance of d and you call a method derived from A, you delegate to the instance of C, otherwise you handle it directly. I think that's the general idea. You should be able to find specific examples somewhere online. HTH Sean From costanza at web.de Tue Nov 11 04:56:27 2003 From: costanza at web.de (Pascal Costanza) Date: Tue, 11 Nov 2003 10:56:27 +0100 Subject: Python from Wise Guy's Viewpoint In-Reply-To: <3fb097fe$1@news.unimelb.edu.au> References: <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <3F9D5D21.2060408@ps.uni-sb.de> <3fb097fe$1@news.unimelb.edu.au> Message-ID: Fergus Henderson wrote: > Suppose the original ML program defines the following functions > > foo : int -> int > bar : string -> string > ... > > We can add dynamic typing like this: > > datatype Generic = Int of int > | String of string > | Atom of string > | Cons Generic Generic > | Apply Generic Generic > | ... ^^^ How many do you need of those, especially when you want to allow that type to be extended in the running program? > Note that our symbol table includes an entry for the function "define", > so that eval can be used to modify the dynamic bindings. DEFUN is just one example. What about DEFTYPE, DEFCLASS, DEFPACKAGE, and so forth... > The program includes a definition for "eval", and "eval" is an > interpreter, So in that sense, we have added a new interpreter. That's the whole point of my argument. Pascal -- Pascal Costanza University of Bonn mailto:costanza at web.de Institute of Computer Science III http://www.pascalcostanza.de R?merstr. 164, D-53117 Bonn (Germany) From email9898989 at yahoo.com Thu Nov 6 13:27:52 2003 From: email9898989 at yahoo.com (email9898989 at yahoo.com) Date: 6 Nov 2003 10:27:52 -0800 Subject: [XPOST] [REQ] open source multimedia authoring tools? In python maybe? References: Message-ID: > > Or, you can use python for the app/quiz tool, and to play videos just > > launch the video file so that it opens in the user's movie player or > > browser, but you cannot play the video inside your python app. > > this is quite ugly, although effective; I'd do it but the final client > (an university) would find it undoubtely "too cheap" - also, it's bound > to give installation/portability problems unless you install every > possibile used tool, and I'd rather have something like SDL/pygame take > care of that layer... I forgot to mention, if it can be Windows-only, you can embed Internet Explorer in your wxPython app and play the videos with it. See ActiveXWrapper_IE in the wxpython demo. David Woods also figured out a way to play video in wxPython using an ActiveX interface to ActiveMovie on the Windows side and a Carbon/Quicktime wrapper for the Mac side: http://www2.wcer.wisc.edu/Transana/Develop See the video_mac.py and video_msw.py files here: http://cvs.sourceforge.net/viewcvs.py/transana/transana/transana/src/ From fjh at cs.mu.oz.au Tue Nov 18 01:14:44 2003 From: fjh at cs.mu.oz.au (Fergus Henderson) Date: Tue, 18 Nov 2003 06:14:44 GMT Subject: Python from Wise Guy's Viewpoint References: <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <3F9D5D21.2060408@ps.uni-sb.de> <3fb097fe$1@news.unimelb.edu.au> <3fb0bf48$1@news.unimelb.edu.au> Message-ID: <3fb9b8d0$1@news.unimelb.edu.au> Pascal Costanza writes: >Fergus Henderson wrote: >>Pascal Costanza writes: >>>Fergus Henderson wrote: >>>>The program includes a definition for "eval", and "eval" is an >>>>interpreter, So in that sense, we have added a new interpreter. >>> >>>That's the whole point of my argument. >> >> Then it's a pretty silly argument. >> >> You ask if we can implement eval, which is an interpreter, >> without including an interpreter? > >Right. Then the answer is obviously no -- regardless of which language you use, and whether it is statically typed or not. In some cases the interpreter might be included as part of the standard library or even as a builtin-in language feature, in other cases it may need to be written as part of the program, but either way, it will still need to be included. >> I don't see what you could usefully conclude from the answer. > >...that you can't statically type check your code as soon as you >incorporate an interpreter/compiler into your program that can interact >with and change your program at runtime in arbitrary ways. This conclusion doesn't follow. How could it, since neither the question nor the answer made any reference to static type checking? -- Fergus Henderson | "I have always known that the pursuit The University of Melbourne | of excellence is a lethal habit" WWW: | -- the last words of T. S. Garp. From martin at v.loewis.de Sun Nov 2 21:37:45 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 03 Nov 2003 03:37:45 +0100 Subject: Distinguishing cp850 and cp1252? In-Reply-To: References: Message-ID: David Eppstein wrote: > Is there an easy way of guessing with reasonable accuracy which of these > two incodings was used for a particular file? You could try the assumption that most characters should be letters, assuming your documents are likely text documents of some sort. The idea is that what is a letter in one code is some non-letter graphical symbol in the other. So you would create a predicate "isletter" for each character set, and then count the number of bytes in a document which are not letters. You should probably exclude the ASCII characters in counting, since they would have the same interpretation in either code. The code that gives you fewer/none no-letter characters is likely the correct interpretation. To find out which bytes are letters, you could use unicodedata.category; letters start with "L" (followed by either "l" or "u", depending on case). You should compute a bitmap for each character set up-front, and you should find out what the overlap in set bits is. To get a higher accuracy, you need advance knowledge on the natural language your documents are in, and then you need to use a dictionary of that language. HTH, Martin From bdesth.nospam at removeme.free.fr Sat Nov 29 17:34:25 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Sat, 29 Nov 2003 23:34:25 +0100 Subject: sorting dictionary keys? In-Reply-To: References: Message-ID: <3fc91af5$0$28610$636a55ce@news.free.fr> Jay O'Connor wrote: > John Smith wrote: > > > Hi, what's the fastest way (least amount of typing) > > Never good criteria > >> but I would like to do: >> #error here >> for k in d.keys().sort(): >> print k, d[k] >> >> why doesn't the nested function call work? Thanks in advance. >> > > sort() sorts in place and returns None > Which is one of the main PITA in Python IMHO :( (not the fact that it sort in place, the fact that it does not return self). Bruno From mwh at python.net Wed Nov 5 08:35:52 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 5 Nov 2003 13:35:52 GMT Subject: class with invalid base class References: Message-ID: <7h31xsnhrfp.fsf@pc150.maths.bris.ac.uk> Thomas Heller writes: > "Andrew Dalke" writes: > > > Out of curiosity, I tried passing using an invalid base > > for a class. I can't explain why I got the error messages > > I did. Can someone here enlighten me? > > > > # Here I'm just curious > > > >>>> def spam(a, b): > > ... return a+b > > ... > >>>> class Spam(spam): > > ... pass > > ... > > Traceback (most recent call last): > > File "", line 1, in ? > > TypeError: function() argument 1 must be code, not str > >>>> > > > > # What's 'function'? Why is it called? > > It's the Don Beaudry hook ;-). If the base class has callable a > __class__ attribute, this is called with three arguments: The name of > the new class, a tuple of the bases, and a dictionary. Or something like > this, the details may be wrong... Actually, I think it's type(baseclass) that gets called -- otherwise you wouldn't be able to inherit from old-style classes! What's changed since 2.2 is that type objects are now callable. (Isn't it amazing how something as simple as metaclasses -- and they *are* a simple idea -- can be *so* confusing? I wrote and rewrote that paragraph at least three times...) Cheers, mwh -- But since your post didn't lay out your assumptions, your goals, or how you view language characteristics as fitting in with either, you're not a *natural* candidate for embracing Design by Contract <0.6 wink>. -- Tim Peters, giving Eiffel adoption advice From bokr at oz.net Tue Nov 18 18:44:03 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Nov 2003 23:44:03 GMT Subject: time.mktime memory access violation bug Message-ID: Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.mktime((1969, 12, 31, 17, 0, 0, 0, 0, 0)) 3600.0 >>> time.mktime((1969, 12, 31, 17, 0, 0, 0, 0, 1)) 0.0 >>> time.mktime((1969, 12, 31, 16, 0, 0, 0, 0, 1)) [crash with popup] I got: The instruction at "0x7802a7ff" referenced memory at "0x00000000". The memory could not be "read". I would have hoped for an informative ValueError exception. This is on NT4. My local time zone is PST. If I let the MSVC++6 debugger try to chase it, it says Unhandled exception in python.exe (MSVCRT.DLL): 0xC0000005: Access Violation and fwiw without source it's pointing to the rep movs in this context: 7802A7F1 call 7802A4BF 7802A7F6 pop ecx 7802A7F7 push 9 7802A7F9 mov esi,eax 7802A7FB mov eax,dword ptr [ebp+8] 7802A7FE pop ecx 7802A7FF rep movs dword ptr [edi],dword ptr [esi] 7802A801 pop edi 7802A802 pop esi 7802A803 pop ebp 7802A804 ret 7802A805 test ecx,ecx and esi is zero, so I guess that did it. Someone have a debug version to check this out? Regards, Bengt Richter From eppstein at ics.uci.edu Mon Nov 10 14:29:25 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 10 Nov 2003 11:29:25 -0800 Subject: More user feedback on Sets.py References: <1hSqb.1167$bQ3.696@nwrdny03.gnilink.net> Message-ID: I had a natural example of sets of sets of sets of sets today... I wanted to explore the trees having n labeled items at their leaves . Each edge of such a tree forms a bipartition of the set of leaves, so I represented the tree as the set of its bipartitions. Each bipartition is itself a set {S, U-S} where U is the set of all leaves and S is some subset of U. So, each tree is represented as a set of sets of sets. I ran some algorithms that involved sets of trees, so these algorithms constructed sets of sets of sets of sets... This was all relatively easy using sets.py (23 new lines added to the code I was already using for exploring other combinatorial objects) and would have been much more cumbersome if I had to represent sets explicitly as bit vectors or dictionaries. So, thanks for sets, and thanks for making it work under python 2.2! -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From janeaustine50 at hotmail.com Fri Nov 21 11:09:08 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 21 Nov 2003 08:09:08 -0800 Subject: jython lacks working xml processing modules? References: <3FBDF1E7.5ADB00B2@hotmail.com> Message-ID: Alan Kennedy wrote in message news:<3FBDF1E7.5ADB00B2 at hotmail.com>... > [Jane Austine] > > I'm trying to parse an xml file with jython (not through java parsers > > like xerces). > > > > I tried minidom in jython 2.1 and 2.2a but all failed. > > It's quite likely that your documents contained namespaces. No. Jython 2.1 on java1.4.2-beta (JIT: null) Type "copyright", "credits" or "license" for more information. >>> from xml.dom import minidom >>> minidom.parseString('foobar') Traceback (innermost last): File "", line 1, in ? File "C:\work\jython-2.1\Lib\xml\dom\minidom.py", line 913, in parseString File "C:\work\jython-2.1\Lib\xml\dom\minidom.py", line 900, in _doparse File "C:\work\jython-2.1\Lib\xml\dom\pulldom.py", line 251, in getEvent AttributeError: feed >>> > The only > parser supported in jython is "xmlproc", because it is pure python. I can't make it work. >>> import xml.sax,xml.dom.minidom >>> p=xml.sax.make_parser(["xml.sax.drivers2.drv_xmlproc"]) >>> xml.dom.minidom.parseString('foobar',parser=p) Traceback (innermost last): File "", line 1, in ? File "C:\work\jython-2.1\Lib\xml\dom\minidom.py", line 913, in parseString File "C:\work\jython-2.1\Lib\xml\dom\minidom.py", line 900, in _doparse File "C:\work\jython-2.1\Lib\xml\dom\pulldom.py", line 251, in getEvent AttributeError: feed > However, "xmlproc" has some significant bugs in relation to namespace > processing, IIRC from the last time I looked at it. > > > What can I do? > > 1. Use a Java SAX2 parser, write a jython ContentHandler for it, build > a Minidom from the events. > 2. Use a Java DOM processor (DOM4J, JDOM, etc), and let it build a DOM > for you. > > It would probably be easier if you could give an outline of what you > are trying to achieve. For example, do you really need to build an > object model? Do you need to use xpath? Do you need to validate > structures? Etc, etc. > I need the tree model of the xml document. So I'm trying to use DOM parsers. > > The last resort would be using java parsers. Then how > > can I use them like python xml parsers? It seems like javadom and > > javasax has something to do, but I don't know how. > > If you want to know about using SAX events to build object models, > check this old thread on c.l.py. > > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=mailman.1058894673.16506.python-list%40python.org > > If you have any specific questions or face any specific problems, post > some details. > > regards, From stephan.diehlNOSPAM at gmx.net Tue Nov 25 10:04:57 2003 From: stephan.diehlNOSPAM at gmx.net (Stephan Diehl) Date: Tue, 25 Nov 2003 16:04:57 +0100 Subject: Bug or Feature? References: <2259b0e2.0311240603.549943b3@posting.google.com> <9cf48f3e1bcf524ab4ad581a061d1852@news.teranews.com> <07279b32fe8f5b18377a1df8467647b6@news.teranews.com> Message-ID: Dang Griffith wrote: > On Mon, 24 Nov 2003 19:35:51 +0100, Stephan Diehl > wrote: > >>Dang Griffith wrote: >> >>> On Mon, 24 Nov 2003 18:13:34 +0100, Stephan Diehl >>> wrote: >>> >>> ... >>>>This is probably more a theoretical question, but if I decide to have an >>>>operation within one specific domain, I want the result in that domain >>>>too. Otherwise, there would be no point at all to define such a numeric >>>>class at all. >>>> >>>>Stephan >>> >>> I understand what you're saying, but there's no universal rule that >>> says that the result of operations between members of a set are also >>> members of the set. Obvious examples include division on the set of >>> integers, and division over the set of real numbers, i.e.division by >>> zero is not a real number. >>> --dang >> >>If we have a look at the mathematical definition of numbers, the >>interesting thing is not the set of these numbers, but the set combined >>with some usefull operators (like addition and multiplication). >>It is (mathematicaly speaking) not possible to have a result under these >>operations that are outside the definition. >> >>In that sense, there IS this universal rule, you were talking about. (and >>division by zero is just not allowed by definition). >> >>Stephan > And for the set of whole numbers, some divisions are allowed, but any > division that results in a fraction would not be allowed. By > definition, i.e. a combination of operators and operands that result > in a value not in the same domain is not a valid combination. It > works, but seems circular. :-) > --dang You might have noticed, I was talking about Mathematics, not the imperfect implementation of it in computers :-) To have division as a meaningfull operation, the set in question must be a group under the '*' operation (See for example "http://en2.wikipedia.org/wiki/Group_(mathematics)" ) The point is, that division is the reverse operation to multiplication. Cheers, Stephan From phil_nospam_schmidt at yahoo.com Fri Nov 14 13:21:55 2003 From: phil_nospam_schmidt at yahoo.com (Phil Schmidt) Date: 14 Nov 2003 10:21:55 -0800 Subject: Making a maze.... References: <1PSsb.44675$jy.34613@clgrps13> Message-ID: <221e7b06.0311141021.2456d03@posting.google.com> I did this 20+ years ago, in Z80 assembly on a TRS-80. It drove an Epson MX-80 lineprinter to produce the output. I later converted it to C when I was learning that language around '88, and had the maze generate and display on the screen, using different colored cells for different cell states. The resulting display resembles a grass fire on a calm day (hmm, what if the algorithm considered "wind"? But I digress), in that it starts as a point at a random location, and grows out from that point in a random fashion, spreading out until all cells are part of the maze (they are "burned out"). Anyway, here is the algorithm. Hopefully I haven't forgotten any steps: 1) Start with a grid of cells, with each cell being marked as "virgin territory". 2) Pick any cell at random, and mark it as "explored". From that cell, identify all the adjacent "virgin territory" cells, and mark them as "frontier". 3) Pick any random "frontier" cell X from the maze, and choose from X at random any wall that adjoins an "explored" cell. Remove that wall, and mark cell X as "explored". Also from cell X, identify all the adjacent "virgin territory" cells, and mark them as "frontier". 4) Repeat (3) until there are no more "frontier" cells. You will need to deal with the boundaries. The "virtual" cells just outside the boundaries have the property that they can't become "frontier" cells, and therefore can't become part of the maze. This will produce a maze with the property that there will be one and only one path from any cell to any other cell in the maze. So, to have an entry and exit to the maze, just open the walls of two cells at the boundaries of the maze. I never tried this with anything but a rectangular grid. It would be fun to use a hexagonal grid. It would also be interesting to do it in 3-D. Sometimes I wish I were still a kid, and had time to play with this kind of stuff... :) From marfadeu at gmx.de Mon Nov 3 05:15:27 2003 From: marfadeu at gmx.de (Markus Faust) Date: Mon, 03 Nov 2003 11:15:27 +0100 Subject: F2py and Compaq Visual Fortran 6.6, Win-XP In-Reply-To: References: Message-ID: <3FA62ABF.6070501@gmx.de> Pearu Peterson (pearu at cens.ioc.ee) replied by email: On Mon, 3 Nov 2003 M wrote: >> This looks much better now, but I do not succeed in invoking the Visual >> Fortran Compiler. f2py always calls the mingw compiler. Do you have an >> idea? Thanks in advance Markus! This is because f2py finds mingw compiler first. You can force f2py to use other compilers either by defining FC_VENDOR=Compaq environment variable or using --fcompiler=Compaq switch. Note that the latter does not work with f2py.bat script on windows and as a workaround write a f2py.py script containing two lines import f2py2e f2py2e.main() In fact, I am dropping f2py.bat support for future f2py releases (because I don't how to prevent .bat script to replace `=` with ` `). So, you can remove f2py.bat altogether from your system. Regards, Pearu From dada_ali at hotmail.com Fri Nov 14 17:33:52 2003 From: dada_ali at hotmail.com (Ali Dada) Date: Fri, 14 Nov 2003 23:33:52 +0100 Subject: setup.py question (newbie) Message-ID: hi all: i want to write an application with python, but first i was checking how to set (or let the user choose) the install directory and the application data directory. i was reading in the documentation "Distributing Python modules" and i understood i should do 2 things to accomplish my 2 objectives (setting the install directory and setting the application data directory): 1) writing a setup.cfg configuration file in the same directory as the setup file and in it i specify the options for the install command (rather than adding them to the cmd prompt) my file went like: [install] install-base= C:\Program Files\pirt 2) execute something like: >python setup.py bdist_wininst install install_scripts to get a windows installer for my application, and in a script i could put the initialization code i want, for now simply creating a directory but it didn't work. i got an installer but the options were unchangeable: installation directory was C:\Python23\Lib\site-packages\ (not as i specified in setup.cfg) and the script i wrote wasn't run so in short: how can i, in unix and windows, give default values such as "C:\Program Files\myApp" and "C:\Documents and Settings\user\Application Data" and let the user have the ability to change them (like in all install scripts), does distutils give me a neat functionality or will i go ahead and write a small python script from scratch?? thanks.. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sorr at rightnow.com Wed Nov 26 17:40:04 2003 From: sorr at rightnow.com (Orr, Steve) Date: Wed, 26 Nov 2003 15:40:04 -0700 Subject: Compressing output via pipes Message-ID: Thanks but what about os.mknode() in 2.3? The docs don't say it's UNIX only. So without named pipes support in windoze there isn't ANYWAY to do this? Windoze sucks. Any possible non-portable pythonic way to do this in *nix? Thanks again. -----Original Message----- From: python-list-bounces+sorr=rightnow.com at python.org [mailto:python-list-bounces+sorr=rightnow.com at python.org] On Behalf Of Paul Moore Sent: Wednesday, November 26, 2003 3:30 PM To: python-list at python.org Subject: Re: Compressing output via pipes "Orr, Steve" writes: > Oracle provides an export utility (exp) and I have a shell script > which compresses its output (not stdout) thru a pipe but l need a > platform portable Python script for this. How platform portable? If you want to do this on Windows, you're basically out of luck, as Windows doesn't support named pipes like this. If you're talking just Unix variants, I'd guess that a minimal shell script is as portable as you need. Paul -- This signature intentionally left blank -- http://mail.python.org/mailman/listinfo/python-list From __peter__ at web.de Wed Nov 5 13:40:38 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Nov 2003 19:40:38 +0100 Subject: reduce() anomaly? References: Message-ID: Stephen C. Waterbury wrote: > This seems like it ought to work, according to the > description of reduce(), but it doesn't. Is this > a bug, or am I missing something? > > Python 2.3.2 (#1, Oct 20 2003, 01:04:35) > [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> d1 = {'a':1} > >>> d2 = {'b':2} > >>> d3 = {'c':3} > >>> l = [d1, d2, d3] > >>> d4 = reduce(lambda x, y: x.update(y), l) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1, in > AttributeError: 'NoneType' object has no attribute 'update' > >>> d4 = reduce(lambda x, y: x.update(y), l, {}) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1, in > AttributeError: 'NoneType' object has no attribute 'update' > > - Steve. No bug, your lambda evaluates d1.update(d2) on the first call and then returns the result of the update() method which is None. So on the secend call None.update(d3) fails. Here's what you might have intended: >>> d1 = {'a':1} >>> d2 = {'b':2} >>> d3 = {'c':3} >>> l = [d1, d2, d3] >>> d4 = reduce(lambda x, y: x.update(y) or x, l) >>> d4 {'a': 1, 'c': 3, 'b': 2} Note the side effect on d1 >>> d1 {'a': 1, 'c': 3, 'b': 2} if you don't provide an initial dictionary. Peter From richie at entrian.com Fri Nov 7 05:50:20 2003 From: richie at entrian.com (Richie Hindle) Date: Fri, 07 Nov 2003 10:50:20 +0000 Subject: Rekall not longer available from theKompany.com - a fabrication In-Reply-To: References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <3fa6a75e$0$12666$fa0fcedb@lovejoy.zen.co.uk> Message-ID: [Richie] > Your website (http://www.totalrekall.co.uk) says "The GPL version would be > free for non-commercial use", which is a contradiction. [Phil] > There's nothing innacurate or contradictory in that statement. After > all, the GPL *is* "free for non-commercial use"; it just happens to > be free for commerical use as well -- and the website doesn't say > that it isn't, it just omits to mention that it is. You are right of course. Let me be more precise (addressing John again): The words used on your website seem to me to imply that the GPL version could not be used commercially. If that is the intention of those words, you are mistaken about either the meaning of the GPL, or your power as a copyright owner to control the application of the GPL to your code. If you release your code under the GPL, it can be used commercially, and you cannot change that. (I vote Phil for pedant of the week. 8-) -- Richie Hindle richie at entrian.com From klapotec at chello.at Thu Nov 27 17:28:29 2003 From: klapotec at chello.at (Christopher Koppler) Date: Thu, 27 Nov 2003 22:28:29 GMT Subject: if - else References: <871xrtr8yb.fsf@pobox.com> <5ctxb.120283$Ec1.5141313@bgtnsc05-news.ops.worldnet.att.net> Message-ID: On Thu, 27 Nov 2003 21:43:31 GMT, Jeff Wagner wrote: >On Thu, 27 Nov 2003 20:33:05 GMT, "Andrew Koenig" wrotf: > >>> True, also someone's being careless with their code. >>> >>> if SumOfNumbers = 10: >>> SumOfNumbers = 1 >>> >>> What happens with that? :) >> >>In Python? Easy -- it doesn't compile. >> > >Ok, why won't it compile? I thought the standard if statement went like this - > >if Condition: > suite > >so why won't the above work? I realize it's not the best way to accomplish what I want to do, I'm >just trying to learn why it is an incorrect if statement so I know for the future. It does assignment (=) instead of comparison (==) in the condition, which is illegal in Python. -- Christopher From garabik-news-2002-02 at kassiopeia.juls.savba.sk Thu Nov 6 09:23:18 2003 From: garabik-news-2002-02 at kassiopeia.juls.savba.sk (Radovan Garabik) Date: 6 Nov 2003 14:23:18 GMT Subject: Unicode and Zipfile problems References: <3fa8d5ee.304218@news.t-online.de> Message-ID: vincent wehren wrote: > > "Gerson Kurz" schrieb im Newsbeitrag > news:3fa8d5ee.304218 at news.t-online.de... > | AAAAAAAARG I hate the way python handles unicode. Here is a nice > | problem for y'all to enjoy: say you have a variable thats unicode > | > | directory = u"c:\temp" > | > | Its unicode not because you want it to, but because its for example > | read from _winreg which returns unicode. > | > | You do an os.listdir(directory). Note that all filenames returned are > | now unicode. (Change introduced I believe in 2.3). > > Wrong. > > That's only true if type(directory) gives you > If you call str(directory) before doing os.listdir(directory) > you (in most cases) want even notice and can continue doing what you want to > do > just fine - plus, and that's the good part - you can forget about > those hacks you suggest later and which some would consider *evil*. > It'll save yourself some time too. > > Hey, and leave my Swahili friends alone will ya! ;) Uhm, AFAIK Swahili does not use any special characters in the alphabet (if you do not count digraphs, that is). Plain old ASCII is sufficient Not that my remark is useful for anything, though. > | Now, could anybody please just write a > | "i-don't-care-if-my-app-can-display-klingon-characters" raw byte > | encoding which doesn't throw any assertions and doesn't care whether > | or not the characters are in the 0x7F range? Its ok if I cannot port > | my batchscripts to swaheli, really. but you HAVE TO care, since on MS Windows, if a filename is unicode, it is UTF-16 and you just cannot convert it into stream of bytes without messing up with encodings. UTF-16 is not even ASCII compatible, after all. -- ----------------------------------------------------------- | 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 no at no.no.net.org.tv.com.edu.welf Tue Nov 11 07:20:58 2003 From: no at no.no.net.org.tv.com.edu.welf (RaYzor) Date: Tue, 11 Nov 2003 12:20:58 GMT Subject: Matrix - Metaphors, Analogies and the REAL References: Message-ID: "3seas" <3seasA at Tthreeseas.DOT.not> wrote in message news:xrQrb.21530$9M3.5754 at newsread2.news.atl.earthlink.net... > If you are not interested, then don't bitch, its a short message. > > http://www.matrixcommunity.org/cgi-bin/ultimatebb.cgi?ubb=get_topic;f=8;t=000918 > > I don't know if that link got broken. > People who think the Matrix series of films are real in any way are amongst the saddest people on Earth. Its OK to like a movie, sure. Even being a super-fan is allright. I like Star Wars series a lot, I have 4 or 5 Star Wars games, I own all the movies. But I don't wander into AMIGA (or for that matter, ANY) newsgroups and start theorizing on how I can use the Dark Side of the Force ... in random, meaningless spurts of convulted text. This is because I know its just a movie. You should really try to get out more. The Matrix series of movies are just movies. And not even GOOD movies. No reality to them at all. Seek help if you think otherwise. RaYzor From benles at bldigital.com Sat Nov 8 19:57:53 2003 From: benles at bldigital.com (Ben Allfree) Date: Sat, 8 Nov 2003 16:57:53 -0800 Subject: os.path.vnormpath Message-ID: Written to normalize web server path names based on a virtual root. I propose that something equivalent to this be added to os.path ------------------------------------- import os.path import copy def vnormpath(root,path): """ Normalize a path based on a virtual root. """ r = copy.deepcopy(root) p = copy.deepcopy(path) if os.path.isabs(path): return root + path while os.path.commonprefix([root, os.path.normpath(os.path.join(r,p))]) <> root: r = os.path.join(r,"junk") return os.path.normpath(os.path.join(r,p)) if __name__ == "__main__": print vnormpath("C:\\foo\\baz", "..\\..\\..\\..\\foo\\baz\\..\\..\\..\\frob\\glop") From http Wed Nov 19 12:35:38 2003 From: http (Paul Rubin) Date: 19 Nov 2003 09:35:38 -0800 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <3FBB805D.40A8DA75@engcorp.com> Message-ID: <7x65hgb6s5.fsf@ruckus.brouhaha.com> "Dave Brueck" writes: > Rotor was nice because for very little costs in terms of CPU / > coding nuisance you could protect semi-sensitive data from nearly > everyone. But given that your application is runnign in interpreted Python, any speed difference between rotor and AES is likely to be insignificant in practice. So you may as well use AES. > Sure it's strength-per-bit-of-key-size doesn't stack up > well against more modern algorithms, but for the vast majority of > users (including myself) data encrypted with rotor or AES is, for > all practical purposes, equally untouchable. No, I don't believe that. If you want to break something encrypted with rotor and you don't have the knowledge or inclination to do it yourself, you can hire someone else to do it for you (possibly using one of the automated tool suites that exist for breaking rotor-like ciphers). Breaking rotor might be as difficult as synthesizing heroin, but there's a heroin problem as long as there are a few specialists who can make it, so that others who can't make it themselves can buy it from the specialists instead. It's the same way with weak cryptography of any sort. > As a built-in data > obfuscator, rotor filled about 99% of my "security" needs. Is 99% really good enough? Would you ride in a car if you had a 1% chance of a fatal crash every time you got behind the wheel? How many users (i.e. potential attackers) does your (e.g.) web site have? Is it really acceptable for your site to be secure against only 99% of them? If you have 10,000 users, that would mean 100 of them can successfully break your cipher. Me, I'll go for 100% or as close to it as I can get, not 99%. Hmmm... the more I think about it I guess the root cause of the problem is the archaic, goofy encryption export laws of the U.S.. Those laws (actually regulations) are still goofy and archaic, but they've softened up to the point where it's now feasible to ship real encryption with Python. It's being worked on. If Python could ship with AES or 3DES and I'd use that, but right now adding an external encryption package just to tell casual snoopers, "it's not worth your time to crack this file - keep moving" seems so over the top. I've posted a pure-python module that's just a page or two of code, that should provide much better security than rotor and runs fast enough for most practical Python apps. I think it is ok as a stopgap til Python gets real encryption. From talon2lm at yahoo.com Sun Nov 2 21:16:25 2003 From: talon2lm at yahoo.com (Rob) Date: Sun, 2 Nov 2003 19:16:25 -0700 Subject: Shelve newbie?? Message-ID: I have been tasked, an assignment from school, to make a usable database using this code...my question, Where is there some good doc on how to use Shelve? The python.org doesn't say much of anything about it. It's driving me nutty. I'm trying to figure out a way to delete enteries (with user inputting the name). Here's the code so far...Obviously it's not ready for turn in! import shelve import string #import pickle UNKNOWN = 0 HOME = 1 WORK = 2 FAX = 3 CELL = 4 class phoneentry: def __init__(self, name = 'Unknown', number = 'Unknown', type = UNKNOWN): self.name = name self.number = number self.type = type # create string representation def __repr__(self): return('%s:%d' % ( self.name, self.type )) # fuzzy compare or two items def __cmp__(self, that): this = string.lower(str(self)) that = string.lower(that) if string.find(this, that) >= 0: return(0) return(cmp(this, that)) def showtype(self): if self.type == UNKNOWN: return('Unknown') if self.type == HOME: return('Home') if self.type == WORK: return('Work') if self.type == FAX: return('Fax') if self.type == CELL: return('Cellular') class phonedb: def __init__(self, dbname = 'C:/phonedata'): self.dbname = dbname; self.shelve = shelve.open(self.dbname); def __del__(self): self.shelve.close() self.shelve = None def add(self, name, number, type = HOME): e = phoneentry(name, number, type) self.shelve[str(e)] = e def lookup(self, string): list = [] for key in self.shelve.keys(): e = self.shelve[key] if cmp(e, string) == 0: list.append(e) return(list) # if not being loaded as a module, run a small test b = 1 foo = phonedb() while b != 3: print b print "Welcome to the Phone Database" print "Please choose from the following" print print "If you would like to add an entry select 1" print print "If you would like to delete for an entry select 2" print print "To quit select 3 " b = input(':') if b == 1: print "Please enter the full name: (Example: John Smith)" n = raw_input(':') print "Please enter the phone number: (Example: 970-432-5432)" p = raw_input(':') print "Please enter the phone type: (0 = Unkown, 1 = Home, 2 = Work, 3 = Fax, 4 = Cell)" t = raw_input(':') if t == '0': foo.add(n, p, UNKNOWN) if t == '1': foo.add(n, p, HOME) if t == '2': foo.add(n, p, WORK) if t == '3': foo.add(n, p, FAX) if t == '4': foo.add(n, p, CELL) print t if b == 2: print "Enter the name to delete" d = raw_input(':') #foo.add('Sean Reifschneider', '970-555-2222', CELL) #foo.add('Evelyn Mitchell', '970-555-1111', HOME) print 'First lookup:' for entry in foo.lookup('reifsch'): print '%-40s %s (%s)' % ( entry.name, entry.number, entry.showtype() ) print print 'Second lookup:' for entry in foo.lookup('e'): print '%-40s %s (%s)' % ( entry.name, entry.number, entry.showtype() ) From nospam at nowhere.hu Tue Nov 18 16:58:47 2003 From: nospam at nowhere.hu (Jegenye 2001 Bt) Date: Tue, 18 Nov 2003 22:58:47 +0100 Subject: using Python to run other programs References: <7T02VNBM37943.8988541667@Gilgamesh-frog.org> Message-ID: Download Duplicity, there's a nice GnuPG module in it, which would also demonstrate the technique how this can be done. http://www.nongnu.org/duplicity To send e-mail is pretty easy by using the standard library. Have a look at the tutorial which comes with your Python installation. Best, Mikl?s Frog wrote in message news:7T02VNBM37943.8988541667 at Gilgamesh-frog.org... > Hi, i'm not a programmer so I have a very stupid question. I'm trying to > make a practical script. I need to run an executable program in it but i > can't get it to work. Maybe someone here can figure it out easily: > > ----- > #! /python > > a = (recipient's e-mail address) > > pgp -feat a > > (sendmail to address after encryption) > ------ > > How do I get python to open the pgp program? > > Should I use an environment other than python? > > thanks! > > From peter at engcorp.com Thu Nov 6 09:27:28 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Nov 2003 09:27:28 -0500 Subject: Question re threading and serial i/o References: <246a4e07.0311040705.5f8d9a9@posting.google.com> <3FA7CB03.6B650215@engcorp.com> <246a4e07.0311060251.3a24d5b@posting.google.com> Message-ID: <3FAA5A50.C05D7C0D@engcorp.com> Frank Millman wrote: > > This is my Mk 3 version, using select() - > def scan(): > p = file('/dev/ttyS0') > while x: > ans = select.select([p],[],[],0.1) > if ans[0]: > print ord(p.read(1)) > p.close() > > The scanner sends a string consisting of 'code' 'qty' . If I > scan a code of '1' and a quantity of '1', I would expect the program > to display 49 9 49 13. The Mk 2 version does this correctly. > > The Mk 3 version behaves differently. After the first scan, it > displays 49. After each subsequent scan, it displays 9 49 13 49. > > If anyone can explain what I am doing wrong, I will be most grateful. > In the meantime I am sticking with Mk 2, as it is doing the job. Not entirely sure... but what is "x" in the while statement? This might be the answer though: when select() returns, it says that there is "some" data waiting to be read, not just one byte. You are reading only one byte, however. Depending on what "x" is, this might mean you are going back to read another single byte only after some other condition comes true. Another possibility is that you have not opened the file in non-blocking mode. I don't know what the effect of that would be on the select() statement, but if you did use non-blocking, you could change the read() call to get a whole bunch of data at a time, instead of only one byte. If you did p.read(1024), for example, on a non-blocking file, you should get back anywhere from 1 to 1024 bytes after select indicates it is readable. If nothing else, this will speed up your final result, in either case. (You can't do that on a block read, of course, since it would then block until all 1024 bytes were available, which might never happen.) -Peter From http Sat Nov 22 17:14:25 2003 From: http (Paul Rubin) Date: 22 Nov 2003 14:14:25 -0800 Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> Message-ID: <7xwu9svyny.fsf@ruckus.brouhaha.com> bokr at oz.net (Bengt Richter) writes: > The question ISTM is whether importing a GPL'd module is enough to > trigger GPL obligations on the part of the importing module. That is a correct statement of the question. According to the FSF, the answer to the question is yes, that's enough to trigger the obligations. > ISTM that is more like a program-program relationship than > incorporation of code (unless it modifies the source. e.g., with an > execfile and changes based on source knowledge). I.e., if a non-GPL > module could be substituted without changing the importer, IWT that > would mean plug-compatibility rather than incorporation. But IANAL. The FSF's lawyer IAL, and he says you're in error. > I haven't read the license recently, but I thought there there was > some arms-length uses of GPL software by proprietary software that > are allowed, or am I mistaken? I don't know how long the arm has to > be though. Somewhat longer than importing a module into your program's address space and calling it through a subroutine interface. From rmunn at pobox.com Sat Nov 22 10:46:47 2003 From: rmunn at pobox.com (Robin Munn) Date: Sat, 22 Nov 2003 15:46:47 GMT Subject: a scipy installation problem? References: Message-ID: avik wrote: > Robin Munn wrote in message >> What happens if you do "import scipy" instead of "from scipy import *"? >> >> "from ... import *" is _almost_ always a bad idea anyway, since it >> clutters up your namespace. It also causes issues with the reload() >> function. Avoid that usage unless you *really* know what you're doing. > > Actually, up to now (during a short time, anyway) I have always used > "import " without having any special reason to avoid "from > import *" :-). > In the case of scipy I just tried out the first thing that's written > in its short tutorial and > > the same is with that: > >>>> import scipy > Segmentation fault (core dumped) > > Regards OK, so "from ... import *" isn't the culprit. I see in your original post that you downloaded the binaries and copied them into your site-packages. It may be that the binaries you downloaded were linked against a library version you don't have. Try downloading a source archive and doing "python setup.py install" to install it. I'm guessing that will fix the segfault problem. -- Robin Munn rmunn at pobox.com From skip at pobox.com Thu Nov 13 22:47:07 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 13 Nov 2003 21:47:07 -0600 Subject: Palindrome In-Reply-To: References: <20031112223135.29045.00000109@mb-m12.aol.com> Message-ID: <16308.20539.482337.663188@montanaro.dyndns.org> Andrew> Gerrit Holl >> Are you looking for: >> 20:58:42:232:0 >>> def ispalindrome(s): >> 20:58:42:232:0 ... return s == s[::-1] Andrew> No. The OP wanted to strip special characters and Andrew> normalize case, so that Andrew> A man, a plan, a canal -- Panama! Andrew> would be allowed as a palindrome. Oh, then how about: import re def ispalindrome(s): s = re.sub("[^A-Za-z0-9]+", "", s).lower() return s == s[::-1] for s in ( "A man, a plan, a canal -- Panama!", "1234", "123321", "Madam, I'm Adam."): print s, "->", ispalindrome(s) Skip From spam-me-senseless at microsoft.com Fri Nov 7 20:18:49 2003 From: spam-me-senseless at microsoft.com (Aum) Date: Sat, 08 Nov 2003 14:18:49 +1300 Subject: Need neural net library Message-ID: Hi, Can anyone please recommend a python-accessible library for neural network simulation? I've already got code for standard feed-forward, back-propagation networks, but am needing something which does recurrent networks. Also desirable is self-organising maps and Hopfield nets. Thanks in advance for your help Cheers Aum From __peter__ at web.de Fri Nov 14 03:01:46 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Nov 2003 09:01:46 +0100 Subject: logging.shutdown() ValueError: I/O operation on closed file References: Message-ID: j vickroy wrote: > > Here is the result of not closing a handler manually -- Peter's suggestion > (3) > > Traceback (most recent call last): > File > "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "E:\$PROJECTS\experimental\Py Logging\t_xc.py", line 61, in ? > log.error('testing Python logging module') > File "C:\Python23\lib\logging\__init__.py", line 923, in error > apply(self._log, (ERROR, msg, args), kwargs) > File "C:\Python23\lib\logging\__init__.py", line 994, in _log > self.handle(record) > File "C:\Python23\lib\logging\__init__.py", line 1004, in handle > self.callHandlers(record) > File "C:\Python23\lib\logging\__init__.py", line 1037, in callHandlers > hdlr.handle(record) > File "C:\Python23\lib\logging\__init__.py", line 592, in handle > self.emit(record) > File "C:\Python23\lib\logging\handlers.py", line 105, in emit > self.doRollover() > File "C:\Python23\lib\logging\handlers.py", line 90, in doRollover > os.rename(self.baseFilename, dfn) > OSError: [Errno 13] Permission denied Works here. Consider switching to an OS where you can rename an open file... Well, you read my discalimer :-) Peter From FBatista at uniFON.com.ar Tue Nov 4 13:11:25 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 4 Nov 2003 15:11:25 -0300 Subject: prePEP: Decimal data type Message-ID: mwilson at the-wire.com wrote: #- I admit that the implementation I'm playing with doesn't #- implement __div__ or __truediv__ yet .. because I can't #- figure out the right way. That's the coolness of taking and implementing an well established standard, ;) . Facundo From donn at drizzle.com Fri Nov 21 20:49:30 2003 From: donn at drizzle.com (Donn Cave) Date: Sat, 22 Nov 2003 01:49:30 -0000 Subject: cooler piping References: <1069377379.729708@yasure> Message-ID: <1069465768.698018@yasure> Quoth Csaba Henk : ... | Only if documentation didn't suck... The Library Reference doesn't mention | anything about the type of the cmd argument of the popen functions, and | after I saw the function working with a cmd of type string, I automatically | assumed that it can be nothing else but a string. (And I don't blame myself | for this...) Well, you will see a lot of it in Python, functions whose arguments may be of various types. Not polymorphic, because we're not talking about any semantic overlap between the types - this is more like overloading. I personally feel that it's a sloppy practice that leads to confusion and errors, but I've done it myself, so at least you and I can use this example as a reminder of what not to do. Donn Cave, donn at drizzle.com From mcfletch at rogers.com Tue Nov 11 10:21:29 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 11 Nov 2003 10:21:29 -0500 Subject: Conversion of 24bit binary to int In-Reply-To: References: Message-ID: <3FB0FE79.5020706@rogers.com> If I'm understanding correctly, hex has nothing to do with this and the data is really binary, so what you're looking for is probably: >>> data = '\000\001\002' >>> temp = struct.unpack( '>I', '\000'+data ) # pad to 4-byte unsigned big-endian integer format >>> print temp # is now a regular python integer (in a tuple) (258L,) >>> print repr(struct.pack( ' Is there an effecient/fast way in python to convert binary data from > file (24bit hex(int) big endian) to 32bit int (little endian)? Have > seen struct.unpack, but I am unsure how and what Python has to offer. > Idar ... _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From steve at ninereeds.fsnet.co.uk Sun Nov 2 19:15:24 2003 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Mon, 03 Nov 2003 00:15:24 +0000 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> <2259b0e2.0311012219.73aa445f@posting.google.com> <2259b0e2.0311021016.496105ea@posting.google.com> Message-ID: On 2 Nov 2003 10:16:20 -0800, mis6 at pitt.edu (Michele Simionato) wrote: >Stephen Horne wrote in message news:... >> OK - but if you are describing superfluidity as a single macroscopic >> effect then you must describe it within a macroscopic framework. At >> which point it has nothing to do with quantum effects because it isn't >> within a quantum framework - it is just that the macroscopic >> phenomenon called electricity (distinct from electrons moving en >> masse) is not subject to the macroscopic phenomenon called resistance >> (distinct from energy loss through the electomagnetic interactions >> between electrons and atoms en masse) when the macroscopic phenomenon >> called temperature (distinct from the kinetic energy of atoms en >> masse) is sufficiently low. >> >> There is nothing wrong with this per se - it is the limit of most >> peoples (mine included) understanding of superconductivity - but it >> has nothing to do with the framework of quantum mechanics. >> > >I am sure I am misreading you again, but the equation is not >microscopic=quantum, macroscopic=classical. It can be very >well quantum=macroscopic. For instance, there is no classical >theory able to describe superfluidity, it must be quantum. >If I am misreading you again, let's say that I am doing this >remark for the other readers here ;) > > Michele But within a framework you don't explain the effects described in that framework - at best you quantify them. e.g. Newton did not give an explanation for how gravity works - he just quantified it. If you want to explain the classical concept of gravity, you need to look at some other model that predicts it - e.g. gravity is created by gravitons (an old quantum theory which IIRC has been abandoned) or gravity is space-time curvature (a relativistic theory). If you are describing superconductivity as a single effect (rather than explaining it in terms of quantum effects working en masse) then it is certainly a macroscopic effect (you can look at it), but basically in that framework you are saying 'this is how it is, get used to it'. This is the same as giving a formula for electrical resistance rather than explaining it in terms of the many interactions of electrons and atoms within the wire. The formula belongs in the macroscopic framework. I'm not saying a single quantum effect cannot be macroscopic, but superconductivity is explained by the way that electrons interact with atoms at low temperature - it is only a single effect in itself in a macroscopic framework where you say "here is how it is, get used to it". If you are explaining how superconductivity arises, then it arises out of microscopic quantum effects acting en masse. However, now that I think harder, I just countered myself in a way. There isn't just one QM framework exactly - there are layers within that too (e.g. quarks relative to protons) so a macroscopic quantum effect can be explained in terms of a microscopic quantum effect and so on. It really depends on whether you call superconductivity a quantum effect even though you aren't looking at simple interactions between quanta. Maybe my definition of 'quantum' is odd, in other words, taking a principle too strictly and ignoring normal conventions. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From Padraig at Linux.ie Tue Nov 25 10:59:29 2003 From: Padraig at Linux.ie (Padraig at Linux.ie) Date: Tue, 25 Nov 2003 15:59:29 +0000 Subject: sleep() function, perhaps. In-Reply-To: References: Message-ID: <3FC37C61.1000209@Linux.ie> Ryan Spencer wrote: > Hello Everyone, > > I want to have a row of periods, separated by small, say, .5 second > intervals between each other. Thus, for example, making it have the > appearance of a progress "bar". You've got the answer for dots, here's a spinner in case it's useful: import sys, time spinner="|/-\\" pos=0 while 1: sys.stdout.write("\r"+spinner[pos]) sys.stdout.flush() time.sleep(.5) pos+=1 pos%=4 From aleax at aleax.it Tue Nov 11 11:09:44 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 11 Nov 2003 16:09:44 GMT Subject: I have a question?? References: Message-ID: Ryan Silverwood wrote: > I want to write a python program which will calculate a person's net > annual income after tax, given the following rules: *The first 1500 is tax > free *any amount earned over ?1500 and upto ?35000 is taxed at 30% > *and amount earned over ?35000 is taxed at 45% It's interesting that somebody else asked _exactly_ this question, numbers and all, on Sunday. Starting to look like some teacher (in the UK, pehraps, given the mention of points) has given a Python assignment, maybe...? Alex From trentm at ActiveState.com Wed Nov 12 12:55:44 2003 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 12 Nov 2003 09:55:44 -0800 Subject: Problem with loading win32com.client in ActivePython 2.3.2 In-Reply-To: ; from shiloh@rvglug.org on Wed, Nov 12, 2003 at 08:03:50AM -0800 References: Message-ID: <20031112095544.G7679@ActiveState.com> [Justin Stockton wrote] > I recently upgraded from ActivePython 2.2.2 to ActivePython 2.3.2 and > I'm running into an issue importing the win32com.client module. Justin, You are right, I see this as well. And the problem is not because you used a space in your install path. I have opened a bug for this problem and will be looking at it very soon: http://bugs.activestate.com/ActivePython/show_bug.cgi?id=28173 Feel free to add yourself to the CC list for this bug to get an update when it is fixed. Note that you are using Build 231 which I haven't actually announced yet ;). Build 231 upgraded ActivePython's included PyWin32/win32all to its latest build and obviously I have not sorted out all the issues there yet. If you do not depend on having the very latest PyWin32, you may have more luck with the previous ActivePython 2.3.2 build (Build 230) which you can find here: ftp://ftp.activestate.com/ActivePython/windows/2.3/ActivePython-2.3.2-230-win32-ix86.msi > Now the part that weirds me out, is that even though import > win32com.client throws an error, I can do the following. > > >>> from win32com import client > >>> Actually, that is just a side-effect of the "win32com" module being _partially_ imported. Python will not try again the second time around. If you start a new shell and then run that again: from win32com import client you will get the same error. http://aspn.activestate.com/ASPN/docs/ActivePython/2.3.2/faq/programming.html#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen Cheers, Trent -- Trent Mick TrentM at ActiveState.com From greg.invalid at capra.us.invalid Thu Nov 13 15:15:39 2003 From: greg.invalid at capra.us.invalid (Greg Krohn) Date: Thu, 13 Nov 2003 20:15:39 GMT Subject: checking for ASCII character In-Reply-To: References: Message-ID: Daniel wrote: > Hi, is there a way to check if a letter entered is an uppercase ASCII > character? > > Thanks > > Daniel If you just want to know if a character is uppercase: if character.isupper(): If it needs to be ASCII, the simplest way is probably: if ord(character) in range(65, 91): greg From newsgroups at jhrothjr.com Sat Nov 1 15:51:18 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 1 Nov 2003 15:51:18 -0500 Subject: prePEP: Decimal data type References: <3cd884n4.fsf@yahoo.co.uk> Message-ID: "Alex Martelli" wrote in message news:fHTob.394884$R32.13090937 at news2.tin.it... > John Roth wrote: > ... > > I decided to snip the prior piece rather than argue about your > > misconception of what I intended. This would have been obvious > > if you had left the context of my comment in, rather than starting > > it out with my response to something invisible to the reader. > > I prefer to trim posts from such generally irrelevant history, > but if you think "This would have been obvious" here is ALL you > had to say in your first post in response to the point, which > you quoted in full, about what operators should apply to decimals: > > """ > > 12. To support the basic aritmetic (``+, -, *, /, //, **, %, divmod``) and > > comparison (``==, !=, <, >, <=, >=, cmp``) operators in the following > > cases: > > > > - Decimal op Decimal > > - Decimal op otherType > > - otherType op Decimal > > - Decimal op= Decimal > > - Decimal op= otherType > > > > Check `Items In Discussion`_ to see what types could OtherType be, and > > what happens in each case. > > > > > 13. To support unary operators (``-, +, abs``). > > OK. > """ > > Now try to argue _with a straight face_ that, quoting this part entirely, it > "would have been obvious" that you wanted to abrogate the applicability of > normal division operators to decimals, and therefore did not need as your > cherished "unbounded precision decimal" a full rational number in some > form. Pah. > > Assuming that's what you intended in that post, I think you made a huge > mistake in NOT saying so, rather just placing a meek "OK" there, and are > now trying to imply that instead of your huge mistake there were some > "misconception" (or as you said earlier, even LESS defensibly!, > "preconceptions" [!!!]) on MY part. In my view of the world, it's all > right to make a mistake (we're humans), but it's NOT ok to try to attack > others rather than admitting and apologizing for one's mistake. Alex, this whole pissing match started because *YOU* assumed, without any justification that I could see, that I was suggesting that we use rational numbers. You devoted several paragraphs in what I took to be a highly patronizing explanation of things I know very well, and in any case had no intention of getting into in the context of this pre-pep. I have attempted to set this straight in the next post on the other chain of this thread. You're the one that made the blunder. You're the one that owes me the appology. John Roth > > > Alex > From adalke at mindspring.com Tue Nov 18 02:03:41 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 18 Nov 2003 07:03:41 GMT Subject: syntax philosophy References: Message-ID: Tuang: > But I'm surprised at what you apparently have to go through to do > something as common as counting the frequency of elements in a > collection. For example, counting word frequency in a file in Perl > means looping over all the words with the following line: ... > This seems sort of unPythonesque to me, given the relative cleanliness > and obviousness (after seeing it once) of other common Python > constructs. > > But I guess I'm making assumptions about what Python's philosophy > really is. I see several replies already, but they don't seem to address your question about the philosophical reasons for this choice. A Python philosophy is that "Errors should never pass silently." (To see some of the other points, 'import this' from the Python prompt.) When you reference '$histogram{$word}++' in Perl it automatically creates the hash 'histogram' and creates an entry for $word with the value of 0 (I think; it may set it to undef or ""). This is great, as long as you don't make mistakes. But people do make mistakes and misspell variables. Had you written '$histrogram{$word}' then Perl would have simply created a new hash for you with that name. This is enough of a problem in Perl that it's recommended you 'use strict' and declare the hash beforehand, as 'my %histogram'. Python takes this approach by default, so there's no need for the 'use strict' declaration. Python also doesn't have the sigil-based typing of Perl so you need to tell it what object to create, hence the need for 'histogram={}'. Similarly, dictionaries require that entries be created before they can be used. This is because it's impossible for Python to know which value you want for the default. Python is strongly typed, so "2"+1 will raise an exception, unlike Perl where it yields the number 3. If Python used a 0 for the default then what if you really wanted to concatenate strings? If it used "" then what if you wanted to add numbers? Whatever choice you make, it will be wrong for most cases. It works in Perl because of Perl's weak type system -- or permissive coercion system if you want to look at it that way -- and corresponding 'typed' operators, so that + and . coerce to numbers or strings, respectively. I've also found that the requirement that the key exists before being used catches mistakes similar to the requirement that variables exist before being used. If you want, you can make a class which acts like a perl hash, and assigns a default value or lets you redefine what to use for that default. Here's a start (similar in result but different in approach to Peter Otten's example) import UserDict class PerlDict(UserDict.DictMixin): def __init__(self, default = 0): self.data = {} self.default = default def __getitem__(self, key): try: return self.data[key] except KeyError: self.data[key] = self.default return self.default def __setitem__(self, key, item): self.data[key] = item def __delitem__(self, key): try: del self.data[key] except KeyError: pass But even with this you won't save much code. Here's what it looks like: histogram = PerlDict() for line in open(filename): for word in line.split(): histogram[word] += 1 Compare that to the canonical Python implementation histogram = {} for line in open(filename): for word in line.split(): histogram[word] = histogram.get(word, 0) + 1 As several people pointed out, for this example you should consider using a histogram/counter class, which would separate intent from the actual calculation, as in histogram = Histogram() for line in open(filename): for word in line.split(): histogram.count(word) Your reply is that you're looking for the philosophy behind Python, using the histogram as an example. That actually is part of the philosophy -- in Python it's much easier to make a class and instantiate an object with the appropriate behaviours than it is in Perl, what with Perl's "bless" and shift and @ISA. The above 'Histogram' is simply class Histogram: def __init__(self): self.histogram = {} def count(self, word): self.histogram[word] = self.histogram.get(word, 0) + 1 In Perl the equivalent would be something like (and only roughly like -- I never did fully figure out how do to Perl OO correctly) package Histogram; sub new { my ($class, $obj) = @_; bless $class, $obj; $obj -> {'histogram'} = {}; return $obj; } sub count { my ($class, $obj, $word) = @_; $obj -> {'histogram'}{$word}++; } However, for a one-off histogram this level of abstraction isn't worthwhile. To summarize, Python's philosophical differences from Perl for your example are: - variables must be declared before use (reduces errors) - dict entries must be declared before use (reduces errors) - dict entries cannot have a default value (strong typing) - classes are easy to create (letting you create objects which better fit your domain) Andrew dalke at dalkescientific.com From deets_noospaam at web.de Sun Nov 30 19:14:44 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Mon, 01 Dec 2003 01:14:44 +0100 Subject: how to show a bitmap? References: Message-ID: > I have a two dimentional array (by Numeric Python) available, and it > represent a grayscaled bitmap picture. How to display it? Thank you! You can use pygame. Diez From gerrit at nl.linux.org Tue Nov 18 13:22:10 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 18 Nov 2003 19:22:10 +0100 Subject: Too much builtins (was Re: Python's simplicity philosophy In-Reply-To: References: Message-ID: <20031118182210.GA6850@nl.linux.org> Andrew Dalke wrote: > str(obj, [base=10]) -> converts integer objects (only!) to the given base, > defaults to base 10. Well, str could be defined as follows: def str(obj, **kwargs): return obj.__str__(**kwargs) That doesn't feel too wrong to me. yours, Gerrit. -- 39. He may, however, assign a field, garden, or house which he has bought, and holds as property, to his wife or daughter or give it for debt. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From jdhunter at ace.bsd.uchicago.edu Sat Nov 15 19:11:51 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sat, 15 Nov 2003 18:11:51 -0600 Subject: Matlab, GUIs and Cygwin In-Reply-To: ("Jay Eichelberger"'s message of "Sat, 15 Nov 2003 19:31:02 GMT") References: Message-ID: >>>>> "Jay" == Jay Eichelberger writes: Jay> Greetings. I am using Python under Cygwin. I'm trying to do Jay> some statistical charts. The Matlab looked likely, but it Jay> uses GTK. matplotlib *used* to require GTK, but not since version 0.2. Note however, that matplotlib with GTK runs great under windows and is an easy install. See the Win32 Quickstart Guide at http://matplotlib.sourceforge.net/installing.html. Also, Jeremy O'Donoghue has implemented the matplotlib wx backend, so you can also use it with wxpython on windows or linux. There is a development version of the wx backend in the current matplotlib-0.32 version on the sourceforge site, which isn't complete but is working pretty well. I expect there will be a complete implementation of the wx backend in about 2 weeks. Just out of curiosity: I use python on win32 a lot and prefer to either use the python.org win installer or the enthought edition of python for windows (which has wx as well as a number of other goodies preinstalled). Is there a reason you need to be using cygwin for your python stuff? Cheers, John Hunter From ods at strana.ru Wed Nov 19 04:50:57 2003 From: ods at strana.ru (Denis S. Otkidach) Date: Wed, 19 Nov 2003 12:50:57 +0300 (MSK) Subject: PEP263 and execfile() In-Reply-To: Message-ID: On 18 Nov 2003, Martin v. [iso-8859-15] L?wis wrote: MvL> > But is there solution possible without modification of MvL> > all those files I do execfile() on? MvL> MvL> Yes, call warnings.filterwarnings() before calling MvL> execfile(). What about warnings.filtererrors() in future versions of Python when this warning will be turned into error? I guess it's OK as temporal hack but it's not a solution of the problem. May be execfile and compile functions should have optional encoding parameter? I'm not sure about execfile, but compile must have it. -- Denis S. Otkidach http://www.python.ru/ [ru] From fpetermaas at netscape.net Tue Nov 18 08:50:35 2003 From: fpetermaas at netscape.net (Peter Maas) Date: Tue, 18 Nov 2003 14:50:35 +0100 Subject: OO design, Python, and GUIs In-Reply-To: <0bc1371b047abbb6ab299bf1c1f167ae@news.teranews.com> References: <0bc1371b047abbb6ab299bf1c1f167ae@news.teranews.com> Message-ID: Christopher Culver schrieb: > I'm creating a home-library management program with Python 2.2, PyGTK, and > Glade. While I've been many little programs before, this is my first large > application in Python. My question is how I should organise the OO design > of such a program. There should be, I gather, a core class "MainClass", > which coordinates everything, other specialised classes which report to > MainClass, and the GUI should ideally be in its own class "GuiClass". There is a start up module that will talk to you first, I'd call it homelib.py. It does the necessary initialisations like loading the GUI resources, opening the database etc. If you want to encapsulate this in a class you could call it main or start. I wouldn't give the feature providing classes generic names like "main". They do something special, so I would give them names that tell something about their resonsibilities, e.g. library, libraryItem, book, magazine, storage, editView, listView etc. Aggregate related classes in a module, related modules in a package (if you have lots of modules). The feature modules would be imported by the start up module. It wouldn't be bad to have a rough plan of your software before you start to write code. The building blocks (packages, modules) of your app have "uses" relations. If module a uses b then a has to import b. A layered approach would probably be helpful: u | startup, user interface t |------------------------------- i | engine (provides the features) l |------------------------------- s | storage (file, db, network) Each layer uses its neighbour below, all layers use utils. The layers could be distributed across several programs (multi-tiered app) but that's not necessary, of course. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From fredrik at pythonware.com Mon Nov 3 18:12:15 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 4 Nov 2003 00:12:15 +0100 Subject: tar interface References: Message-ID: David Bear wrote: > I just googled for a 'python tar interface module' and got over 33000 > hits. ug. you're supposed to use import, not google: $ python Python 2.3.2 >>> import tarfile >>> help(tarfile) Help on module tarfile: NAME tarfile - Read from and write to tar format archives. FILE c:\python23\lib\tarfile.py CLASSES exceptions.Exception TarError CompressionError ExtractError ReadError StreamError TarFileCompat TarIter __builtin__.object ExFileObject TarFile TarInfo if you have an earlier Python version, see this page: http://www.gustaebel.de/lars/tarfile/ From daniel.dittmar at sap.com Thu Nov 27 09:38:42 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 27 Nov 2003 15:38:42 +0100 Subject: SAP DB and Python References: <490316A24CC5D411ACD700B0D078F7F003915C7C@cseexch01.cse.creoscitex.com><3FC5FCC9.1040908@geochemsource.com> Message-ID: Gandalf wrote: > >>> from sapdb import dbapi > >>> dbapi.connect > > >>> conn = dbapi.connect('dba','dba','Demo') > > Traceback (most recent call last): > File "D:\Python\Projects\Test\test.py", line 2, in ? > conn = dbapi.connect('dba','dba','Demo') > File "D:\Python23\lib\sapdb\dbapi.py", line 102, in __init__ > database, host, configString) > File "D:\Python23\lib\sapdb\dbapi.py", line 60, in wrapCall > raise ProgrammingError (err) > sapdb.dbapi.ProgrammingError: sql.SQLError: [-8000] (at 1) Message not > available Username and password are case sensitive, where as other tools like dbmcli map them to uppercase unless quoted. So conn = dbapi.connect('DBA','DBA','Demo') should work Daniel -- Daniel Dittmar SAP Labs Berlin daniel.dittmar at sap.com From gerryandsharon at sympatico.ca Sat Nov 22 18:01:41 2003 From: gerryandsharon at sympatico.ca (Gerry Sutton) Date: Sat, 22 Nov 2003 18:01:41 -0500 Subject: Using Python to add scripting to Hyperterminal? Message-ID: Is it possible to automate and script the windows Hyperterminal utility with Python? From aahz at pythoncraft.com Sun Nov 9 03:02:21 2003 From: aahz at pythoncraft.com (Aahz) Date: 9 Nov 2003 03:02:21 -0500 Subject: prePEP: Decimal data type References: Message-ID: In article , Mel Wilson wrote: >In article , >"John Roth" wrote: >> >>My personal opinion in the matter is that setting the precision >>high enough so that you won't get into trouble is a hack, and it's >>a dangerous hack because the amount of precision needed isn't >>directly related to the data you're processing; it's something that >>came out of an analysis, probably by someone else under some other >>circumstances. Given a software implementation, there's a performance >>advantage to setting it as low as possible, which immediately puts >>things at risk if your data changes. > > It puzzles me. In the COBOL days, we used to worry over setting the >sizes of our data fields large enough. We'd set a size we thought was >ridiculously large and then worry whether today would be the day that >the company would do the unprecedented amount of business that would >blow up the night-shift batch runs. We escaped from that with Python's >long ints and now we're trying to invent it again. Division is the fly in the ointment, unfortunately. The other operations lead to unbounded-but-finite number sets; division leads to infinite size unless truncated or rounded. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From http Wed Nov 19 13:21:38 2003 From: http (Paul Rubin) Date: 19 Nov 2003 10:21:38 -0800 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <7xad6sb7cd.fsf@ruckus.brouhaha.com> Message-ID: <7xvfpg6wy5.fsf@ruckus.brouhaha.com> Robin Becker writes: > You're probably right, but given that the code itself has to unobfuscate > to make use of the data then any key/algorithm etc has to be present > somewhere. The idea of cryptography now is to keep the data secure as long as the key is secret. It's ok if the algorithm is known. If the key is known too, all bets are off. > How should we obfuscate? Using a crypto function just increases the time > and effort that someone needs to get the plain text. If you can keep the key secret and the cryptography is any good, there should be no way for anyone to break the cryptography without the key. Rotor fails in that criterion. > Likewise using a C > extension makes it harder for the casual thief. The professional won't > be bothered. I think you're underestimating the technical ability and determination of amateurs on the internet. Look at all the virus writers out there--who is paying them? Almost every day Microsoft has to release a new critical security patch because of some weakness that got exploited by a non-professional and caused users a lot of hassle. The exploit usually isn't some technical breakthrough on the attacker's part, but rather stems from an attitude problem at Microsoft, that their products only have to be secure enough to make it "harder for the casual thief" since "the professional won't be bothered". That is precisely the wrong attitude to have, as we see every time Microsoft announces that "as of today security is our #1 priority" and then goes back to doing the same dumb stuff, and a few days later, yet another virus brings everyone's work to a halt yet another time. If you're going to use cryptography at all, use it as well as you can. > The rotor module was small and speedy. In my case I'm sure that it makes > very little difference to use base64 and a xor or something similar. Using base64 or an xor should be even smaller and speedier than rotor, so if that's your goal, the answer is still "use xor and get rid of rotor". The only reason to use rotor instead of xor is you think xor isn't secure enough. But if xor isn't secure enough, you should use real cryptography, not rotor. > When we really want data to be protected we're using one time passwords > assigned by a special server. If you really want data to be protected I hope whatever methods you're using were designed or at least reviewed by someone who knows what they're doing. That's not intended as a put-down toward you; there are a lot of mistakes that get made over and over again, and it takes some knowledge and experience to recognize them and not make them. Using something like rotor is very frequently an example of such a mistake. From pellis.nospam at tampabay.rr.com Tue Nov 11 00:07:22 2003 From: pellis.nospam at tampabay.rr.com (Patrick Ellis) Date: Tue, 11 Nov 2003 05:07:22 GMT Subject: What do you think of this Python logo? References: <3FB00D3B.2BCE081A@engcorp.com> Message-ID: "Sean Ross" wrote in message news:boppcl$2gr$1 at driftwood.ccs.carleton.ca... > > "Brandon J. Van Every" wrote: > > > > > > What do you think of this Python logo? > > > http://pythonology.org/logos > > > Good, bad, indifferent, love it, hate it? > > > I don't mind the snake, but I would lose the planet ("Python is taking over > the world!" ... ahem ... right ... ok, then ...), and perhaps add eyes, so > it looks less like sperm. > > Anyway. If I could draw, I would probably try to make the snake in the shape > of the letter "P" - something like this > http://chat.carleton.ca/~sross/py.JPG (only not drawn with a mouse in > MSPAINT, like this was :). Kind of a cross between "GAP" and the Portishead > logo - um, but with a snake. Slick it up a bit and it might make a good > T-Shirt ... or, not ... > > The logo at python.com (yeah, _that_ python.com) with the green, bared-fang > snake, and the electrified "Powered by Python" is pretty cool (though not > really corporate, which is what it looks like you're after). Too bad it's on > a porn site ... All the logos seem to be purely snake oriented. There is nothing about the Monty kind of Python. I don't think a snake with a silly walk would work as a logo. Maybe a snake with a napkin on its head? Patrick Ellis From eppstein at ics.uci.edu Fri Nov 14 12:57:34 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 14 Nov 2003 09:57:34 -0800 Subject: Python's simplicity philosophy References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <8hfsb.7707$nz.895@newsread2.news.pas.earthlink.net> <9s8tb.22141$9_.810000@news1.tin.it> Message-ID: In article <9s8tb.22141$9_.810000 at news1.tin.it>, Alex Martelli wrote: > > How's that? I've never used a programming language that has sum() in > > it. (Or at least not that I was aware of.) In fact, the *Python* I > > use doesn't even have sum() in it! I've used a number of languages > > Never used a modern Fortran? Or never bothered to _learn_ it properly > "because it's a language for peasants"?-) For that matter, Haskell, the third thing I get from googling "functional programming language", has had sum since it was first created (version 1.0 report 1990), despite its being easily replaceable with reduce (or I guess in Haskell terms foldl). -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From tim at worthy.demon.co.uk Tue Nov 25 07:58:43 2003 From: tim at worthy.demon.co.uk (Tim Howarth) Date: Tue, 25 Nov 2003 12:58:43 GMT Subject: win32com (VBScript to Python) problem References: Message-ID: <7473e5564c.tim@worthy.demon.co.uk> In message "Michel Claveau" wrote: > import win32com.client > WMIService = > win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate,(Shutdo > wn)}!\\CPU01\root\cimv2") > > objs = WMIService.ExecQuery(r"Select * from Win32_OperatingSystem") > for obj in objs: > obj.Reboot() This gives me the same error 'int' is not callable. Maybe it's something to do with late/early binding ?? What version of Python/win32all have you used this on ? -- ___ |im ---- ARM Powered ---- From gherron at islandtraining.com Fri Nov 21 18:27:57 2003 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 21 Nov 2003 15:27:57 -0800 Subject: python regular expression In-Reply-To: References: Message-ID: <200311211527.57839.gherron@islandtraining.com> On Friday 21 November 2003 03:03 pm, eddieNOSPAM at eddiecentral.net wrote: > I am trying to edit a bunch of files that are similar. I want to remove all > the ASP code that appears before the tag. Can some one help me with > a regex that can replace everything before the tag with nothing? You don't need a regular expression for that. Just find the index of the first occurrence of and slice away. i = data.find('') # i=-1 means not found if (i != -1) data = data[i:] Gary Herron From a_bogdan_marinescu at yahoo.com Fri Nov 14 05:05:39 2003 From: a_bogdan_marinescu at yahoo.com (a_bogdan_marinescu) Date: Fri, 14 Nov 2003 10:05:39 -0000 Subject: Strange Python COM behaviour Message-ID: Hello all, I'm trying to do some COM automation from Python (using Mark Hammond's Win32 extensions, of course) and I'm getting some very strange errors. Specifically, I try to use a COM object that supports events, and I'm instantiating it like this: eventobj = win32com.client.DispatchWithEvents( crtthread, DebuggerThreadEvents ) When I try to do this, I get the following error: ... File "d:\work\scripts\automation\autobuild.py", line 106, in execute_one_file eventobj = win32com.client.DispatchWithEvents( crtthread, DebuggerThreadEvents ) File "C:\Python23\lib\site-packages\win32com\client\__init__.py", line 264, in DispatchWithEvents result_class = new.classobj("COMEventClass", (disp_class, events_class, user_event_class), {"__setattr__" : _event_setattr_}) TypeError: str() takes at most 1 argument (3 given) It seems that events_class's type is str ( as returned by getevents() function in __init__.py file from win32com/Client directory) instead of 'classobj' as it is supposed to be. event_class is actually a simple string showing a CLSID. I'm new to COM and I can't understand why this is happening. Please help me if you can. Regards, Bogdan Marinescu From gh at ghaering.de Wed Nov 12 08:12:01 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 12 Nov 2003 14:12:01 +0100 Subject: guten tag In-Reply-To: References: Message-ID: <3FB231A1.3040009@ghaering.de> Necati Agirbas wrote: > Betreff: SCHULBESCHEINGUNG F?r Frau DERYA AGIRBAS, [...] I just informed the sender that (s)he apparently sent this to the wrong email address. I might have a strange humour, but I found it quite funny to find such a misposted letter to a German school in this list. -- Gerhard From tim.one at comcast.net Tue Nov 25 14:17:46 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 25 Nov 2003 14:17:46 -0500 Subject: looking for 2.1.3 Windows binary with large file support In-Reply-To: Message-ID: [Mathew] > the version that is distributed with Zope/Plone does not handle large > files. Sorry, no version of Python 2.1 exists that supports large files on Windows. Adding support for that required substantial Windows-specific changes to the Python core, and 2.2.3 is the first Python version in which Windows largefile support was essentially complete (2.2 had most of it in place, but a few things were missing, like file.truncate(integer_bigger_than_2_gig)). Note that Zope 2.7 and Zope3 are skipping the 2.2 line -- they'll both require 2.3.2+. From max at alcyone.com Thu Nov 20 17:17:19 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 20 Nov 2003 14:17:19 -0800 Subject: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com> <3FBC2025.B2A33B6F@alcyone.com> <87d6bncbaj.fsf@einstein.electron.net> Message-ID: <3FBD3D6F.E4068821@alcyone.com> Curt wrote: > curty at einstein:~$ less uniq.txt > flirty > curty > flirty > curty > > curty at einstein:~$ uniq uniq.txt > flirty > curty > flirty > curty > > curty at einstein:~$ sort uniq.txt | uniq > curty > flirty > > Maybe my uniq is unique. No, that's expected behavior, and consistent with what I said. uniq doesn't really care whether its input is sorted, it just takes consecutive sequences of identical lines (identically by the criteria you specify on the command line) and collapses them into at most one. In your sample, there were no consecutive lines that were identical, so uniq did nothing. Change the order of them, and despite still being non-sorted, you'll see that uniq is working: max at oxygen:~/tmp% cat > uniq.txt flirty curty curty flirty ^D max at oxygen:~/tmp% uniq uniq.txt flirty curty flirty The duplicate consecutive "curty" lines got collapsed into one. > NAME > uniq - remove duplicate lines from a sorted file > ****** That's true that's in the one-line description of uniq on some systems, such as GNU, since that's the most common usage. But if you look at the description of what it actually does, you'll see its behavior doesn't require sorted input: DESCRIPTION Discard all but one of successive identical lines from INPUT (or standard input), writing to OUTPUT (or standard output). And on some systems, the summary doesn't mention sorting at all; Solaris 8, for instance: NAME uniq - report or filter out repeated lines in a file and sort is only mentioned in the "SEE ALSO" section, nowhere in the main descpription. For an example where uniq would be useful despite the input deliberately not being sorted, consider processing a log file with a lot of duplicate entries, and you only want to see the first of each series of consecutive duplicates. (This is actually not unheard of; syslog for instance will do this automatically.) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ Extremes meet. -- John Hall Wheelock From Raaijmakers, Vincent (IndSys, Mon Nov 10 11:43:35 2003 From: Raaijmakers, Vincent (IndSys, (Raaijmakers, Vincent (IndSys,) Date: Mon, 10 Nov 2003 10:43:35 -0600 Subject: web guru advise needed. Message-ID: <971323274247EB44B9A01D0A3B424C8502FCFEB1@FTWMLVEM02.e2k.ad.ge.com> Looking at all the materials available, books, technologies etc etc.. I try to make a decision on what technology to select for a web server design, but I need help. I know, this question has been asked many many times sorry about that, but please help me. My desk is full with printouts and books, I'm getting a stack overflow. Currently the existing design is using JSP's. Now, most of the business logic of behind this application is database and image processing driven. This part of the code is in a design phase, not coding. Looking at the design, python would be very powerful. I'm afraid that java will kill the performance + development time here. But how to make the link between my JSP and python business logic. Jython is still at the python 2.1 level. Looking at the libraries, the use of Python 2.3 seems for me more a must. The web server requirements I'm looking at are: 1) simple presentation layer processing. The HTML pages produced by server will be more focused on presenting images (dynamic), rather that fancy tables, frames, buttons. 2) the framework has to be robust and FAST on performance. 3) runs only on Linux, well not really a requirement, more a statement. 4) runs on Apache (and/or Tomcat) What technology gives me the best performance? I'm so afraid that adapters like WebKit kills my performance but because of my jsp experience, psp seems the best option. Vincent From aleax at aleax.it Mon Nov 10 12:00:20 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 10 Nov 2003 17:00:20 GMT Subject: Am I the only one who would love these extentions? - Python 3.0 proposals (long) References: <7xznf4jhi3.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I've been thinking for a while that Python could benefit from a fork, > that's not intended to replace Python for production use for any group > of users, but rather to be a testbed for improvements and extensions > that would allow more concrete experiments than can be done through > pure thought and the PEP process. Most proposals for Python > improvements could then be implemented and tried out in the > experimental platform before being folded back into the regular > implementation. That's one of the benefits that the pypy project is intended to provide: a "reference implementation" that's easiest to play with for exactly such purposes as the experiments you mention. And -- we do hope to release pypy 1.0 before Christmas...! Alex From jzgoda at gazeta.usun.pl Sun Nov 23 13:56:29 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 23 Nov 2003 18:56:29 +0000 (UTC) Subject: ConfigParser lower-cases options automatically? References: Message-ID: Matthew Wilson pisze: > I wonder if this is something intentionally built-in to ConfigParser in > order to remove case-sensitivity issues that are variable across > platforms. Does anyone else have any comments or ideas? I don't need > case-sensitivity in my script, but I am puzzled by this behavior. Yes, I think it was intentional. Check optionxform() in Python documentation to get an idea how to make ConfigParser case sensitive. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From peter at engcorp.com Mon Nov 3 11:27:49 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Nov 2003 11:27:49 -0500 Subject: programming languages (etc) "web popularity" fun References: <3d06fae9.0310310915.4447d4ca@posting.google.com> <9Zzob.75517$e5.2773519@news1.tin.it> <2531b4fb3a153253e29f8a74f733aef1@news.teranews.com> Message-ID: <3FA68205.636ED781@engcorp.com> Dang Griffith wrote: > > On Sat, 01 Nov 2003 00:53:17 -0000, claird at lairds.com (Cameron Laird) > wrote: > > >Note, too, that the Python one hasn't been on the street > >as long as some of the others. It's reasonable to specu- > >late that the ratios haven't equilibrated yet. > > Not sure I understand your comment. > Python predates Java. > --dang I'm sure Cameron is quite aware of that, and yet your comment does nothing to invalidate his statement. Surely you can accept that "Python hasn't been on the street as long as *some* of the others" (emphasis added), can't you? -Peter From maoy at cis.upenn.edu Sun Nov 9 00:11:20 2003 From: maoy at cis.upenn.edu (Yun Mao) Date: Sun, 9 Nov 2003 00:11:20 -0500 Subject: how to read in an array in text file? Message-ID: Hi, what's the easy way of reading in a two-dimentional array from a text file? The text file looks like this: 0.1 1.1 2.3 12.1 0.3 33.0 4.1 1.1 I'm using Numeric Python now. Other solutions are also welcome. Thanks a lot! Yun From bkelley at wi.mit.edu Mon Nov 24 15:36:02 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Mon, 24 Nov 2003 15:36:02 -0500 Subject: small, fast and cross-platform flat-file database for python In-Reply-To: References: Message-ID: <3FC26BB2.6090800@wi.mit.edu> Tim Churches wrote: > Brian Kelley wrote: > >>I have successfully used metakit in a fairly large application and >>couldn't be happier with the results. The best thing about metakit is > > >>that you can view millions of records in a nice view with ease: > > > Really millions of records? The metakit documentation warns that its > efficiency starts to decline dramatically above about 250,000 records, > and in testing I found that was true, and at 1 million records it became > really slow. > It depends upon what types of operations you are performing of course. I have stored 1.5 million molecules in a metakit database taking up about 1 gigabyte. Each compound has a variable number of data fields. Each compound has a unique id which helps *a lot*. One of metakit's flaws, though, is that it doesn't really know if a given id is unique when it is doing internal selects and joins. If the table size is "to large" I always do joins on the unique keys in pure python first. That is, I use a python dictionary to pre-filter the necessary rows and then recombine them. If you are doing a more complicated select operation and joining to an additional table, then things may slow down quite a bit. In the mysql layer, this can happen during calls to view.product which is usually used for selections like: I) select a,b from view1, view2 where view1.a > view2.b and view1.c < view2.d My applications generally do selections like: II) select a,b from view1, view2 where view1.id = view2.id and view1.a > 20 and view2.b > 100.0 Which is very fast since I don't have the join explosion. What metakit is really good for is very fast scans through columns. If you can organize your logic such that columns take precedence over rows (i.e. II versus I) then metakit is very powerful even for many, many, records. Another trick is to occasionally save the database to a new file, this optimizes internal space and the like: storage.write(open(newfile, 'wb')) At least, this has been my experience ;) If your queries are more like I, I would suggest PySQLLite http://pysqlite.sourceforge.net/ although > Tim C Brian. From python-url at phaseit.net Mon Nov 10 04:45:55 2003 From: python-url at phaseit.net (Emile van Sebille) Date: Mon, 10 Nov 2003 09:45:55 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Nov 10) Message-ID: QOTW: "A good rule of thumb is: The less non-python stuff you have around, the better. Non-python parts of any given system are invariably the ones causing most of the problems :-)." --Ville Vainio "The Language Reference [http://www.python.org/doc/current/ref/ref.html] is very readable, not excessively formal, and well worth a read." -- alan kennedy Will Stuyvesant asks how to protect his software from prying eyes when offering trial versions of commercial software. http://groups.google.com/groups?threadm=cb035744.0311030035.2ffb5e06 at posting.google.com ActiveState no longer includes PyPPM, a utility for managing Python extension modules, from current releases of ActivePython, and now plans to come up with a good next-generation system that leverages PyPI and distutils. Feedback solicited. http://aspn.activestate.com/ASPN/Mail/Message/ActivePython/1872769 Thomas Heller releases py2exe 0.5 for python 2.3. py2exe is a distutils extension to convert python scripts into executable windows programs. http://groups.google.com/groups?selm=he1f521c.fsf at python.net Kevin Oliver replies to Stefano with EClass, a cross-platform, open source software toolkit for authoring, managing and delivering e-learning via computer or the Internet http://groups.google.com/groups?threadm=rq3lqvkkjv0vu6n10m78plandaa7e7dm16%404ax.com Fernando asks for an advanced OOP tutorial and gets links to both. http://groups.google.com/groups?threadm=a26792eb.0311041033.7e6be3cb at posting.google.com Guido van Rossum will present the principles and some examples of the newer features of Python at the BayPIGgies user group meeting at Stanford on Thursday. http://groups.google.com/groups?selm=bo1p4h$mhl$1 at agate.berkeley.edu The folks at Secret Labs AB now offer the Daily URL as an RSS feed. http://www.pythonware.com/daily/index.htm#106828618203975811 Edward K. Ream releases Leo 4.1 beta 1, an outlining editor for programmers written in and scriptable with Python. This is the first official release of the reorganized 4.1 code base http://groups.google.com/groups?threadm=vqnfid3a3h3b78 at corp.supernews.com Yield creates a generator and proves a critical distinction in the answer to this puzzler observed by Gerson Kurz. http://groups.google.com/groups?threadm=3fa808c3.20995000 at news.t-online.de John Hunter is looking for a data structure to identify the closest neighbor in 2D to new points as they are added to the structure. Brute force works, but is there something better? http://groups.google.com/groups?threadm=mailman.356.1067832883.702.python-list at python.org Jim Bublitz announces the latest release of PyKDE (3.8.0), which includes the ability to write KDE panel applets completely in Python, http://groups.google.com/groups?threadm=z9Fqb.5262$AB5.1534510124 at twister1.starband.net Anthony Baxter announces the release of SpamBayes version 1.0a7. http://groups.google.com/groups?selm=mailman.1068041583.8786.clpa-moderators at python.org Fredrik Lundh releases PythonDoc 2.0 final, a documentation tool for Python inspired by JavaDoc. http://groups.google.com/groups?selm=mailman.1068304442.32337.clpa-moderators at python.org Jack Jansen releases the second build of the MacPython additions for Panther. This second build allows you to install the full Python documentation, and fixes an IDE startup problem http://homepages.cwi.nl/~jack/macpython/ Marco Seiri=F6 announces ruleCore 1.0beta6, an event-driven reactive rule engine with GUI tools based on ideas from the research done on active rules called Event-Condition-Action (ECA) rules. http://groups.google.com/groups?selm=438a319a.0311091143.256db982 at posting.google.com ======================================================================== 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 newly-revitalized newsgroup at least 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 The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ 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. *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 bignose-hates-spam at and-benfinney-does-too.id.au Fri Nov 14 07:28:38 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 14 Nov 2003 23:18:38 +1050 Subject: Overriding variables used by base classes References: Message-ID: On 14 Nov 2003 04:17:58 -0800, Corey Lubin wrote: > from original import * > someGlobal=2 Your use of "global" and "from foo import *" belie an approach counter to encapsulation and modularity. What is it you're trying to achieve? -- \ "You know I could rent you out as a decoy for duck hunters?" | `\ -- Groucho Marx | _o__) | Ben Finney From __peter__ at web.de Thu Nov 20 17:54:24 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 Nov 2003 23:54:24 +0100 Subject: time.mktime memory access violation bug References: Message-ID: Bengt Richter wrote: > What does the following sequence do on your machine? Your tests did not > apparently exercise the daylight savings time path involved in my crash. My (tacit, sorry) assumption was that setting daylight savings to 1 would subtract 3600s from the Unix epoch, making it a negative value and thus provoke the crash. But that was wrong: >>> def d(t): ... tpl = time.localtime(t) ... return time.mktime(tpl[:-3] + (0, 0, 0)) - time.mktime(tpl[:-3] + (0, 0, 1)) ... >>> d(0) 0.0 With an arbitrary summer time: >>> d(962924461) 3600.0 >>> > E.g., > > >>> import time > >>> time.localtime(0) > (1969, 12, 31, 16, 0, 0, 2, 365, 0) > >>> time.mktime(time.localtime(0)) > 0.0 > >>> time.mktime(time.localtime(0)[:6]+(0,0,1)) > > (my NT4 crashes here) > For completeness: >>> time.localtime(0) (1970, 1, 1, 1, 0, 0, 3, 1, 0) >>> time.mktime(time.localtime(0)) 0.0 >>> time.mktime(time.localtime(0)[:6] + (0, 0, 1)) 0.0 >>> >From the docs I would expect that such a "smart" behaviour would require a DST flag of -1. Looking at the two zero times (UTC + x vs UTC - x hours) I wonder if an NT machine on this side of the zero meridian would encounter the same problems. Peter From noemail at noemail4u.com Mon Nov 3 11:14:34 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Mon, 03 Nov 2003 16:14:34 GMT Subject: programming languages (etc) "web popularity" fun References: Message-ID: <1b0569eff1ff540df7b1bf4ad2d5da1f@news.teranews.com> On Fri, 31 Oct 2003 11:30:47 GMT, Alex Martelli wrote: >(You need Mark Pilgrim's pygoogle, see >http://diveintomark.org/projects/pygoogle/ , and a personal license to the >google api, see http://www.google.com/apis/ , saved in a file such as >"googlekey.txt" in your home directory [pygoogle looks in several places, >see http://diveintomark.org/projects/pygoogle/readme.txt for the list). > > >googling sure _IS_ plenty of fun!!!-) > > >Alex Any chance of seeing PowerBuilder in the list? --dang From cpgray at library.uwaterloo.ca Wed Nov 19 09:29:12 2003 From: cpgray at library.uwaterloo.ca (Chris Gray) Date: Wed, 19 Nov 2003 09:29:12 -0500 Subject: Looking for an http proxy server written in Python In-Reply-To: <7x4qx14hr4.fsf@ruckus.brouhaha.com> References: <7x4qx14hr4.fsf@ruckus.brouhaha.com> Message-ID: On Tue, 18 Nov 2003, it was written: > > I sometimes use Amit Patel's proxy3 for web surfing, but I don't know > if I'd call it production quality because it's so slow. I don't know > if anything can be done about that, because Python itself is pretty > slow. You may need to bite the bullet and use Squid or the Apache > proxy module or something like that. I've had reasonable success > hacking various html rewriting features into the Apache module when > such things were needed. I may have a look at Squid and mod_proxy (and Jigsaw to boot) at some point. I'm not as worried about speed as I am about choking on requests that can't be handled. I'm not trying to do the processing in real time; that is, the results of the processing don't have to be available to the client in real time. Thanks for the feedback, Chris From __peter__ at web.de Mon Nov 24 14:23:07 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Nov 2003 20:23:07 +0100 Subject: os.walk help References: <3FBEAF80.5020802@hotmail.com> <3FC0F2B2.5030201@hotmail.com> Message-ID: Robin Munn wrote: > hokiegal99 wrote: >> Thanks for the tip. That code shows all of the dirs that Python is >> complaining about not in the list... trouble is, they *are* in the list. >> Go figure. I'd like to try doing the rename outside the scope of >> os.walk, but I don't undersdtand how to do this, when I break out of >> os.walk and try the rename at a parallel level, Python complains that >> variables such as "oldpath" and "newpath" are undefined. > > Wait, I just realized that you're changing the list *while* you're > iterating over it. That's a bad idea. See the warning at the bottom of > this page in the language reference: Here's a way to modify the list while iterating over it. Too lazy to generate the sample directory tree, so I suggest that the OP test it :-) def clean_names(rootpath): bad = re.compile(r'%2f|%25|%20|[*?<>/\|\\]') for root, dirs, files in os.walk(rootpath): for index, dname in enumerate(dirs): newdname = bad.sub('-', dname) if newdname != dname: newpath = os.path.join(root, newdname) oldpath = os.path.join(root, dname) try: os.rename(oldpath, newpath) except OSError: print >> sys.stderr, "cannot rename %r to %r" % (oldpath, newpath) else: dirs[index] = newdname # inform os.walk() about the new name Peter From adalke at mindspring.com Mon Nov 17 13:11:23 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 17 Nov 2003 18:11:23 GMT Subject: Books I'd like to see References: <2259b0e2.0311132223.11af146a@posting.google.com> Message-ID: Alex: > I'm familiar with Ruby's claims, but, as methods/functions aren't really > first-class objects there, I don't necessarily buy into them. The claim, as I understand it, is that the method notation qwerty.abc(1,2,3); sends the 'abc' message to 'qwerty', and they don't go along with Python's approach that 'qwerty.abc' gets the method 'abc'. Instead, they say there's another way to ask for the method object, theMethod = qwerty.method("abc") theMethod.call(1,2,3) What makes that not a first class object? Andrew dalke at dalkescientific.com From james.kew at btinternet.com Mon Nov 3 18:12:17 2003 From: james.kew at btinternet.com (James Kew) Date: Mon, 3 Nov 2003 23:12:17 -0000 Subject: Does python always need to compile ENTIRE program before it can start to run it??? References: Message-ID: "John Roth" wrote in message news:vqdamhn2pq1qaf at news.supernews.com... > I've never > gotten a satisfactory explanation of why it doesn't save the compiled > version of the top level script, but then, I've never really looked > into it. It's just curious. I've always wondered that too. The top-level script _might_ be standard input or command-line, but it seems to me that it often (usually?) is a .py which _could_ be stashed into a .pyc. Taken to extremes, it suggests that top-level scripts should be as small as possible: an if __name__ == "__main__" delegating immediately to a worker function imported from a helper module. I'm not sure there's anything realistic that's code-heavy and short-running enough for it to make much difference, though... James From tuanglen at hotmail.com Mon Nov 24 15:55:10 2003 From: tuanglen at hotmail.com (Tuang) Date: 24 Nov 2003 12:55:10 -0800 Subject: Parsing strings -> numbers Message-ID: I've been looking all over in the docs, but I can't figure out how you're *supposed* to parse formatted strings into numbers (and other data types, for that matter) in Python. In C#, you can say int.Parse(myString) and it will turn a string like "-12,345" into a proper int. It works for all sorts of data types with all sorts of formats, and you can pass it locale parameters to tell it, for example, to parse a German "12.345,67" into 12345.67. Java does this, too. (Integer.parseInt(myStr), IIRC). What's the equivalent in Python? And if the only problem is comma thousand-separators (e.g., "12,345.67"), is there a higher-performance way to convert that into the number 12345.67 than using Python's formal parsers? Thanks. From t-meyer at ihug.co.nz Fri Nov 28 00:53:48 2003 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 28 Nov 2003 18:53:48 +1300 Subject: [OT] Spambays question In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F13043158BD@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F130212B1A7@its-xchg4.massey.ac.nz> > This is a litle bit out of topic, but i suppose that a lot of > python users, use the spanbays spam filter. As well as the spambayes mailing list already mentioned, you might want to try the spambayes website , FAQ , and wiki . > I must admit it works great, after a month testing with it, > it made no errors and catch 100% of spam. The only (litle) > problem I see is that it puts all spam in a spam folder. I > think, that now i'm confident with it, it would be great if > you could simple delete automaticly the spam without putting > it in a spam folder. > > Perhaps somebody managed to do that ? FAQ 3.9 has your answer: . (This assumes you are using the Outlook plug-in - if not, then just alter whatever rule you created in your mail client). =Tony Meyer From nav+posts at bandersnatch.org Thu Nov 20 09:45:39 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 20 Nov 2003 09:45:39 -0500 Subject: GIL risky for threading and networking? (was Re: good book on multithreaded programming with Python) References: <3FBB9FD9.62D62FD@engcorp.com> Message-ID: Peter Hansen writes: > Is this a case of fear arising out of ignorance? Most probably. On the other hand, I probably wouldn't have spoken up if I hadn't seen the post I replied to. I am planning on as pure Python an approach as possible, and have been from the start. I certainly wasn't trying to borrow trouble from the future or optimize too early in development. > If you have specific reasons for the concern, please provide them so > we can address them. This is the attitude that makes me tell my boss(es) that I get better support from the open source community than I ever could from a commercial outfit. Thanks! > The GIL certainly doesn't get in the way of > soft real-time work in any way that's significant. I'm going to proceed with that expectation, thanks again. 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 pythonguy at Hotpop.com Fri Nov 14 06:24:45 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 14 Nov 2003 03:24:45 -0800 Subject: Books I'd like to see References: Message-ID: <84fc4588.0311140324.70886bf4@posting.google.com> You forgot the following. 1. Wesley Chun ( or is it Alex Chun ?) Core Python Programming 2. David Mertz Text Processing in Python. I would like to see a general book on "Software development using Python", which will discuss the practitioner's approach to developing software using python, by one of the established methods. May be this can be taken up as a joint project by one of the python gurus say Alex or David, and one of those Software Engineering/Methodology gurus like Martin Fowler or Bruce Eckel. Just my $0.02. -Anand Bryan wrote in message news:... > Nick Vargish wrote: > > I would like to see "wxPython Programming" from Grayson, John E. > > > > His book on tkinter is pretty darn good, but I'm much more interested > > in wxWindows. I find the need to look up the C++ wxWindows > > documentation and do a translation to the Python equivalent really > > gets in my way of learning how to use the widgets properly. > > > > Nick > > > > i 2nd this > > bryan From sombDELETE at pobox.ru Sat Nov 29 17:35:35 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sun, 30 Nov 2003 01:35:35 +0300 Subject: sorting dictionary keys? References: <3fc91af5$0$28610$636a55ce@news.free.fr> Message-ID: > > Which is one of the main PITA in Python IMHO :( > (not the fact that it sort in place, the fact that it does not return self). > def sort(lst): lst.sort() return lst -- Serge From lex at cc.gatech.edu Sat Nov 1 16:29:27 2003 From: lex at cc.gatech.edu (Lex Spoon) Date: Sat, 01 Nov 2003 16:29:27 -0500 Subject: Python from Wise Guy's Viewpoint References: <3F9D5D21.2060408@ps.uni-sb.de> <20031027184024.GO1454@mapcar.org> <20031028093713.GQ1454@mapcar.org> <20031029085604.GU1454@mapcar.org> Message-ID: >>>It sounds unbelievable, but it really works. >> I believe you. I have trouble swallowing claims like `It is never >> wrong, always completes, and the resulting code never has a run-time >> error.' or `You will never need to run the kind of code it doesn't allow.' > > This kind of claim comes is usually just a misunderstanding. > For example, the above claim indeed holds for HM typing - for the > right definitions of "never wrong" and "never has an error". > > HM typing "is never wrong and never has a run-time error" in the > following sense: the algorithm will never allow an ill-typed program > to pass, and there will never be a type error at run-time. However, > people tend to overlook the "type" bit in the "type error" term, at > which point the discussion quickly degenerates into discourses of > general correctness. It is misleading to make this claim without a lot of qualification. It requires careful, technical definitions of "type" and "type error" that are different from what an unprepared audience will expect. For example, it is not considered a type error if you get the wrong branch of a datatype. So if you define: datatype sexp = Atom of string | Cons of (sexp, sexp) fun car (Cons (a,b)) = a then the following would not be considered a "type error" : car (Atom "hello") To add to the situation, HM flags extra errors, too, that many people would not consider "type errors" but which are for HM's purposes. For example, it is considered a type error if two branches of an "if" do not match, even if one branch is impossible or if the later code can remember which branch was followed. For example: val myint : int = if true then 0 else "hello" or more interestingly: val (tag, thingie) = if (whatever) then (0, 1) else (1, 1.0) val myotherstuff = if tag = 0 then (tofloat thingie) + 1.5 else thingie + 1.5 In common parlance, as opposed to the formal definitions of "type error", HM both overlooks some type errors and adds some others. It is extremely misleading to claim, in a non-technical discussion, that HM rejects precisely those programs that have a type error. The statement is actually false if you use the expected meanings of "type error" and "type". All this said, I agree that HM type inference is a beautiful thing and that it has significant benefits. But the benefit of removing type errors is a red herring--both in practice and, as described in this post, in theory as well. -Lex From jjl at pobox.com Mon Nov 3 17:20:10 2003 From: jjl at pobox.com (John J. Lee) Date: 03 Nov 2003 22:20:10 +0000 Subject: Selling Python Software References: <8765i1d2jb.fsf@pobox.com> <3FA6BCF4.9BC51DF@alcyone.com> <3FA6BFF2.5238729B@engcorp.com> Message-ID: <87d6c99js5.fsf@pobox.com> Peter Hansen writes: > Erik Max Francis wrote: [...] > I think Quicken is one of the few programs I've seen lately which seems > to remain somewhat intact. (I'm quite sure I'll hear otherwise now, but > so far I haven't seen rampant copying.) The basic technique used there > is online registration, which I assume decrypts and/or enables certain > critical portions of the code after server verification of credentials, > and prevents repeat registrations using the same CD. Maybe that's a > good new baseline for such protection. In the end, that's just as vulnerable to hacking as anything else to a determined binary-attacker (which as you point out, do exist for consumer apps). John From aleax at aleax.it Tue Nov 4 11:07:10 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 04 Nov 2003 16:07:10 GMT Subject: Function Name Resolution Problem References: Message-ID: Haoyu Zhang wrote: > Dear Freinds, > I am learning Python throught the book "Learning Python" published > by O'Reilly. In its 4.6.2, the author gave an example about incorrect ... > However, when I tested it in my python, it works correctly. So is > it because the standard changes? Or any other reasons? The version > in our university's server is 2.2.1. "Learning Python" is describing Python 1.5.2 -- back then, things did indeed work as the book says. Many years have passed since, and a second edition of "Learning Python" (updated to 2.2 at least, perhaps with some notes on the tiny additions of 2.3 wrt 2.2) will be out in December (latest estimate -- they're WAY late wrt the earlier estimates, which were to be several months ago). Alex From __peter__ at web.de Thu Nov 13 04:27:17 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Nov 2003 10:27:17 +0100 Subject: Try, except...retry? References: Message-ID: Robert Brewer wrote: > I just got there, Alex. :) However, it got me thinking. I keep running > into cases like: > > try: > aPiranha = allPiranhas['Doug'] > except KeyError: > aPiranha = Pirhana() > allPiranhas['Doug'] = aPiranha > aPiranha.weapon = u'satire' > > which would, in my opinion, be better written (i.e. *clearer*) as: > > try: > allPiranhas['Doug'].weapon = u'satire' > except KeyError: > allPiranhas['Doug'] = Pirhana() > retry > retry does remind me of VBA's on error goto ... resume [next] a little too much. You lose track of the actual program flow too fast. To me, the first variant appears much clearer in that it has only code in the try clause that is actually supposed to fail. Also, in try: setWeapon("Doug", u"satire") except KeyError: allPiranhas["Doug"] = Goldfish() retry where would you want to jump? Should setWeapon() be executed in a way similar to generators, saving its state in case of an exception instead of a yield? Sometimes you can *not* execute a statement twice in a reliable manner. Peter From dietrich at zdome.net Wed Nov 19 21:02:42 2003 From: dietrich at zdome.net (Dietrich Epp) Date: Wed, 19 Nov 2003 18:02:42 -0800 Subject: Reading a Bitstream In-Reply-To: References: <653b7547.0311181810.786118af@posting.google.com> Message-ID: On Nov 19, 2003, at 7:02 PM, Bengt Richter wrote: [snip] > Maybe this will do something for you? > Note that this is a response to your post, and not something > previously tested, > (in fact not tested beyond what you see ;-) and it will be slow if you > have > huge amounts of data to process. > > You pass a string to the constructor, specifying big-endian if not > little-endian, > and then you use the read method to read bit fields, which may > optionally have > their most significant bits interpreted as sign bits. > > E.g., reading 4-bit chunks or bits, little-endian and big-endian: [snip] It looks like what I did before I started using struct.unpack. I think I'll stick with my current code, which, although it looks like ugly C code, works. Someday I'll probably get the itch again and make a decent module out of it. From jjl at pobox.com Tue Nov 18 06:56:37 2003 From: jjl at pobox.com (John J. Lee) Date: 18 Nov 2003 11:56:37 +0000 Subject: Origin of the term "first-class object" References: <8ef9bea6.0311171335.356a7af6@posting.google.com> <3FB947AF.F4F942BE@alcyone.com> Message-ID: <87llqdvqiy.fsf@pobox.com> Erik Max Francis writes: > Hung Jung Lu wrote: > > > Does anybody know where this term comes from? > > > > "First-class object" means "something passable as an argument in a > > function call", but I fail to see the connection with "object class" > > or with "first-class airplane ticket". > > It doesn't have any connection with the former (since the term long > predates object orientation, so far as I know). It does have a > connection to the latter, in that something going first class has all > the privileges and properties owed to it as a complete and total thing. [...] Ben is closer to the mark in terms of etymology, I think -- though maybe "first-class citizen" in turn derives from "first-class ticket"? John From SEE_AT_THE_END at hotmail.com Fri Nov 7 20:51:13 2003 From: SEE_AT_THE_END at hotmail.com (Georgy Pruss) Date: Sat, 08 Nov 2003 01:51:13 GMT Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> Message-ID: "Alex Martelli" wrote in message news:SwQqb.108165$e5.3904529 at news1.tin.it... > Georgy Pruss wrote: > > > seq=[1,3,4,7] > > map( int.__sub__, seq[1:], seq[:-1] ) # nearly twice faster than > > ....zip.... for long arrays > > If this is a race, then let's measure things properly and consider > a few more alternatives, shall we...? :) No, it's not a race. I just found the map expression to be clear and elegant. Fortunatelly, one of the fastest solutions too. G-: > > [alex at lancelot xine-lib-1-rc2]$ python a.py > reduce: 100 loops, best of 3: 13.8 msec per loop > zip: 100 loops, best of 3: 18 msec per loop > izip: 100 loops, best of 3: 7.6 msec per loop > w2: 100 loops, best of 3: 7.1 msec per loop > wib: 100 loops, best of 3: 12.7 msec per loop > loop: 100 loops, best of 3: 8.9 msec per loop > map: 100 loops, best of 3: 7.6 msec per loop > > itertools.w2 is an experimental addition to itertools which I > doubt I'll be allowed to put in (gaining less than 10% wrt the > more general izip is hardly worth a new itertool, sigh). But, > apart from that, map and izip are head to head, and the plain > good old Python-coded loop is next best...! reduce is slowest. > > My code...: > <...> > > Alex > From duncan at NOSPAMrcp.co.uk Thu Nov 27 04:41:21 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 27 Nov 2003 09:41:21 +0000 (UTC) Subject: Is there a .tolower() for a string?? References: <7b1fa3cb.0311261057.ecb7325@posting.google.com> Message-ID: Wojtek Walczak wrote in news:bq345v$97s$1 at nemesis.news.tpi.pl: > Dnia 26 Nov 2003 10:57:32 -0800, Amy napisa?(a): > [...] >> Isn't there a built in method for changing a string to lowercase? > >>>> print ''.lower.__doc__ > S.lower() -> string > > Return a copy of the string S converted to lowercase. > > > Read the docs! Also, you could have said 'learn to use the help command, its more convenient than printing __doc__': > >>>> help("".lower) >Help on built-in function lower: > >lower(...) > S.lower() -> string > > Return a copy of the string S converted to lowercase. > Another command the OP might have found useful would be help(""), or help(str) which tell you all about the string methods. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From tim at worthy.demon.co.uk Tue Nov 25 06:38:53 2003 From: tim at worthy.demon.co.uk (Tim Howarth) Date: Tue, 25 Nov 2003 11:38:53 GMT Subject: win32com (VBScript to Python) problem References: Message-ID: <6e24de564c.tim@worthy.demon.co.uk> In message "Rony Steelandt" wrote: > Not knowing exactly what you want to do, just a question. > > Why use COM, shutdown is an exe so why not just execute it? Using this method you can shutdown and poweroff (the 12 value) a machine, shutdown.exe from the reskit leaves a machine at "You may now switch off". I want to use this to shutdown all machines in the school in which I work from a schedule on a server. I could use the VBscript version but there are long delays if a machine is switched off - in Python I can thread the communication with individual machines (to achieve this in VBScript I have to call a new instance of w(c)script for each machine), effectively shutting them down in parallel. -- ___ |im ---- ARM Powered ---- From pclinch at internet-glue.co.uk Fri Nov 7 11:00:56 2003 From: pclinch at internet-glue.co.uk (Paul Clinch) Date: 7 Nov 2003 08:00:56 -0800 Subject: Request for simple a customisable Python editor References: Message-ID: <8cf2994e.0311070800.1f07f9c8@posting.google.com> stephenlee at exe-coll.ac.uk wrote in message news:... > I want to develop a simple Python program to edit source code that is > persisted in a database (memo fields). > The code to be edited is iHTML and SQL and I want syntax colouring and good > basic features including tabs for multiple 'files' and searching. > It will be a Win32 deployment. > A quick check of the python package index (www.python.org/pypi) reveals PyPE (http://pype.sourceforge.net/) an editor written in python with wxwindows. Also the CUTE User-friendly Text Editor is a scintilla and QT based code editor, which can be extented using the python scripting language. The project page of CUTE is http://cute.sourceforge.net. pyscinitilla provides an interface to the popular scintilla code editor at http://wingide.com/opensource/pyscintilla . Regards, Paul Clinch From tarball at phreaker.foo Mon Nov 3 18:48:18 2003 From: tarball at phreaker.foo (Thomas F.B.) Date: Tue, 04 Nov 2003 00:48:18 +0100 Subject: Forcing import of sitecustomize.py References: Message-ID: On Tue, 04 Nov 2003 10:00:09 +1300, Jamie wrote: > > I'm deploying a python application packaged as an executable with py2exe. > I'm forcing the import of sitecustomize.py to set the default encoding... > "Don't do this!" (MHO) I used sitecustomize.py, too. But after having nothing but trouble with 3rd party modules, py2exe, McMillan Installer etc. etc. I decided to write my applications in such a way that they do not depend on a specific default encoding. (E.g. things which worked with one version of py2exe etc. did not work with the next version etc.) My opinion: sitecustomize.py is fine for small python scripts which you use on your own system (admin scripts, daily work etc.). It allows you to program without caring about encodings and stuff (i.e. to be lazy :-) But for applications which you want to deploy, I would not recommend to make use of or to rely on the default encoding set in sitecustomize.py. Thomas -- mailto: tarball at phreaker.foo (foo = net) From __peter__ at web.de Sat Nov 15 15:33:49 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 15 Nov 2003 21:33:49 +0100 Subject: getopt References: Message-ID: Don Low wrote: > I'm going over a script that demonstrates the getopt function. I include > the script here: I you are only now exploring the possibilities of getopt, you might want to leapfrog and use the more powerful optparse module. > options, xarguments = getopt.getopt(sys.argv[1:], 'ha', \ > ['file=', 'view=', 'version', 'python-version']) If you want the "a" option to require an argument, you have to append a colon serving the same purpose as the "=" for long options: options, xarguments = getopt.getopt(sys.argv[1:], 'ha:', \ ['file=', 'view=', 'version', 'python-version']) Peter From claird at lairds.com Sun Nov 30 11:54:26 2003 From: claird at lairds.com (Cameron Laird) Date: Sun, 30 Nov 2003 16:54:26 -0000 Subject: Tkinter question References: <3FC79B0B.B9ED8894@mdstud.chalmers.se> Message-ID: In article , Logan wrote: >On Fri, 28 Nov 2003 19:59:23 +0100, Ali El Dada wrote: > >> i am using Tkinter in my application, and i have a button >> that, when clicked, opens a new window as in: >> >> b1 = Button(someframe, text="bla", command = someFunction) >> >> def someFunction(): >> newWindow = Toplevel() >> '''the new window widgets go here''' >> >> of course, whenever the button is clicked, a new window >> opens. what do you recommend as a neat way to allow only one >> window to open?? > >It depends on what kind of behavior you want: if newWindow is e.g. >a dialog (like 'find', 'find & replace' etc. in an editor), you >want the new window to pop up, but any older dialog should get >destroyed. > >To achieve this, you can make newWindow a *global variable* and >use e.g. the following (not very elegant, but it works): > ># here, the 'find'-dialog is created (e.g. inside some class) > try: > newWindow.destroy() > except: > pass > > newWindow = Toplevel() > # widgets for the 'find'-dialog > ># here, the 'find&replace'-dialog is created (e.g. inside some class) > try: > newWindow.destroy() > except: > pass > > newWindow = Toplevel() > # widgets for the 'find&replace'-dialog > > >If you want, that your window gets created only once (and whenever >such a window is already open, no new window should be created) you >could either use an approach similar to the one above (i.e. with >newWindow being a global variable) or e.g. use a class which >keeps track on how many instances of itself were already created >and which behaves accordingly (Google: python, singleton). > >There are other solutions, too. The 'right' solution for you >depends mainly on the design of your whole program (OO or not etc.). . . . It's quite common with some toolkits--Tkinter among them--to re-use widgets. The body of a program just uses widgets as needed, and little initializers or constructors or helpers take care of creating (or sometimes deiconify- ing) the widgets as needed. They aren't destroyed, in general, although they might oc- casionally be iconified or withdrawn or unmanaged or such. -- Cameron Laird Business: http://www.Phaseit.net From jkrepsBEAR at FISHneb.rr.com Wed Nov 5 19:14:41 2003 From: jkrepsBEAR at FISHneb.rr.com (GrayGeek) Date: Wed, 05 Nov 2003 18:14:41 -0600 Subject: import cx_Oracle References: <3fa32966$0$1118$6c56d894@feed0.news.be.easynet.net> Message-ID: <7lgqb.119692$%C5.21026@twister.rdc-kc.rr.com> Andy Todd wrote: > GrayGeek wrote: >> Waldemar Osuch wrote: >> >> >>>GrayGeek wrote in message >>>news:... >>> >>>>Andy Todd wrote: >>>> >>>> >>>>>GrayGeek wrote: >>>>> >>>>> >>>>>>Uwe Hoffmann wrote: >>>>>> >>>>>> >>>>>> >>>>>>>GrayGeek wrote: >>>>>>> >>>>>>> >>>>>>>>Bernard Delm?e wrote: >>>>>>>> >>>>>>>> >>>>>>>> >>>>>>>> >>>>>>>>>>It gives me an error about being unable to find the OCISetDefault >>>>>>>>>>entry point in 'oci.dll'. >>>>>>>>> >>>>>>>>>cx_Oracle works on top of the regular oracle client, which you'll >>>>>>>>>need to install before it works. The OCI libraries are >>>>>>>>>parOCISetDefault t of that. >>>>>>>> >>>>>>>> >>>>>>>>I have it installed, and have used it to create webpages using >>>>>>>>Oracle's HTP.P function, and I also accessed tables on the Oracle9 >>>>>>>>server from JDev9 >>>>>>>>and from PLSQLDeveloper. The oci.dll is in the Oracle Home/dll >>>>>>>>directory. As my first post indicated, cx_Oracle is able to see >>>>>>>>oci.dll, it just can't communicate with it properly. >>>>>>>>??? >>>>>>> >>>>>>> i think that the binaries were built against another version of >>>>>>> oracle. i had a similar problem with DCOracle2 (versions 8.0.5 vs. >>>>>>> 8.1.7 or >>>>>>>7.3.3 vs. 8.0.5). >>>>>>> As far as i remember OCISetDefault was one of the problematic >>>>>>> symbols. >>>>>> >>>>>> >>>>>>I'm hoping that we can switch from Java to Python but since we are >>>>>>standardizing on Oracle having a reliable Python connection to Oracle >>>>>>9i is >>>>>>important. mmm... Maybe I can use PostgreSQL for a proof of >>>>>>concept... >>>>> >>>>>Is $ORACLE_HOME/bin on your path? This is how cx_Oracle picks up the >>>>>oci.dll. Its not necessary for the Oracle toolks like JDeveloper and >>>>>SQL*Plus, but its essential for third party tools. >>>> >>>>Yes. cx_Oracle has no problem finding oci.dll, it just can find the >>>>right 'entry point'. >>>> >>>> >>>>>You don't mention which version of Oracle you are using. There are >>>>>binaries for either Oracle 8i or 9i with Python 2.2 on the home page >>>>>(http://www.computronix.com/utilities.shtml#Oracle) but they won't work >>>>>with earlier versions of Oracle. Although, with a bit of luck and a >>>>>following wind the 8i binary can be used to access a 9i database (it >>>>>just can't do anything with the new features). But on the whole you >>>>>will be better off getting the appropriate driver for your database >>>>>version. >>>> >>>>I started using Python 2.3 and when I ran into this problem my first >>>>tack was to remove Python 2.3 and revert to Python 2.2, but Python 2.2 >>>>shows the >>>>same problem. We use both Oracle 8i and Oracle 9i. I am attempting to >>>>connect to my Oracle 9i database. I have tried both binaries and the >>>>"import cx_Oracle" dies in both using Python 2.2 against Oracle 9i. >>> >>>I had similar problem once on a machine with two Oracle installations. >>>cx_Oracle was finding oci.dll all right but it was the wrong one. >>>When I found a machine with only one version of Oracle the problem >>>went away. >>>After this hurdle was over I had nothing but positive impressions from >>>using cx_Oracle module. >>> >>>waldemar >> >> >> mmm... the only Oracle onnection on my box is for the 9i database. >> > > So, just to clarify, on your Windows box you now have *only* Python 2.2 > and the Oracle 9i client? I'm presuming also that your database is on > another machine. And you've installed the appropriate cx_Oracle binary? > Works for me; Your assumptions are correct. But, it doesn't work for me. > > PythonWin 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on > win32. Portions Copyright 1994-2001 Mark Hammond > (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further > copyright information. > >>> import cx_Oracle > >>> cx_Oracle.version > '3.1' > >>> db=cx_Oracle.connect('andy/andy at melchett') > >>> cursor=db.cursor() > >>> cursor.execute("SELECT user FROM dual") > [] > >>> print cursor.fetchall() > [('ANDY',)] > >>> > > I also tried it with cx_Oracle version 2.5a, and then on my other > machine with Python 2.3, the 9i client and version 3.0a of cx_Oracle. > > So, my guess is that you are still suffering from a DLL confusion > (somewhere). Probably true, but JDev9 and PSQLDeveloper doesn't have any connection problems. ?? -- - GrayGeek From http Wed Nov 19 14:28:37 2003 From: http (Paul Rubin) Date: 19 Nov 2003 11:28:37 -0800 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <3FBB805D.40A8DA75@engcorp.com> <3FBBA68A.6D819C5C@engcorp.com> Message-ID: <7xhe10w42i.fsf@ruckus.brouhaha.com> "Dave Brueck" writes: > Just as a semi-off-topic followup, rotor-like algorithms still have > some situations that make them more attractive than modern > algorithms. While rotor _is_ much weaker on an "equivalent key size" > basis, its computational simplicity makes it feasible to use > extremely large keys without additional CPU costs, so that you can > end up with a much _higher_ degree of security per CPU cycle spent > in encryption / decryption if there is a way for both sides to agree > on extremely large keys (and there are plenty of ways to do that). But the internal state of the rotor system has fixed size, no matter how long the key is. In the case of the Python rotor module, that size is 10 bytes, though of course there are much better attacks than brute force search. > For example, suppose you and I have a monthly face-to-face meeting, > so we use that as an opportunity to swap CDs of random data. It is > feasible for us to use _the entire CD_ as an encryption key (yay, a > 6 billion bit key!) and, assuming the data is sufficiently random, > there is literally _no_ amount of computing power that can crack a > single intercepted message using a brute force approach (because > cracking part of the key doesn't yield you info on any other part of > the message until you have intercepted messages totalling several > times the length of the key). In that case we can just use the random cd as an additive one-time pad and have no need for rotor algorithms. Note that we won't get any authentication either way. > Obviously you could use the face-to-face meeting to exchange a CD of > AES keys to use, but each intercepted message would, in theory, be > open to a brute force attack, But in fact the likelihood of such an attack is much lower than the likelihood of the CD itself getting intercepted by an attacker. Really, this stuff gets rehashed on sci.crypt almost every week, it gets boring after a while. > But there do exist > situations where you are CPU constrained, so it may be a good > tradeoff for e.g. an embedded device with limited CPU to use a > rotor-like algorithm and its own ROM as the key. There are much better algorithms than rotor even for tiny cpu's. Skipjack, for example, needs only about 3 bytes of scratch ram on an 8-bit cpu while any reasonable rotor cipher needs far more than that. > Also, with rotor errors in the key cause only localized damage in > the data stream, Several of the standard block cipher chaining modes have the same property. > so if the application consuming the decrypted data can recover from > a small error rate, you can use some pretty crazy sources for your > keys: with a little work you could e.g. encrypt live telephone > conversations with the satellite video feed of CNN (with the > telephony application running the feed through a filter to reduce > noise and extract a reliable subset of the feed and then > synchronizing off of, say, the closed caption data). If somebody > knows that you're using that as your key source then they can crack > your message, but otherwise an intercepted message is safe from > brute force attacks. But that's silly, you have to assume that your attacker knows what methods and key sources you're using (Kerchoff principle). If you can't securely exchange a shared secret key beforehand, the solution is to use a public-key key agreement algorithm with locally generated random data at each end, not crazy crap like digitizing a CNN feed. > (I'm not suggesting that we should be using rotor everywhere, just > pointing that it has some cool properties and isn't totally useless > nowadays. :) ) But it really is totally useless nowadays, unless you want an insecure system. From edreamleo at charter.net Mon Nov 10 16:19:00 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Mon, 10 Nov 2003 15:19:00 -0600 Subject: Leo + Python: the ultimate scripting tool: gui issues References: Message-ID: Several responses mentioned gui issues, which have little to do with scripting. However, gui issues are near and dear to my heart, so I thought I would summarize how things stand with Leo and guis: 1. Leo is in the midst of a global reorg that will separate gui-dependent code from a gui-independent "core". This is going well, and will be completed in about a week. This reorg is the basis for the 4.1 code base. 4.1 final is due out in December; there will be a lengthy period of testing (including many new unit tests) while the code settles down. A prototype plugin for Leo already exists that replaces Leo's default Tk/tkinter gui with a wxPython gui. The original version of the prototype had to duplicate a large amount of Leo's core to be even partly functional. With the new code base the wxPython gui only needs to know how to do generic wxPython kinds of stuff. All knowledge of Leo's core is handled by base classes that are in Leo's core. In another reply I misspoke: I said that anygui probably wasn't up to the job. In fact, with the new organization it would be dead easy to create a plugin to support anygui instead of, say, wxPython. Experimenting with anygui would be virtually risk free: it would take an hour or so of time. N.B. Gui plugins are _completely_ responsible for handling all gui-related events. In particular, the interface between Leo's core and gui plugins ignores event handling completely. This greatly simplifies the interface and ensures that no assumptions at all about event handling "infect" Leo's core. I was originally dubious about matching anygui's model of events. Now I see the fear was unfounded. 2. One of my hopes in writing the original series of postings was that there would be some discussion of integrating Leo with Emacs using pymacs. This may have started to happen. I would really like help with this project, and I'll support anyone working on such a project in any way I can. I think running some kind of Leo window on Emacs would be totally cool. 3. Several people have mentioned that it would be good to start up Leo in scripting mode. There are several easy ways to do this. It will happen eventually: don't know when. Right now it seems more like a cute feature than something vital...In any event, there will eventually be a way of running Leo without any gui at all: a null-gui plugin probably could do this with about 10 lines of code. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From gerrit at nl.linux.org Thu Nov 13 14:56:04 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 13 Nov 2003 20:56:04 +0100 Subject: HELLO everybody! In-Reply-To: <003001c3a9c1$92eeed60$35c8c8c8@mcgsdev1.com> References: <003001c3a9c1$92eeed60$35c8c8c8@mcgsdev1.com> Message-ID: <20031113195604.GB5646@nl.linux.org> ?????? wrote: > I am newbie for python. Congratulations on finding Python! You may want to subscribe to the Python Tutor mailinglist: http://mail.python.org/mailman/listinfo/tutor Have you programmed before? If so, you may want to read the online tutorial: http://www.python.org/doc/current/tut/tut.html If not, you may want to buy one of the Python books. The most recent one is minus 3 weeks old and is called "Learning Python, 2nd edition". It will be out in december: http://www.oreilly.com/catalog/lpython2/ yours, Gerrit. -- 1011001 1101111 1110101 1110010 1110011 0101100 1000111 1100101 1110010 1110010 1101001 1110100 -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From peter at javamonkey.com Mon Nov 3 12:05:58 2003 From: peter at javamonkey.com (Peter Seibel) Date: Mon, 03 Nov 2003 17:05:58 GMT Subject: Explanation of macros; Haskell macros References: <87brs2tjut.fsf@memetrics.com> Message-ID: Joachim Durchholz writes: > Peter Seibel wrote: > > > Joachim Durchholz writes: > > > >>Peter Seibel wrote: > >> > >>>Joachim Durchholz writes: > >>> > >>>>And, of course, macros can evaluate at compile time. Personally, I'd > >>>>prefer to do compile-time evaluation based on "the compiler will > >>>>evaluate all known-to-be-constant expressions". The advantage here > >>>>is that programmers don't need to learn another sublanguage for > >>>>compile-time expressions. > >>> > >>>Ah, but in Lisp we don't have to. We use Lisp. > >> > >>Having readers and special forms /is/ an extra sublanguage. I don't > >>have to learn extra syntax for these forms (which is good), but I do > >>have to learn about a lot of special rules that apply to macros and > >>nothing else (which is not so good). > > Hmmmm. The special forms (25 of them, called special operators these > > days, by the by) are used the same in macros and functions. Lisp's > > customizable reader is a separate thing--there is no need to customize > > the reader to write macros. > > You're right, and made me rethink what's actually disturbing me about > macros. > > Perhaps it's that I have to adapt to dual-mode (two-tier?) thinking: > I have to reason about both what the macros are doing and what the > software is doing. Alternatively, I could consider the macros as > "part of the language" and not reason about the macro code but about > their effects - in which case I have effectively augmented the > language by all macros that are in use. I think you're right that you have to adopt a dual-mode of thinking. When you're writing macros you're essentially extending the compiler/language to recognize constructs that would otherwise be meaningless. Then, having written them, you use them as if they were in the language all along. At one level this is no different from extending a language by writing a function. That is, if you're working in a language (like Common Lisp, Scheme, C, or--I imagine--any FPL) where much of the "language" itself is implemented in terms of built-in functions, if you write a new function you're extending the language and after you've written it you can forget about the details of how it works and just use it. The only difference between macros and functions is that macros operate by generating code which then performs actions as opposed to *being* code that performs actions. But that level of indirection makes it easy to express things that would otherwise be difficult (in my experience.) > Personally, I'd still prefer a compiler that's evaluating constant > expression. Hmmm. If it will make you feel any better, macros are just fuctions whose domain and range happens to be Lisp expressions. That happen to be run by the compiler. So eventually the compiler is evaluating constant expressions, just some of them were automatically derived from the written source. > Is there anything that a macro does that can't be done by > preevaluating data structures that contain functions (or closures)? > At first glance, I'd say no, but then I don't know what macros are > used for in practice. Well it depends whether you consider syntax to be "anything". I think it was you who objected to one of my examples by saying, "that's just syntactic sugar". Macros can (and many do) do large amount of under-the-covers bookkeeping. For instance here are a few rules from a grammar for a lexer for Java source code: (defprod line-terminator () (/ #\newline (#\return (? #\newline)))) (defprod white-space () (/ #\space #\tab #\page line-terminator)) (defprod input () ((* input-element) (? #\Sub))) (defprod input-element () (/ white-space comment token)) (defprod token () (/ identifier java-keyword literal separator operator)) DEFPROD is a macro that squirrels away the stuff on the right which is an s-expy form of BNF. The rest of the grammar is more of the same. At the bottom of the grammar file where the productions are diffined I have this form: (deflexer java-lexer (input) ((:tokens identifier java-keyword literal separator operator))) That DEFLEXER call (another macro) expands into a single parsing function built out of all the productions created by DEFPROD calls, appropriately wired together and embedded into code that takes care of the stepping through the input and gather up values, etc. And that function is compiled into extremely efficient code because all the intercommunication between productions goes through lexical variables. And the file containing these calls to DEFPROD and DEFLEXER is legal Lisp source which I can feed to the compiler and get native machine code back. So I don't know if that is "anything" or not. I don't know how I would write such a thing in Haskell, et al. but I know this is a *lot* cleaner than what *I'd* be able to do in Java, Perl, Python, or C. > Um, well, yes, there is one thing that macros can do: extending > syntax in ways that aren't part of the original language syntax. > E.g. replacing all those parentheses by indentation, or something > similar un-Lispish. (Extending syntax in such ways is a mistake > IMHO, but YMMV. Anyway, I'm more interested in the question if > there's any /semantics/ that can be done via macros but not via > compile-time evaluation.) Actually, changing the syntax is--if one thinks one must--is really done by read-macros which are quite different. But most Lispers agree with you--there's just not enough benefit to changing the syntax to be worth it. Except for occasionally making a new syntax for expressing certain frequently created literal objects that otherwise would require a much more verbose creation form. (Someone gave a great example the other day in another thread of an airline reservation system (Orbitz I think) that has a special kind of object used to represent the three-letter airport codes. Since they wanted to always have the same object representing a given airport they needed to intern the objets with the TLA as the key. But rather than writing (intern-airport-code "BOS") everywhere, they wrote a reader macro that let them write: #!BOS. Since this was an incredibly common operation in their system, it was worth a tiny bit of new syntax. But note, again, that's not *changing* the syntax so much as extending it.) > >> Letting the compiler evaluate what it can means that I don't even > >> have to learn extra forms. > > > > I'm not sure what "extra" forms you're talking about. Other than > > DEFMACRO, I guess. But by that argument we'd be better off without > > DEFUN too because that's just another darn thing to learn. > > I believe it's not DEFMACRO that's complicating things, it's the > macros that it allows (see above). Fair enough. But do you object to the ability to write new functions on the grounds that that just means you have a lot of new functions to learn and that complicates things needlessly? That's obviously a rhetorical question but I am actually curious why you find them different, if you do. > >>I just suspect that better solutions are available in every case, > > Interesting. A lot of people suspect that who haven't actually used > > Common Lisp macros. Yet almost all Common Lispers--who by in large are > > *not* monolinguists--think macros are one of Common Lisp's great > > features. I'm not saying your wrong, but if those better solutions are > > out there for all the things I can do with macros, I haven't seen > > them. Now I don't know Haskell or ML so I'm also suffering from finite > > knowledge. Maybe one day I'll have time to learn one of them for > > myself and see if they really do offer better solutions. > > Agreed on all accounts (except that I don't know how "multilingual" > Lispers really are *g*). Well, there is the problem that once folks find Lisp they tend to stop looking for better things because what could be better than Lisp. ;-) But most Lispers take a fairly circuitous path to Lisp and hit a bunch of other languages before they find it. > Does anybody have a keyword-style list of useful applications of the > macro facilities? > > >>and I not just suspect but know that macros have some very serious > >>disadvantages (such as bad debugger interaction, a potential for > >>really ugly hairballs, and a constant temptation for stopgap > >>solutions that "work well enough"). > > Well, of those the debugger interaction is perhaps the most serious. > > Yet in practice (Hey Pascal, I almost said "in 99% of cases"!) > > "99% of all cases" is a pretty good argument actually :-) > It's just that Pascal doesn't (want to) believe that it's enough for > type checking. His problem, not mine... > > > it > > doesn't seem to be that much of a problem. Maybe that's because we've > > just learned to deal with the pain; maybe MACROEXPAND is all you > > really need to get your bearings. At any rate, there's no in principle > > that a Lisp implementation couldn't keep track of macro information > > along with the compiled code just the way most compiler keep track of > > line number information in order to show you the code as written in > > the debugger. (And if it was really slick to let you step through the > > macro expansion, etc.) > > Agreed. I'm getting more and more convinced that it's not language > size or KISS issues that's setting me off, it's that "two-tier > thinking" that I (perhaps mistakenly?) associate with macros. The funny thing is to me, when you say "two-tier thinking" that perfectly describes how I think about the process of making abstractions. Regardless of the *kind* of abstraction one is creating, one has to be facile at switching mental gears between *building* the abstraction and *using* it. You are probably so used to doing this when writing functions that you don't even notice the switch. But because macros are a bit strange you *notice* the switching and it annoys you. I suspect that anyone who's capable of building functional abstractions would--if they actually used macros--quickly learn to switch gears equally smoothly when writing and using macros. > >>Lisp-the-language is a quite pretty lean-and-mean KISS language. The > >>stuff that's built on top of it (macros, readers, dispatch > >>mechanisms, etc. etc.) is neither lean nor KISS nor (IMHO) pretty - > >>YMMV. > > Clearly. I find Common Lisp to be a pretty beautiful piece of > > *engineering*. Which may be different than a beautiful realization of > > a beautiful theory. > > I wouldn't want HM typing if it were just beautiful theory. > HM typing happens to be a beautiful theory. Things are getting less > beautiful once you interact with the Real World (TM), which is > stateful - OTOH, Real World is a mess, so don't expect computing to be > beautiful anymore when there is interaction with it *g*. What > surprised me is how much of a computation can be separated from such > interaction. With the proper framework, one can even describe > interaction patterns (which are themselves stateless), feed these > patterns to the framework, and watch in amazement how the execution > engine follows these patterns. It's the kind of abstractive facility > I've been yearning for decades... > Lisp could do this just as well. It's just not done because taking the > shortcut and doing stateful computations directly is so much easier. > (And I don't pretend that functional languages are doing this kind of > thing perfectly right now. I think the potential in these ideas is > just beginning to be exploited - and what's available is already quite > impressive.) > > >>Or, more to the point: I have yet to see something that cannot be > >>done in a leaner, more KISS way. > > Well, if I promise to continue to think that someday I really should > > learn a hard-core FP language so I can see what all the static typing > > fuss is about, will you promise to think in the back of your mind that > > maybe someday you should learn Common Lisp and see what makes us all > > so gaga over macros. > > Actually I'm trying to understand macros and macro usage right now, > without having to learn all the details of CL (which would be a bit of > overkill - I know it might not be enough, but then my time is limited > so I'm doing my best within the available budget). Sure. Cheers. -Peter -- Peter Seibel peter at javamonkey.com Lisp is the red pill. -- John Fraser, comp.lang.lisp From SBrunning at trisystems.co.uk Mon Nov 17 06:42:28 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Mon, 17 Nov 2003 11:42:28 -0000 Subject: Capturing/Recognizing Text In Another Window Message-ID: <31575A892FF6D1118F5800600846864D01200CE3@intrepid> > From: News M Claveau /Hamster-P [SMTP:essai1 at mci.local] > I obtain a traceback in line 4 : "win32ui : No windows is active." ??? Line 4 of *what*? Does this help?: http://www.brunningonline.net/simon/blog/archives/000664.html If not, try giving us a little more to work with... Cheers, Simon Brunning, http://www.brunningonline.net/simon/blog/ --LongSig ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From s-rube at uselessbastard.net Wed Nov 12 19:38:25 2003 From: s-rube at uselessbastard.net (Eric Williams) Date: Thu, 13 Nov 2003 01:38:25 +0100 Subject: web guru advise needed. References: Message-ID: Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: > Thnx. > > Regarding the SimpleTAL, can you give me an example of one of your heinous > URLs and explanation why you had to do it that way? > > Vincent Sure, although I might embarass myself: My setup is: http://server/index.py is the main script possible displayable objects are represented as story objects. Each story has a unique id, stored in a PostgreSQL database with meta information as SQL fields, and the object itself as a blob. Generally, you only have to specify an ID for a story or category URL: http://server/index.py?story_id=40 The default method here would be the "show" method of the story, and will fill in the blanks of which category you're in, etc. so far so good. What gets messy is when you want to perform other actions on the story than showing, e.g. /index.py?story_id=40&action=edit_story so that simpleTALES knows to load and compile the edit_story.html template instead of the show_story.html one, And, of course, if they've got cookies disabled /index.py?story_id=40&action=edit&cmxsessid=742308039 The equivalent Zope URL, for example, would be something like: http://server/Category/StoryId/EditStory.html Which, in comparison, is a lot easier read to someone over the phone. There's probably away around this kind of thing if you're good enough with Apache rewriting, but I'm not, and it kind of takes care of itself. I'd also be interested in what people consider the Right Way to Do It. Although it works, it smells a little too much like php to me. cya, Eric > > -----Original Message----- > From: Eric Williams [mailto:s-rube at uselessbastard.net] > Sent: Monday, November 10, 2003 1:25 PM > To: python-list at python.org > Subject: Re: web guru advise needed. > > > Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: > >> >> 1) simple presentation layer processing. The HTML pages produced by >> server will be more focused on presenting images (dynamic), rather that >> fancy tables, frames, buttons. 2) the framework has to be robust and FAST >> on performance. 3) runs only on Linux, well not really a requirement, >> more a statement. 4) runs on Apache (and/or Tomcat) >> >> What technology gives me the best performance? >> I'm so afraid that adapters like WebKit kills my performance but because >> of my jsp experience, psp seems the best option. >> >> Vincent > > FWIW, I recently complete a CMS project with the following constellation: > > 1) Apache with mod_python > 2) PostgreSQL for content storage, mostly in the form of blob'd Pickles > 3) Templating using SimpleTAL (elegant and leightweight, but requires some > downright heinous URLs) > 4) Everything running behind Squid in accelerator mode > > It's pretty dang snappy on performance, but you'd need a dedicated > server/processor for dynamic images, I would think. > > cya, > Eric > -- --- s- should be removed to contact me... From tjreedy at udel.edu Tue Nov 18 18:36:14 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Nov 2003 18:36:14 -0500 Subject: True inconsistency in Python References: <3FB91F07.9F275BB4@alcyone.com> <20031117201113.28795.00000484@mb-m17.aol.com> Message-ID: "KefX" wrote in message news:20031117201113.28795.00000484 at mb-m17.aol.com... > >not. However long the expression is, I don't see how adding `== true' > >at the end makes it more clear. > > What if the expression is 37 lines long? Given that if References: <9eabe547.0311131610.4dd7819c@posting.google.com> Message-ID: Thomas Guettler schrieb: > Me, too. I like python very much. But most people > who use computers since 1996 use either java, perl, C or bash. > > They know their language and don't want to change. > > One reason could be: python is too simple. If you write > code that nobody understands (perl) you are a guru. You are right. If you learn something that's hard to grasp for others you are a guru. But in software development the tools should add no unneccessary burden to the solution as the problems are already hard enough. An example of guru appeal I recently stumbled about are Perl's Quantum::Superpositions which is really a nice idea. This module is inspired by quantum physics but in fact applied probability theory and predicate logic. But to say, "Hey, I just did quantum computations in Perl" has surely more guru appeal than to say "Hey, I just enumerated a sample space." :-) Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From adalke at mindspring.com Mon Nov 10 00:05:09 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 10 Nov 2003 05:05:09 GMT Subject: Rekall and associated software go 100% GPL References: <3fae9c76$0$12714$fa0fcedb@lovejoy.zen.co.uk> <99dce321.0311091647.3e9e8165@posting.google.com> Message-ID: <90Frb.5937$nz.851@newsread2.news.pas.earthlink.net> John Dean > > So please visit > > http://www.totalrekall.co.uk and download download a copy for yourself. In > > order for you to be able to download you must register with the Total Rekall > > Portal. David M. Wilson > I'm sure you are aware, that this is unenforcable under the GPL. No it isn't. Given John's statement above, it's completely valid and enforceable. Once you have the software you can redistribute it without requiring that others register with Total Rekall Portal. > People are free to redistribute without registration requirements. Yup. Note the "redistribute" part. You have to get it in the first place. > It is also interesting to see that after going to great (and > controversial) lengths to give your users more freedom through this > new license, you apply this 'petty' restriction of registration and > mandatory notifications of new releases. This seems a little > contradictory to me, 'sall. Saying nothing about Rekall, but if I wanted to I could require that you pay me $1 million and your home phone number before you get a copy of my GPL'ed software. You are at that point free to redistribute the software without additional requirements, but if you wish you could also redistribute it for $1 million a pop. Andrew dalke at dalkescientific.com From skip at pobox.com Tue Nov 25 10:00:56 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 25 Nov 2003 09:00:56 -0600 Subject: sleep() function, perhaps. In-Reply-To: References: Message-ID: <16323.28328.257960.417504@montanaro.dyndns.org> Ryan> I want to have a row of periods, separated by small, say, .5 Ryan> second intervals between each other. Thus, for example, making it Ryan> have the appearance of a progress "bar". You might find my progress module at http://www.musi-cal.com/~skip/python/progress.py a good starting point. Something like import progress, time ticker = progress.Progress(major=1, minor=1, majormark='.') while True: ticker.tick() time.sleep(0.5) running in a separate thread should do what you want. In many situations you want to actually measure progress of some computation. If you can wedge in a call to ticker.tick() on each pass of your main computation loop: import progress, time ticker = progress.Progress() while some_condition_holds: one_more_computational_step() ticker.tick() you can watch your computation progress. This is particularly helpful if you know how many passes you need to make around the loop: import progress, time number_of_passes = 10000 ticker = progress.Progress(title="(%d)" % number_of_passes) for i in xrange(number_of_passes): one_more_computational_step() ticker.tick() The title displayed tells you how many loops to expect and the dots and numbers measure your progress: (10000): .........1.........2.........3.........4 and when you delete the ticker or it goes out-of-scope, it displays the total number of ticks (which might be lower if the loop was exited prematurely). There are more bells and whistles. Check the Progress class docstring for full details. Skip From arnaud.fausse at wanadoo.fr Thu Nov 27 01:00:06 2003 From: arnaud.fausse at wanadoo.fr (Arnaud-F. FAUSSE) Date: Thu, 27 Nov 2003 07:00:06 +0100 Subject: NoneType object returned by .fetchone() in MySQLdb References: Message-ID: Peter, my code looks similar to cs = conn.cursor() cs.execute("select * from mytable;") cs.fetchone() but I don't have a cursor problem due to reaching the end of the selected data. The object returned is not None but something like that: (125L,), I expect a tuple of 1 element containing a long integer. In fact the type of this object is NoneType and not Tuple as expected. If I do the same with "fetchall", the returned object has a Tuple type. I will do some captures and send in a next mail. Regards Arnaud "Peter Otten" <__peter__ at web.de> a ?crit dans le message de news:bq358d$jcq$00$1 at news.t-online.com... > Arnaud-F. FAUSSE wrote: > > > I wrote code to store and fetch information from MySQL, and I have this > > problem: > > - using .fetchall(), I get tuples (correct according to specification) > > - using .fetchone(), I get NoneType object, that I have many problems to > > use > > :-( > > Did I miss somthing ? > > > > Any clue ? > > Are you testing with code like below? > > cs = conn.cursor() > cs.execute("select * from mytable;") > cs.fetchall() > cs.fetchone() > > fetchall() moves the cursor after the last row. When you invoke fetchall() > again it will return an empty list whereas fetchone() will return None. > To fix it, just execute the cursor before fetchone(), e. g: > > cs.execute("select * from mytable;") > while 1: > row = cs.fetchone() > if row is None: break > # process row > > #this might also work (it does for sqlite) > cs.execute("select * from mytable;") > for row in cs: > # process row > > Of course I'm just guessing. It could also be an sql select that returns no > rows or something entirely different. Please post a minimal example code > next time you have a problem. > > Peter From mark.ferguson at newellandbudge.com Wed Nov 5 09:34:29 2003 From: mark.ferguson at newellandbudge.com (Mark Ferguson) Date: Wed, 05 Nov 2003 14:34:29 +0000 Subject: Pycurl proxy authentication anyone? Message-ID: I've been trying to get a simple pycurl script working with an authenticating proxy, here is the code (with changes to protect the guilty!): from pycurl import * import StringIO b = StringIO.StringIO() c = Curl() c.setopt(URL, "http://www.google.com/") c.setopt(VERBOSE,1) c.setopt(HTTPHEADER, ["User-Agent: Mozilla/5.001 (windows; U; NT4.0; en-us) Gecko/25250101", "Agent: "]) c.setopt(PROXY, "dummyproxy") c.setopt(PROXYPORT,80) c.setopt(PROXYUSERPWD,"dummyuser:dummypasswd") c.setopt(HTTPAUTH,8) #NTLM c.setopt(WRITEFUNCTION, b.write) c.setopt(FOLLOWLOCATION, 1) c.setopt(MAXREDIRS, 5) c.perform() print b.getvalue() And I get.... * About to connect() to dummyproxy:80 * Connected to dummyproxy (10.10.10.10) port 80 > GET http://www.google.com/ HTTP/1.1 Proxy-authorization: Basic ZHVtbXl1c2VyOmR1bW15cGFzc3dk Authorization: NTLM TlRMTVNTUAABAAAAAgIAAAAAAAAgAAAAAAAAACAAAAA= Host: www.google.com Pragma: no-cache Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */* User-Agent: Mozilla/5.001 (windows; U; NT4.0; en-us) Gecko/25250101 < HTTP/1.1 407 Proxy authentication required < Proxy-Authenticate: NTLM < Proxy-Connection: close < Content-Length: 503 < Content-Type: text/html * Connection #0 left intact Error 407

HTTP Error 407

407 Proxy Authentication Required

You must authenticate with a proxy server before this request can be service nd then try again.

Please contact the Web server's administrator if this problem persists.

* Closing connection #0 The username:password combo are correct. I'm stumped! suggestions gratefully accepted.. Mark. From peter at engcorp.com Tue Nov 25 12:06:57 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 25 Nov 2003 12:06:57 -0500 Subject: ssh connections? References: Message-ID: <3FC38C31.47D13846@engcorp.com> Laura Uixera Cotano wrote: > > I'm new in Python and I have to make a ssh connection to a proxy server. > Can you tell me how can I do it? > I've tried to find something useful, but I didn't find anything in books or > in the internet. > I have installed the version 1.5.2 of Python. Do you know if I need to > install a newer one to use ssh connections? > If you can tell me where can I find more information, please tell me. Twisted has SSH (named "conch" therein), though I haven't tried it myself. I did post a simple snippet that allowed using the "ssh" program on Linux via pexpect. Check the archives of the newsgroup/mailing list for that. It was just a modified version of something that, as I recall, Eric Raymond had written up. -Peter From jdhunter at ace.bsd.uchicago.edu Mon Nov 3 23:15:34 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 03 Nov 2003 22:15:34 -0600 Subject: nearest neighbor in 2D In-Reply-To: (bokr@oz.net's message of "4 Nov 2003 02:49:10 GMT") References: Message-ID: >>>>> "Bengt" == Bengt Richter writes: Bengt> Are you trying to find closest location to a mouse cursor Bengt> as it moves, and then adding a point when there's a click? Bengt> I.e., your particular use case might suggest a strategy Bengt> that's different from, e.g., what you'd do if each new Bengt> point's coordinates where read from file or came from a Bengt> generator, and you had exactly one search leading to Bengt> exactly one update of the set. And also what you wanted to Bengt> do with the completed set. I had two use cases just yesterday. The one that prompted the question arose in making a contour plot. I'm defining a contour as an ordered sequence of values over a 2D MxN matrix where the values differ from some target value by at most some tolerance. I maintain a list of i,j indices into the matrix for a given contour value, and follow the contour from a given i,j location by examining its neighbors. In order to close the loop (eg, when the contour finder has passed once around a level curve of a mountain, I want to test whether a given point i,j is close to a previously discovered point k,l. Since I have a list of these 2 tuple coordinates, I want to find the nearest neighbor in the list and terminate the contour when the nearest neighbor falls within some minimum distance 3 4 5 2 6 13 1 7 12 8 11 10 9 In the example above, I am traversing a contour identifying points in the order 1,2,3...; as above each point represents an i,j tuple which is an index into the matrix I am contouring. I would like to terminate the search at 13 rather than spiral around the existing contour 1-12. Each time I add a new point to the contour, I would like to query the existing list (excluding the most recently added points which are close by construction) of locations and find the minimum distance. If I'm not too close to the preexisting contour, I add the new point and proceed. As I write this I realize there is an important efficiency. Since from an existing point I add the closest neighbor, the biggest step I can make is 1,1. If on the last nearest neighbor query I find a minimum distance of d, it will take me d minimum steps to approach the existing contour. So I don't need to check the distance again for at least d steps. So the algorithm can proceed 1) obtain the distance d from the existing contour to the most recently obtained point 2) make d steps adding points that meet the value criteria 3) repeat. The second use case arose with gdmodule, which can only allocate 256 colors, which I cache as a dict from rgb tuples (eg, 0.0, 0.05, 1.0) to color. When the total number of color allocations is made, and a new rgb request comes into the color manager, I pick the already allocated point in rgb space closest to the requested point. I'll try David Eppstein's approach tomorrow and see how this fares. Thanks to all for suggestions, John Hunter From bignose-hates-spam at and-benfinney-does-too.id.au Wed Nov 19 20:15:15 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 20 Nov 2003 12:05:15 +1050 Subject: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com> <5sednRMoe_Q-jiGiRVn-tg@speakeasy.net> <7xu14zrg39.fsf@ruckus.brouhaha.com> Message-ID: On 19 Nov 2003 17:20:10 -0800, Paul Rubin wrote: > "A.M. Kuchling" writes: >> [the Unix command] uniq doesn't report an error if its input isn't >> sorted. > > Maybe it should. If its behavior on unsorted input isn't specified, > you shouldn't assume it will act in any particular way. The specification on the man page for GNU uniq seems clear on this: DESCRIPTION Discard all but one of successive identical lines from INPUT (or standard input), writing to OUTPUT (or standard output). It doesn't care if the input is sorted or unsorted; it describes behaviour on successive identical lines, not the total set of all lines. -- \ "The Bermuda Triangle got tired of warm weather. It moved to | `\ Alaska. Now Santa Claus is missing." -- Steven Wright | _o__) | Ben Finney From aleax at aleax.it Mon Nov 17 12:09:17 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 17 Nov 2003 17:09:17 GMT Subject: Dictionary problem References: Message-ID: <1h7ub.34645$9_.1383276@news1.tin.it> Elena Schulz wrote: > myList = [] > for i in range(3) : > myDict['id']=i > myList.append(myDict) > > myList becomes: [{'id':2}, {'id':2}, {'id':2}] but I want: [{'id':0}, > {'id':1}, {'id':2}] So, you don't want to append myDict itself, but, rather, a copy of it. > thanx for any hint how to achieve that Instead of: myList.append(myDict) which appends myDict itself, append a copy, e.g.: myList.append(myDict.copy()) or myList.append(dict(myDict)) Python doesn't make copies by default: when you want a copy, you ask for one explicitly, as in these two examples. > (Please answer to my mail address directly as I am currently not > subscribed to this list, thanks) Answering by both posting and mailing as requested. Alex From mbabcock at fibrespeed.net Mon Nov 3 16:49:17 2003 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Mon, 03 Nov 2003 16:49:17 -0500 Subject: variable assignment within a loop In-Reply-To: References: Message-ID: <3FA6CD5D.3010204@fibrespeed.net> > have this for loop in a program that I'm writing: > > for bad_dir_char in bad_dir_chars: > newdir = dir.replace(bad_dir_char,'-') > > Now, when I use this if statement: > > if newdir != dir: > old_dir_path = os.path.join(root,dir) > new_dir_path = os.path.join(root,newdir) > os.rename(old_dir_path,new_dir_path) > print "replaced: ",bad_dir_char," > > I get a "local variable 'newdir' referenced before assignment" error. The problem I would guess is that you don't create "newdir" before that loop. It helps to have a shorter example: a = "" for x in "abc": a = x print a print a You'll get something like: a b c c ... because you've overwritten your "a" variable with each looping, when you're done the loop the 'a' variable still has the same value as it did in the last loop ("c"). Now, if you remove the 'a = ""' at the beginning, you'll get an error on that last "print a" because the variable doesn't exist in that "scope". For the sake of visualization, scope is basically the depth of indentation in Python. So if you didn't define the variable at this indent level or higher, it doesn't exist. I'm not sure that is readable, but its what I had after a long day of C++/MFC coding ... ugh. -- Michael T. Babcock C.T.O., FibreSpeed Ltd. http://www.fibrespeed.net/~mbabcock From skip at pobox.com Sat Nov 22 23:15:33 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 22 Nov 2003 22:15:33 -0600 Subject: DBI trace? In-Reply-To: References: Message-ID: <16320.13413.342733.16816@montanaro.dyndns.org> >>>>> "Andrew" == Andrew Fabbro writes: Andrew> Is there something akin to perl's DBI->trace in python? I don't know. What is DBI->trace? If you describe what you're looking for, perhaps someone will have some ideas about whether or not it exists currently or might be fairly easily implemented. Skip From jjl at pobox.com Fri Nov 28 16:56:21 2003 From: jjl at pobox.com (John J. Lee) Date: 28 Nov 2003 21:56:21 +0000 Subject: math.pow vs pow References: <87k75lmlru.fsf@pobox.com> Message-ID: <877k1k2m4a.fsf@pobox.com> "Georgy Pruss" writes: > "John J. Lee" wrote in message news:87k75lmlru.fsf at pobox.com... > | For some applications, getting a complex result means you've made a > | mistake. And some people don't know what a complex number is, and > | would rather have their teeth drilled than find out. > > Can you provide an example when pow with real arguments gives a complex result, > please? [...] I was thinking about results of earlier calculations providing the argument for pow. John From joshway_without_spam at myway.com Fri Nov 7 12:20:18 2003 From: joshway_without_spam at myway.com (JCM) Date: Fri, 7 Nov 2003 17:20:18 +0000 (UTC) Subject: reduce()--what is it good for? References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> Message-ID: Alex Martelli wrote: ...various good points... > if one is in a hurry, recursion and > memoization are obviously preferable: > def facto(n, _memo={1:1}): > try: return _memo[n] > except KeyError: > result = _memo[n] = (n-1) * facto(n-1) > return result > the performance numbers being: > [alex at lancelot bo]$ timeit.py -c -s'import facs' 'facs.factorial(13)' > 100000 loops, best of 3: 10.3 usec per loop > [alex at lancelot bo]$ timeit.py -c -s'import facs' 'facs.fac(13)' > 10000 loops, best of 3: 32 usec per loop > [alex at lancelot bo]$ timeit.py -c -s'import facs' 'facs.facto(13)' > 1000000 loops, best of 3: 1.26 usec per loop I'm going off topic, but it's really not fair to compare a memoized function to non-memoized implementations using a "best of 3" timing test. From rshaw2 at midsouth.rr.com Mon Nov 3 10:26:34 2003 From: rshaw2 at midsouth.rr.com (Richard) Date: 3 Nov 2003 07:26:34 -0800 Subject: [newbie] file object not returned by function? References: Message-ID: <84e0f331.0311030726.2d2c4945@posting.google.com> > >while True: > > minutes, seconds = localtime()[4], localtime()[5] > > > > if date != localtime()[2]: # a new day has dawned, open a new logfile > > logfile = make_logfile() > > date = localtime()[2] > > Just an idea here, but you call "localtime" four times here when you only need to call it once. Might something like this work? while True: day, hours, minutes, second = localtime()[2:6] if date != day: logfile = make_logfile() date = day Richard From hottlips_4u69x3 at yahoo.com Thu Nov 27 21:55:03 2003 From: hottlips_4u69x3 at yahoo.com (hottlips_4u69x3) Date: Fri, 28 Nov 2003 02:55:03 -0000 Subject: Got Cum? Message-ID: If you have a full cock that needs to be drained take a look at the link below. I met three bitches off there and get laid more then I can handle. Take a look it's FREE!! http://www.hotpersonalad.com/landing.asp?afl=NYHO From http Tue Nov 25 17:43:44 2003 From: http (Paul Rubin) Date: 25 Nov 2003 14:43:44 -0800 Subject: Python docs in Info format? References: <7x3ccc87ki.fsf@ruckus.brouhaha.com> Message-ID: <7x8ym4yspr.fsf@ruckus.brouhaha.com> Ben Finney writes: > You can browse Web pages in Emacs using W3. > > Yeah, but that's not so nice to navigate. Info is a perfectly good doc format and it would be nice to be able to crunch those latex files into info format. From rooting_j00 at hotmail.com Wed Nov 5 02:30:01 2003 From: rooting_j00 at hotmail.com (Code_Dark) Date: 4 Nov 2003 23:30:01 -0800 Subject: New to Python; Command equivalents Message-ID: <8f43ba42.0311042330.7eaa6e10@posting.google.com> Hi, I'm new to the Python programming language, and eager to learn. I know C and C++, but I'm sure you all know that feeling when you just _need_ a new language. I chose python because I'd heard good things about it. I have python 2.3 installed on my computer, and I am glad to say that I've created a "Hello, World" program. Right, the only problem is that the only command I've been able to figure out is 'print'. That's quite a problem. I was just wondering if someone could give me the command for 'cin' or 'scanf' in the C-based languages, and if it is required to define variabled before using them as in the C based languages (such as ;int numbofPizza' in the beginning of the program). Sorry for asking such newbieish questions, but I am, in fact, a newbie. Please reply to this, or email me at dshaw858 at hotmail.com ... the email address I use for my newsgroups (rooting_j00 at hotmail.com) isn't regularly checked because of spam... meh. Thanks in advance, - Code Dark From theller at python.net Sat Nov 1 14:56:06 2003 From: theller at python.net (Thomas Heller) Date: Sat, 01 Nov 2003 20:56:06 +0100 Subject: py2exe question References: <3FA36D0A.45BCA44B@easystreet.com> <6FKob.391474$R32.12987108@news2.tin.it> <3FA3EE35.F382B493@easystreet.com> Message-ID: achrist at easystreet.com writes: > The error I'm getting is in module imputil.pyo, line 601, in > import_file, module does not define init function initpywintypes23. > > Please, can anyone tell what this means and how to fix? I think it has to do with the way win32all finds and loads the PyWinTypes extension. Back in the past it was found via registry entries, nowadays Mark Hammond changed it to be done without the registry. py2exe up to version 0.4.2 has not be adapted to this change, but the 0.5.0 alpha version (available in the files section of http://sf.net/projects/py2exe) is able to handle this. It requires Python 2.3 (because it uses the new zipimport feature), and a fairly new win32all. Thomas From j-anthony at rcn.com Tue Nov 11 10:44:25 2003 From: j-anthony at rcn.com (Jon S. Anthony) Date: 11 Nov 2003 10:44:25 -0500 Subject: Python from Wise Guy's Viewpoint References: <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <3F9D5D21.2060408@ps.uni-sb.de> <3fb097fe$1@news.unimelb.edu.au> <3fb0c2cd$1@news.unimelb.edu.au> Message-ID: Fergus Henderson writes: > Well, DEFTYPE in lisp really just defines a function, doesn't it? > So that's not much different than DEFUN. Likewise, DEFCLASS just > defines a collection of functions, doesn't it? OK, maybe these > also record some extra information in some global symbol tables. > That is easily emulated if you really want. > > I don't know exactly what DEFPACKAGE does, but if the others are any > guide, it's probably not too hard either. Yes, if you reimplement Lisp you can achieve what was asked. However, I don't think "turing equivalence" or Greenspun's tenth was the point... /Jon From jjl at pobox.com Mon Nov 3 17:36:34 2003 From: jjl at pobox.com (John J. Lee) Date: 03 Nov 2003 22:36:34 +0000 Subject: timeoutsocket.py References: Message-ID: <878ymx9j0t.fsf@pobox.com> "Gilles Lenfant" writes: [...] > > Note that if you upgrade to Python 2.3, it's now built-in. > > Thanks, I know this, but I need to stay with Python 2.2.x because [...] Do note this thread, then: http://www.google.com/groups?selm=mailman.1037399909.22831.python-list%40python.org John From email9898989 at yahoo.com Mon Nov 17 12:14:07 2003 From: email9898989 at yahoo.com (email9898989 at yahoo.com) Date: 17 Nov 2003 09:14:07 -0800 Subject: PyQt, Qt, Windows and Linux References: Message-ID: > Trolltech's pricing strategy, for me, keeps me on wxWindows. Qt does > seem like an excellent product, however. I agree. I guess the simplest explanation is that if you have anything to do with Windows or if you want to sell your software, you have to pay for TrollTech's Qt and PyQt (minimum $400 for BlackAdder). The only way it is free to use it is if you are developing on Linux, distributing only to Linux users, and not charging for your software. Here are some technical advantages to Qt/PyQt/PyKDE, but I can still wouldn't recommend it for Windows development: - QT Designer is a very nice intuitive visual GUI builder (form designer). You can progress from a simple prototype to a cross-platform app easily. You aren't forced to plan the layout in advance. Then again for most apps it is not hard to just do your layout in code. - The QT C++ API is better designed, although that doesn't mean it is better for Python development (both PyQt and WxPython are basically thin wrappers for the C++ Qt and wxWindows APIs). Performance or bug-wise I don't know that PyQt is better than wxPython on Windows. On Linux, wxPython uses GTK. - With KParts and KDE applications, you can embed other components (like a web browser or spreadsheet) into your own app, although PyKDE does not yet support this. You can do something similar in wxPython on Windows embedding ActiveX controls (such as Internet Explorer or Adobe Acrobat Viewer). From theller at python.net Sat Nov 1 06:54:14 2003 From: theller at python.net (Thomas Heller) Date: Sat, 01 Nov 2003 12:54:14 +0100 Subject: Py2exe invalid syntax???/i hate distutils References: Message-ID: "Ray" writes: > Python setup.py install > No still getting "invalid syntax" Looks like a syntax error somewhere in 'setup.py'. Thomas From nav+posts at bandersnatch.org Wed Nov 12 23:16:09 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 12 Nov 2003 23:16:09 -0500 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: Message-ID: aahz at pythoncraft.com (Aahz) writes: > No, they won't. They'll be challenged under the ADA (Americans with > Disabilities Act) and judged illegal. I'm amazed it hasn't been challenged yet. I can't see how the tactic doesn't violate Section 508, which means the US goverment can't employ it on any of their sites. 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 bgudorf at neurokode.com Mon Nov 17 01:55:46 2003 From: bgudorf at neurokode.com (Bryan J Gudorf) Date: Mon, 17 Nov 2003 01:55:46 -0500 Subject: Python Database Objects (PDO) 1.2.0 Released Message-ID: PDO, an open source python module for interfacing with RDBMS (SQL databases), has now reached 1.2.0! PDO provides an object oriented API, similar to that of ADO or JDBC, to python developers. PDO features column access by name. This new release adds support for the cx_Oracle, DB2 and adodbapi modules, allowing users to use PDO with a variety of database systems. 9 different DBAPI modules are now supported, allowing for PDO to be used with almost any RDBMS. Additional features, such as query parameters, have also been added in this release, as well as the usual bug-fixes. PDO is released under a BSD style license. PDO supports the following DBAPI python modules and databases: MySQLdb (supports MySQL) PySQLite (SQLite) pgdb (PostgreSQL) kinterbasdb (Firebird, Interbase) mxODBC (Many) pyDB2 (IBM's DB/2) cx_Oracle (Oracle) adodbapi (windows only - any RDBMS with an OLE DB provider or ODBC driver) As we move forward in this series we will be adding further functionality and support. Community support and feedback is appreciated so that we can make PDO as useful as possible. Downloads for Python Database Objects are available on SourceForge.Net or for more information please visit pdo.neurokode.com. Bryan J Gudorf ~NeuroKode Labs From mark at hahnca.com Thu Nov 6 01:14:48 2003 From: mark at hahnca.com (Mark Hahn) Date: Wed, 5 Nov 2003 22:14:48 -0800 Subject: New to Python - Compiled Language? References: <2259b0e2.0311050822.6c114cb9@posting.google.com> Message-ID: If you want to see an example of a complete non-trivial windows shareware application written in 100% python, download my: http://ezpicmailer.com. There is no way anyone can distinquish it from a C++ or VB app and no one has dinged me for it's download size. "Michael Geary" wrote in message news:vqif0v95nftmba at corp.supernews.com... > > Michael Geary: > > > Python compiles to bytecode, not to machine code. But that > > > doesn't mean the end user needs to install a Python interpreter. > > Michele Simionato: > > Actually it does; py2exe and similar programs ship the interpreter > > bundled with the code, so you don't install the interpreter directly, > > but indirectly you do. The disadvantage is that a ten line script > > requires megabites of space in order to be made executable. This > > may be an issue if you plan to distribute your program via the net > > and your customers have slow connection. Also, it may be an issue > > for embedded systems. Finally, it is somewhat disturbing that a ten > > line script cannot fit in good old 3.5' floppy :-( > > That's true, of course. What I meant was merely that you could hide all of > this so that the end user doesn't have to go through a separate step of > downloading and installing the Python interpreter. So it becomes a size > issue, not a "why do I have to go through all these steps?" issue. > > -Mike > > From alanmk at hotmail.com Tue Nov 18 05:43:13 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 18 Nov 2003 10:43:13 +0000 Subject: syntax philosophy References: Message-ID: <3FB9F7C1.7CCF7985@hotmail.com> [Tuang wrote] > I'm checking out Python as a candidate for replacing Perl as my "Swiss > Army knife" tool. The longer I can remember the syntax for performing > a task, the more likely I am to use it on the spot if the need arises. > If I have to go off and look it up, as I increasingly have to do with > Perl's ever hairier syntax, I'm more likely to just skip it, making me > even less likely to remember the syntax the next time. and [Tuang wrote] > Imagine that you have a list of records -- lines in a text file will > do fine. Let's say each record is a person and you're interested in > favorite colors. > > You iterate thru the lines, regexing the "favorite color" field out of > each and put it in the variable $color. Then you just use the line: > > $dict{$color}++ > > to count up what you find. The first time that line is called, it > creates the dictionary, then creates a key for $color, initializes its > value to zero, then increments it to 1. > > As you continue iterating, each new color it encounters creates a new > key, initializing it to zero and incrementing. When it finds a color > that already has a key, it just increments the count. It seems to me that it is not syntax that is the issue here, but semantics. You've listed a number of data structures that are creatly implicitly by Perl, given the above syntax, i.e. dictionaries, keys, etc, are created implicitly as your code is run. That, IMHO, is what hinders you from remembering the "syntax" to carry out the job. You don't just have to remember the syntax, but also all of the implicit object creation semantics that go with it. That is more likely to send you reaching for the reference manual, and also more likely to prevent you using such use a construct (according to your statement "If I have to go off and look it up .. I'm more likely to just skip it"). The problem with such implicit semantics is that they increase the complexity of what it is that you're learning, and thus steepen your learning curve. It gets worse if/when there are lots of special cases because the implicit object creation semantics don't fit every situation, and the semantics implied by a syntax vary depending on context. I think the fundamental difference between Perl and Python is one of philosophy. Perl people seem to like implied semantics, because it gives them terser code, meaning that 1. More steps can be achieved with less syntax, e.g. golf competitions[1]. 2. Increasing knowledge of the "secret operation of the machine" brings on feelings of guru-hood. 3. Which is shown off by writing code which depends upon the detailed implicit semantics of the machine, that no-one else can understand without a similar detailed understanding of the machine. Python takes the opposite philosophical view: Explicit is better than Implicit. Meaning object and data creation semantics are always explicit. This tends to make python code easier to read, because there is a limited (but well-designed and powerful) set of semantics to learn, which must be explicitly stated by all code that uses them. Have you done this yet? shell>python Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 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! >>> Welcome to the python community. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan [1] http://perlmonks.thepen.com/130140.html From exarkun at intarweb.us Thu Nov 6 16:09:16 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 6 Nov 2003 16:09:16 -0500 Subject: prePEP: Decimal data type In-Reply-To: References: Message-ID: <20031106210916.GA25268@intarweb.us> On Thu, Nov 06, 2003 at 03:37:52PM -0500, Aahz wrote: > In article , > John Roth wrote: > > > >AFAICS, there are only two solutions: > > > >.add(, []) > > > >and > > > >.add(, ) > > Both are too inconvenient for casual users. I think that for the Money > subclass, it'll probably make sense to require users to specify an > explicit Context before the first operation (raising an exception if not > initialized). For Decimal, using the same defaults as Rexx will > probably work just fine. That sounds like it would work, if you are forced to specify the context on a per-instance basis. Otherwise, I don't see how two different modules which wanted to treat Money differently could ever be used together. How about this instead? import context class Decimal: ROUNDING_STYLE = 'decimal-rounding-style' ITALIAN, FRENCH, AMERICAN = range(3) def __add__(self, other): rstyle = context.get(Decimal.ROUNDING_STYLE, 'sane default') # Do stuff, depending on rstyle return stuff def jiggerSomeMoneys(a, b, c): # Lots of operations on a, b, and c context.call({Decimal.ROUNDING_STYLE: Decimal.ITALIAN}, jiggerSomeMoneys, a, b, c) This way, only the top-most invocation need deal with the context. The actual implementation dealing with decimals is free to ignore it completely, and should it require a change, there is only a single place where that change is required. As an added bonus, the context code is completely independent of the decimal code, and can be re-used for any other application requiring contextual data. Implementations of context.call and context.get are left as an exercise to the reader (Eh, ok, I can show you mine if anyone is actually interested :) Jp From nhodgson at bigpond.net.au Thu Nov 6 15:54:18 2003 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Thu, 06 Nov 2003 20:54:18 GMT Subject: Unicode and Zipfile problems References: <3fa8d5ee.304218@news.t-online.de> <3faa8836.11485859@news.t-online.de> Message-ID: <_xyqb.181398$bo1.149434@news-server.bigpond.net.au> Gerson Kurz: > Of course I don't have the source for these, but > the Dependency Viewer (from the Microsoft SDK) will show you that all > of these link with the ASCII-Versions of the Windows API. No, these applications link to what Microsoft calls the "ANSI" versions of the Windows API. That is important because your initial problem would not have occurred if all your file names were ASCII. Instead they contained character 0x88 which was probably a circumflex modifier although it could have been a Euro symbol. > Seems like > there is a lot of broken apps out there! And the most shocking of all > - this holds true even of python23.dll: ShellExecuteA, > RegQueryValueExA, LoadStringA, LoadLibraryExA - its all ASCII! > Somebody better call for a major unicode cleanup! We will gradually work on increasing the scope of Unicode support in Python. For example, os.popen would be a good candidate for receiving Unicode support. > But OK, I agree, the subject is somewhat boring - even though every > week somebody else runs into problems with this (see the thread > "Strange problem with encoding" from today) there will probably be no > change introduced in Python at this point on this subject. If you are interested in enhancing Python then produce a concrete proposal. From my point of view, Unicode has been a great source of simplification as it has reduced the need for code conversion and potential for loss of information. In the future, more of the software infrastructure will be able to handle Unicode. ZIP files produced by some tools can already store Unicode file names although there is no published standard for this. Example product: http://www.componentsource.com/Catalog/XceedZipCompressionLibrary_505440.htm "Stores and retrieves the latest zip file format extensions, allowing Unicode filenames and NT file attributes, extra time stamps and security permissions to be stored in the zip file" ZIP format definition: http://www.pkware.com/products/enterprise/white_papers/appnote.html Neil From oss at oss.coresecurity.com Thu Nov 27 17:38:47 2003 From: oss at oss.coresecurity.com (CORE Security Technologies) Date: Thu, 27 Nov 2003 19:38:47 -0300 Subject: [ANNOUNCE] Python network security tools: Pcapy, Impacket, InlineEgg Message-ID: <3FC67CF7.50602@oss.coresecurity.com> Core Security Technologies acknowledges the increasing interest on its products and technologies and therefore wants to share part of them with the developers out there in the spirit of creating an open user community around its key components and give back to the community the results of our ongoing development. These are indeed primary components of our software, CORE IMPACT, and not the regular free giveaways you'd get somewhere else. As such they are being actively maintained by our team. Python developers, network administrators, penetration testers, vulnerability researchers and information security practitioners in general may find this packages useful. All the tools described in this announce are available at http://oss.coresecurity.com/ Today we are announcing the public release of the following components: Pcapy-0.10.2 Impacket-0.9.4 InlineEgg-1.02 And there is still more coming... enjoy! OSS at coresecurity.com A brief description of the components and bundled tools is provided below -OSS projects released November 27th, 2003- Pcapy http://oss.coresecurity.com/projects/pcapy.html Pcapy is a Python extension module that enables software written in Python to access the routines from the pcap packet capture library. From libpcap's documentation: Libpcap is a system?independent interface for user?level packet capture. Libpcap provides a portable framework for low?level network monitoring. Applications include network statistics collection, security monitoring, network debugging, etc. Pcapy is most useful when used together with a packet handling package such as Impacket, a collection of Python classes for constructing and dissecting network packets. What makes pcapy different from the others? * works with Python threads. * works both in UNIX with libpcap and Windows with WinPcap. * provides a simpler Object Oriented API. Impacket http://oss.coresecurity.com/projects/impacket.html Impacket is a collection of Python classes for working with network protocols. Impacket is mostly focused on providing low?level programmatic access to the packets, however some protocols (for instance NMB and SMB) are implemented in a higher level as a foundation for other protocols. Packets can be constructed from scratch, as well as parsed from raw data, and the object oriented API makes it simple to work with deep hierarchies of protocols. Impacket is most useful when used together with a packet capture utility or package such as Pcapy, an object oriented Python extension for capturing network packets. What protocols are featured? * Ethernet, Linux "Cooked" capture. * IP, TCP, UDP, ICMP, IGMP, ARP. * NMB and SMB (high?level implementations). * DCE/RPC versions 4 and 5, over different transports: UDP (version 4 exclusively), TCP, SMB/TCP, SMB/NetBIOS and HTTP. * Portions of the following DCE/RPC interfaces: Conv, DCOM, EPM, SAMR, SvcCtl, WinReg. What tools are included? We bundle some tools with Impacket which are mostly intended for documentation purposes, but that are worth mentioning as they might be useful even for non?programmers and those who don't plan to develop with this library. RPCDump An application that communicates with the Endpoint Mapper interface from the DCE/RPC suite and displays it in a more or less human readable form. This can be used to list services which are remotely available through DCE/RPC, such as the Windows Messenger. SAMRDump An application that communicates with the Security Account Manager Remote interface from the DCE/RPC suite and lists system user accounts, available resource shares and other sensitive information exported through this service. Tracer A grapher written using Tkinter that displays a parallel coordinates graph of captured traffic. It's very easy to find network usage patterns with this type of graphs, and therefore to detect unexpected variations. At the moment Tracer only supports TCP and UDP traffic, but can be easily extended to handle other protocols. Split A small tool that can split any pcap supported capture file into several smaller fires, separated by connection. This was developed to address the need to feed several hundred?megabyte captures to Ethereal in a way that didn't take too long to load. At the moment Split only supports TCP streams, but can be easily extended to handle other stream?oriented protocols. InlineEgg http://oss.coresecurity.com/projects/inlineegg.html InlineEgg is a Python module that provides the user with a toolbox of convenient classes for writing small assembly programs. Only that instead of having to remember confusing assembly mnemonics and requiring the developer to remember how to use complex tools like assemblers and linkers, everything is done the easy way: in Python. InlineEgg is oriented ?but not limited? to developing shellcode (sometimes called eggs) for use in exploits. InlineEgg started separately as a pretty simple idea to fulfill a pretty simple need, but today it's part of CORE IMPACT's egg creation framework. We are releasing it under an open source license for non-commercial use in the hope that you'll find it helpful for your own projects. From stuartf at the-i-junction.com Fri Nov 7 03:59:30 2003 From: stuartf at the-i-junction.com (Stuart Forsyth) Date: Fri, 7 Nov 2003 10:59:30 +0200 Subject: Unicode Hell In-Reply-To: Message-ID: <000601c3a50d$8b61dbb0$4e82010a@theijunction.icelogic.co.za> The replace string in this case is actually the contents of a file. I have simplified it for the purposes of the example. The file I'm doing the replace on is a web archive (.mht) file. Within that file are a number of different replace fields e.g. #name# #organisation# etc.. Everything was working fine until the replace function tried to replace the #name# replace field with a posting variable that had a tilde in it. The script then moaned about it being non-ascii and crashed. The exact error is: Error Type: Python ActiveX Scripting Engine (0x80020009) Traceback (most recent call last): File " """ def printReply(): connection = MySQLdb.connect( db = "try") cursor = connection.cursor() from convert import genPrime, genPrimeE p1 = genPrime() q1 = genPrime() e1 = genPrimeE() N1 = p1 * q1 M1 = (p1-1)*(q1-1) print 'e1 %d,' %e1 print 'm1 %d' %M1 while(e1 % M1 == 0): e1 = genPrimeE() cursor.execute("insert into trials(p,q) values ('4','546');") authorList = cursor.fetchall() cursor.close() connection.close() from convert import convertToBlocks list = convertToBlocks(form["message"].value) from convert import encryptBlock encList = [] for i in list: x = encryptBlock(i,e1,N1) encList.append(x) nProd = 0 for i in encList: nProd = (nProd + i) * 10000 personInfo['message'] = nProd print """ The following information has been saved in our database:
Name Email Phone OS Message
%(firstName)s %(lastName)s%(email)s %(phone)s%(os)s%(message)s



""" % personInfo def printFormError(): print """ FORM ERROR
You have not filled in all fields. Click the Back button, fill out the form and resubmit.

Thank You.""" printContent() form = cgi.FieldStorage() try: personInfo = { 'firstName' : form[ "firstname" ].value, 'lastName' : form[ "lastname" ].value, 'email' : form[ "email" ].value, 'phone' : form[ "phone" ].value, 'book' : form[ "book" ].value, 'os' : form[ "os" ].value, 'message' : form["message"].value } printReply() except KeyError: printFormError() Thanks!! From mcfletch at rogers.com Tue Nov 4 10:15:06 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 04 Nov 2003 10:15:06 -0500 Subject: sorting "problem" In-Reply-To: <200311040235.24482.gherron@islandtraining.com> References: <200311040235.24482.gherron@islandtraining.com> Message-ID: <3FA7C27A.7010802@rogers.com> Gary Herron wrote: >On Tuesday 04 November 2003 01:48 am, Bror Johansson wrote: > > >>Assume having defined two lists. There will be a one-to-one relationship >>between elements in the two lists. >> >>Is there a way to - when calling listA.sort() - have elements in listB >>shuffled the same as those in listA? When calling listB.sort(), the listA >>should be sorted alikewise. >> >> You can use the Numeric Python extensions for this if you've got a lot of elements: >>> from Numeric import * >>> a array([8, 5, 1, 4, 3]) >>> b array([5, 2, 9, 8, 7]) >>> indices = argsort(a) >>> indices array([2, 4, 3, 1, 0]) >>> c,d = take(a,indices),take(b,indices) >>> c array([1, 3, 4, 5, 8]) >>> d array([9, 7, 8, 2, 5]) Enjoy, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From bignose-hates-spam at and-benfinney-does-too.id.au Mon Nov 17 20:33:36 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 18 Nov 2003 12:23:36 +1050 Subject: True inconsistency in Python References: <3FB91F07.9F275BB4@alcyone.com> <20031117201113.28795.00000484@mb-m17.aol.com> Message-ID: On 18 Nov 2003 01:11:13 GMT, KefX wrote: > un-attributed author wrote: >>I don't see the value in this. The expression in an if statement is >>treated as a Boolean expression. [...] >>However long the expression is, I don't see how adding `== true' at >>the end makes it more clear. > > What if the expression is 37 lines long? What of it? Is a long expression in an 'if' statement somehow less likely to be treated as Boolean? What does appending ' == True' gain? How could it not be obvious that the entire expression will be evaluated for Boolean truth, when the expression is the argument to 'if' ? > Fishing out the main comparison in such a monster isn't always the > easiest thing to do. How does "fishing out the main comparison" have anything to do with appending ' == True' to the expression? > "a == 0" isn't comparing against true or false, it's comparing against > an integer. Correct. The comparison, though, is a Boolean expression, which will evaluate to either True or False. Its use in an 'if' statement will always evaluate it this way. > It's worth noting here that omitting the "== 0" here is > considered bad style by many (though this is by no means universal). Only in cases where ' == 0' is *not* a test for Boolean falsity. Compare a variable against 0 if you want to test if its value is numerically zero; evaluate the variable if it is supposed to contain a Boolean true or false value. > The camp that would have you write "== false" invariably falls in the > same camp that would have you write "== 0", because that way the two > would be consistent in that you always specify what's being compared > to what. No. The argument to 'if' is a Boolean expression. A test against numeric zero is not the same as a test against Boolean false, except by implementation coincidence. If the variable 'a' is conceptually containing a numeric value, then using it as a Boolean value implies things that are not necessarily true about the Boolean implementation. Hence, 'if( a == 0 )' and not 'if( ( a == 0 ) == True )'. Similarly, testing the negative case is 'if( not ( a == 0 ) )'. No explicit comparison to True or False is required. If the variable 'a' is conceptually containing a Boolean value, then using it as the argument to 'if' is consistent. Hence, 'if( a )' and not 'if( a == True )'. Similarly, testing the negative case is 'if( not a )'. No explicit comparison to True or False is required. Once the expression *reads as a Boolean expression*, then adding further comparisons against Boolean values helps nothing. > The idea is consistency (I don't know how that slipped my mind in my > original posting.) I, too, value consistency, which is why I abhor adding ' == True' to some Boolean expressions but not to others. It should be added to none of them. You appear to want semantic consistency between types (integer and Boolean) that *by design* aren't semantically consistent. The 'if' statement takes a Boolean expression as argument; to be consistent, one passes it a Boolean expression argument, not some other type of argument. -- \ "A celebrity is one who is known by many people he is glad he | `\ doesn't know." -- Henry L. Mencken | _o__) | Ben Finney From forth at gmx.de Tue Nov 18 12:06:23 2003 From: forth at gmx.de (S.Susnjar) Date: 18 Nov 2003 09:06:23 -0800 Subject: maximum value for long? Message-ID: Hello all, I have been programming in Python only for a month or so and have stumbled over a "problem" that I could not solve through rtfm. $ python Python 2.2.2 (#1, Nov 6 2003, 09:19:47) [GCC 3.3] on irix646 Type "help", "copyright", "credits" or "license" for more information. >>> ulong_max=18446744073709551615 >>> type(ulong_max) >>> print ulong_max 18446744073709551615 >>> very_long_long=1844674407370955161518446744073709551615 >>> type(very_long_long) >>> print very_long_long 1844674407370955161518446744073709551615 >>> result=very_long_long/15 >>> type(result) >>> print result 122978293824730344101229782938247303441 >>> I have set ulong_max above to the C compilers ULONG_MAX definition from limits.h I would have expected Python to complain when setting the value of the variable very_long_long to anything greater than ULONG_MAX. Since I am currently doing computations with integer values *much* bigger than ULONG_MAX, this behaviour suites me, but I am wondering if this is a "standard" Python behaviour since I do not want my scripts to become dependant on some obscure non-standard feature... Could any kind Python-Guru please shed some light on this? Also, if Python really can handle longs that are bigger than the machines native longs, the interpreter has to do some sort of arbitrary precision math somewhere. Could you please point me to the according interpreter's source file(s)? TIA + Regards, S.Susnjar From ulysses_dm at yahoo.com.cn Sat Nov 15 01:01:44 2003 From: ulysses_dm at yahoo.com.cn (ulysses) Date: 14 Nov 2003 22:01:44 -0800 Subject: can't run py app after compile to exe by py2exe , gettext References: <43e3984e.0311120110.2bea96cc@posting.google.com> <43e3984e.0311121700.1a7e642e@posting.google.com> Message-ID: <43e3984e.0311142201.603a6d17@posting.google.com> Thomas Heller wrote in message news:... Thank you very much. I was killed this question. completely remove python22 and python23,wxpython,py2exe. then reinstall python22,wxpython,py2exe 0.4.1. Rewrite my source code to a new py file. it's work. I still don't know where is bug. But I solve it. maybe my code very confusion. Python don't like awful code. :) anyway ,thanks Heller. > ulysses_dm at yahoo.com.cn (ulysses) writes: > > > I do a small test app for this. Still can't run. > > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > full source package > > please download from > > > > http://211.90.187.42/ourbt/gettexttest.rar > > > > you test in in your computer. Thanks. > > I tried it, and it seems you have to make sure that the en.mo file is in > the same directory as the exe, and you have to manually include the > 'encodings' package - there's a command line switch for that. > > To help to find these types of problems, it's always useful to build the > exe as a console version first with the --console command line flag to > py2exe. There's no way for the --windows exe to notify you of the > tracebacks. > > And if you want to try the 0.5.0 version of py2exe (which requires > Python 2.3), here is the setup script you would use: > > """ > from distutils.core import setup > import py2exe > > setup(name='testgettext', > options = {"py2exe": {"packages": ["encodings"]}}, > windows = ['main.py'], > data_files = [("", ["en.mo"])], > ) > """ > > The latest py2exe 0.5.0 creates windows programs in such a way that > tracebacks are routed into a log file (that would be 'main.exe.log' in > the above case), and even displayes a message box when the program ends > pointing the user to the logfile. > > Thomas From steve at ninereeds.fsnet.co.uk Sun Nov 2 02:36:10 2003 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sun, 02 Nov 2003 07:36:10 +0000 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <87he1vsopi.fsf@pobox.com> <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> Message-ID: <1589qvcdv9bni5fr8opactkgj9n5hecpj7@4ax.com> On Sat, 01 Nov 2003 17:39:54 GMT, "Andrew Dalke" wrote: >> How come then that the sciences have been so uncanningly effective >> given that they are such an arbitrary choice within the knowable? The >> answer is of course that there are a lot of other possible sciences, >> completely unrelated to our own that would have been just as effective >> as -or even more effective than- our current sciences, had they been >> pursued with equal persistence during the same amount of time over a >> lot of generations. > >I don't follow your argument that this occurs "of course." > >It's not for a dearth of ideas. Humans did try other possible >sciences over the last few millenia. Despite centuries of effort, >alchemy never became more than a descriptive science, and >despite millenia of attempts, animal sacrifices never improved >crop yields, and reading goat entrails didn't yield any better >weather predictions. ;-) Actually I missed this point in Antons post, being already primed to be bugged by his last paragraph or two, so I will reply to it here. The choice was not arbitrary by any stretch of the imagination. We could not construct the models described by quantum mechanics or relatively until we had a good understanding of classical mechanics. We cannot percieve either quantum or relativistic effects directly, so they could not be the earliest models. We needed sufficient scientific understanding and practical technology to be able to observe these effects at all. I doubt anyone could form a sensible theory of electricity, for instance, if the only experience of electricity that they could perceive was of phenomena such as lightning and flames. No wonder it was all blamed on angry gods! And yes, even classical mechanics could not have been our first model for simple commonsense reasons. How often, for instance, did ancient Greeks get to observe objects moving through a frictionless environment? >On the other hand, there are different but equivalent ways to >express known physics. For example, Hamiltonian and Newtonian >mechanics, or matrix vs. wave forms of classical quantum mechanics. >These are alternative ways to express the same physics, and some >are easier to use for a given problem than another. Just like a >sun-centered system is easier for some calculations than a "my house" >centered one. Rather similar to the idea of using different metaphors to explain the same model, though you are looking at maths rather than language. >On the third hand, there are new theoretical models, like string >theory, which are different than the models we use. But they are >not "completely unrelated" and yield our standard models given >suitable approximations. Agreed. Just as quantum mechanics and relativity both yield a close approximation of classical mechanics within certain limits, and just as classical mechanics yields something close to 'intuitive physics' within the limits of most peoples everyday lives. >On the fourth hand, Wolfram argues that cellular automata >provide such a new way of doing science as you argue. But >my intuition (brainw^Wtrained as it is by the current scientific >viewpoint) doesn't agree. I just love the way that a guy who got rich selling software to do fiddly maths jobs such as working with systems of differential equations has suddenly decided that all that fiddly maths is completely the wrong way to go ;-) But even if, at some level, the universe is a cellular automata, I don't see that meaning that the fiddly maths can be abandoned. The fiddly maths is generally an artifact of removing detail in a sense, after all - we use the formula for the entire path, for instance, rather than listing all the points that make up the path. And the list of points, like the list of states of the cells, lacks explanatory power. >> The effectiveness of the current natural sciences is a perceptual >> artifact caused by our biased history. From a lot of different >> directions messages are coming in now, all saying more or less the >> same: "If asking certain questions, one gets answers to these >> questions in a certain way, but if asking different questions one gets >> different answers, sometimes even contradicting the answers to the >> other questions". >> >> This might seem mystic or strange but one can see these things >> everywhere, if one asks that kind of questions :-) > >Or it means that asking those questions is meaningless. I wouldn't go so far. No model (at least none we have yet) is perfect, so different models are bound to contradict each other - particularly when you push them beyond their limits. Extrapolation is always less reliable than interpolation, so it is best not to use a model to extrapolate beyond the range where experiment has shown it to apply. But there is clearly a baseline reality which these models are seeking to approximate. As I mentioned earlier, when a primitive person tries to understand how your car works, the engine does not turn into a demon. The technology based on our current scientific understanding works, whatever you personally happen to believe. >For a simpler case .. what is the center of the universe? All locations >are equally correct. Is it mystic then that there can be multiple >different answers or is simply that the question isn't well defined? Hmmm - I suppose this depends what you mean by center. If you mean 'origin' in the graph-plotting sense, then you are right, of course. But my understanding is that the universe, so far as anyone can tell, is either an infinite space or finite without bounds. In either case, there is no such thing as a center. I find the 'infinite' theory dubious - if the expansion rate has remained finite since the big bang, then how can space have grown to become infinite? The only way I can understand it is if space was always infinite. That wouldn't necessarily mean it can't 'expand', just as it isn't necessarily impossible to multiply infinity by two. I guess 'expansion' relating to the universe is a metaphor too, really - after all, the universe isn't an object within some other space. The 'expansion' is really just rewriting of the scale factors on the dimension axes of the universe, I suppose. That being why the speed of light isn't a problem in inflation - nothing is actually moving faster than the speed of light, even though the distances between things is expanding faster than the speed of light. Hmmm - I wonder if 'expansion' or 'scale' is a continuous value in space-time, like curvature? Well, I guess it must be really - just write the model in those terms and hey presto - but what I mean, I guess, is "is there a function that can define that 'scale' in terms of local physics to explain things we don't currently have an explanation for?". >> One example would be the role the observer plays in quantum mechanics, >> but something closer to a programmer would be the way static or >> dynamic typing influence the way one thinks about designing a computer >> program. >And I don't see how the reference to QM affects the argument. Then >again, I've no problems living in a collapsing wave function. I suspect this is the 'conscious mind has special role as observer' thing again. And as has already stated, there are other explanations of waveform collapse that don't require consciousness to take a special role. Explanations that make more sense, as the observer never had any control over how the waveform collapses - it is a mechanical process that follows clearly defined non-mystical rules. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From peter at engcorp.com Mon Nov 10 17:28:27 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Nov 2003 17:28:27 -0500 Subject: OT lousy pun (was Re: What do you think of this Python logo?) References: Message-ID: <3FB0110B.927E72F8@engcorp.com> "Brandon J. Van Every" wrote: > > Brandon's Law (after Godwin's Law): > "As a Usenet discussion grows longer, the probability of > a person being called a troll approaches one RAPIDLY." Hmm... if that happens, should one *duck*? ;-) (I guess you meant 1.0, not one as in "a person".) -Peter From dave at pythonapocrypha.com Sun Nov 2 21:29:00 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sun, 2 Nov 2003 19:29:00 -0700 Subject: Experienced programmer evaluating Python References: Message-ID: <097001c3a1b2$3f183eb0$6400000a@YODA> > Hello. I'm an experienced programmer who is evaluating learning Python if > it is applicable to a few projects. The programs I am going to list are > production software - they are not throwaway toy projects, but will > actually have real world application. I've spent years writing C++ and > Perl code, but I would like to try "this Python language" out in their > implementation, as I have the luxury of slack deadlines for the next > little while. Awesome - hope you find the info below helpful. > 1] Embedding Python into a realtime game. I'm willing to take a > performance hit over strict c++ in the range of 10%, if the implementation A few commercial games out there have done this (Google Groups should turn up a few links if someone doesn't post the specific games) so it's definitely doable although I'm not sure of how much of a performance overhead you'll incur - hopefully someone more knowledgeable will chime in. At least one commercial game used the Stackless variant of Python so that you can have literally thousands of "microthreads", each running a separate game entity. You might also check out Pygame, although that's probably farther down the path than you're thinking of going. > 3] Redistributable end-user product development tools. I know and love > using wxWindows in C++. Basically, I need the ability to distribute > everything necessary for developers on the Internet (read: not average > users) to run wxWindows based Python apps on Win32 development > workstations. Licenses and convenience come into play. I don't mind a > large download for this crowd, but asking them to compile anything is > above and beyond. Not a problem, especially for Win32. www.wxPython.org plus stuff like py2exe or McMillian's Installer can give you whatever combination of half-baked or fully-baked applications you need. On Windows you can install Python, wxPython, and most other add-on libraries without requiring the user to have a compiler, and licensing isn't an issue with Python or wxPython. Another interesting twist is to use ctypes, which lets you call just about any API in any Windows DLL, again without a compiler, and again easily distributable. > Finally, is there any issues with me not distributing Python source if I > include a compiled DLL with commercial software? If I embed Python for > Win32, I have read that I need to dynamically link it. No - see http://www.python.org/doc/Copyright.html which includes "The gist of it is that Python is absolutely free, even for commercial use (including resale). There is no GNU-like "copyleft" restriction." Hope you have fun trying out Python, Dave From lord_ergo at yahoo.com Mon Nov 3 23:50:19 2003 From: lord_ergo at yahoo.com (Ergo) Date: Mon, 3 Nov 2003 22:50:19 -0600 Subject: wxPython Message-ID: Can anyone point me to a good site for wxPython. I can find the lib info, but would like more info on things like makeing textboxes, coloring the GUI and buttons etc. Thanks Ergo From mike at nospam.com Mon Nov 3 13:37:01 2003 From: mike at nospam.com (Mike Rovner) Date: Mon, 3 Nov 2003 10:37:01 -0800 Subject: Python on Itanium Windows 64: available or planned? References: Message-ID: Martin v. L?wis wrote: > That may even be a source of bugs. I'm in the process of putting > size_t in every place Python currently uses "int" or "long" to store a > number of bytes. In some cases, exceeding 4GB (sometimes 2GB) will > cause crashes in Python 2.3 (in other cases, this is somewhat overkill > - eg. when the compiler complains that strlen(some_file_name) may not > fit into 4 bytes). Does that mean forthcoming API interface change? There are mostly ints for sizes (ex. PyString_AsStringAndSize (PyObject *obj, char **buffer, int *length)). Regards, Mike From servantofthesecretfire at fea.st Sun Nov 16 23:26:41 2003 From: servantofthesecretfire at fea.st (ServantOfTheSecretFire) Date: 16 Nov 2003 20:26:41 -0800 Subject: Tkinter uses a lot of memory?! Message-ID: Hi there, I wrote my first Python program this weekend, Conway's Game of Life, and I used Tkinter for the graphics. I thought I had done something wrong when I saw the memory consumption, so I wrote the simplest Tk program I could, and yep, it takes about 40MB of memory! I'm using Red Hat Linux 9.0 and recent versions of the software. Please look at the output below, and tell me if I am confused... ~/python: cat /etc/redhat-release Red Hat Linux release 9 (Shrike) ~/python: rpmquery python python-2.2.2-26 ~/python: rpmquery tk tk-8.3.5-88 ~/python: rpmquery tkinter tkinter-2.2.2-26 ~/python: cat hello.py #!/usr/bin/python import Tkinter as Tk root = Tk.Tk() Tk.Button(text='Quit', command=root.quit).pack() root.mainloop() ~/python: python hello.py & [1] 25633 ~/python: ps u USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND sjm 23897 0.0 0.2 4980 1088 pts/0 S 12:18 0:00 -csh sjm 25633 4.8 7.2 41576 37352 pts/0 S 22:35 0:00 python hello.py sjm 25634 0.0 0.1 2616 660 pts/0 R 22:35 0:00 ps u From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Nov 6 15:35:08 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 06 Nov 2003 21:35:08 +0100 Subject: return multiple values from fuction In-Reply-To: References: Message-ID: <3faab07b$0$58705$e4fe514c@news.xs4all.nl> Alex Martelli wrote: >>how can I assign the two return values to two distinct variables, as for >>ex. >> >>varC = variableA >>varD = variableB > > > "just do it": > > varC, varD = function() I like that comment... "just do it"... I find this is also true for most other things that you want to do in Python. "How do I create a mapping between a person's last name and the list of telephone numbers he/she can be reached at?" -- "umm.. just do it?" { "de Jong": ['234234', '34562363'] } or whatever ;-) --Irmen From mis6 at pitt.edu Sun Nov 2 12:18:41 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 2 Nov 2003 09:18:41 -0800 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <87he1vsopi.fsf@pobox.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> <1589qvcdv9bni5fr8opactkgj9n5hecpj7@4ax.com> Message-ID: <2259b0e2.0311020918.2a8be41b@posting.google.com> "Andrew Dalke" wrote in message news:... > > But my understanding is that the universe, so far as anyone can tell, > > is either an infinite space or finite without bounds. In either case, > > there is no such thing as a center. > > Michele is a better one for this topic. My point was just that many > different answers doesn't necessarily imply a mystic explanation. Since the Universe is homogenous and isotropic, every point has the same right to be the center that any other point. In a more mathematically inclined perspective, notice that in a curved space the concept of center is tricky. For instance, what's the center of the *surface* of the Earth? (yes, somebody could say Washington DC, but I was talking about non-euclidean geometry, not about politics ;) > I read a popular account of "branes", membrane theory, which > was interesting. I don't know enough to describe it Then you know as much as the authors of the theory ;) Michele Simionato From dthierbach at gmx.de Sun Nov 2 05:38:23 2003 From: dthierbach at gmx.de (Dirk Thierbach) Date: Sun, 2 Nov 2003 11:38:23 +0100 Subject: Python from Wise Guy's Viewpoint References: <20031029085604.GU1454@mapcar.org> Message-ID: Lex Spoon wrote: > To add to the situation, HM flags extra errors, too, that many people > would not consider "type errors" but which are for HM's purposes. For > example, it is considered a type error if two branches of an "if" do > not match, even if one branch is impossible or if the later code can > remember which branch was followed. [...] > val (tag, thingie) = > if (whatever) > then (0, 1) > else (1, 1.0) > > val myotherstuff = > if tag = 0 > then (tofloat thingie) + 1.5 > else thingie + 1.5 The point here is of course that you "glue together" the tag and the value, with the additional side effect that this documents your intention. So you would write in this case data Thingie = Tag0 Integer | Tag1 Float and then you can write myfirststuff whatever = if whatever then Tag0 1 else Tag1 1.0 myotherstuff (Tag0 thingie) = (fromInteger thingie) + 1.5 myotherstuff (Tag1 thingie) = thingie + 1.5 Then the type checker will happily infer that myfirststuff :: Bool -> Thingie and myotherstuff :: Thingie -> Float So you indeed have to express your tags a bit differently. Is this asking too much? Is that so inconvient, especially when you get a good documention of your intentions for free? - Dirk From salvadorindali at gmx.de Sat Nov 29 21:48:20 2003 From: salvadorindali at gmx.de (Sven) Date: Sun, 30 Nov 2003 02:48:20 +0000 (UTC) Subject: list: from 2 to 3 dimensions..looking for a nice way References: Message-ID: > So why *do* you want a triply-nested list? I got values from a db in this way -> [[id, date, value1, value2, value...],[id,date,value1,value2,value..],...] I'd like to group the arrays if they have the same id and the date is nearby(+-1 sec) to one array(so that they stand for an order)-> [[[],[],[]],[[],[],[]]] I don't mind if it would be these structure {id:[[],[]],id:[[],[]]} but in the end they should be sorted by date From Mike at DeleteThis.Geary.com Fri Nov 21 14:23:19 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Fri, 21 Nov 2003 11:23:19 -0800 Subject: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com> <3FBC2025.B2A33B6F@alcyone.com> <87d6bncbaj.fsf@einstein.electron.net> <3FBD3D6F.E4068821@alcyone.com> <878ymad3ga.fsf@einstein.electron.net> <3FBD6419.A5A863C8@alcyone.com> <874qwyaqqj.fsf@einstein.electron.net> <87znepa954.fsf@einstein.electron.net> Message-ID: Curt wrote: > I'm saying exactly what I said, i.e. that any arbitrary > list upon which one performs an operation which > segregates items into groups according to a specified > criterion is sorted. If you have a list of cows and cats > and dogs, and perform an operation on said list which > groups all the cows together, you have sorted that list > "by cows". This appears to me to be a standard > definition; I have yet to see an argument from you > that would dissuade me from believing this to be > true, but I would love to see it if it exists. Curt, you have a point that in conventional English usage, "sorted" does not necessarily mean "ordered". For example, if you hand me a bag of mixed fruit and ask me to sort the fruit, I won't need to ask you what order to put them in. I will merely separate out the apples, oranges, bananas, pears, and what have you. But you must realize that in the software world, when someone says "sorted" they usually do mean "sorted and ordered". That's why people have been having trouble understanding your point. Even so, you are quite mistaken about the uniq command. It really has nothing to do with the input being sorted at all. Consider this file: up down up up down down down up up up down down This file is not sorted by any definition of the word. Agreed? Now run uniq on it and you'll get this result: up down up down up down As you can see, uniq simply removes consecutive duplicate lines, nothing more and nothing less. It does this whether the file is ordered, sorted, or unsorted. -Mike From pmaupin at speakeasy.net Fri Nov 21 01:16:09 2003 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 20 Nov 2003 22:16:09 -0800 Subject: Reading a Bitstream References: <653b7547.0311181810.786118af@posting.google.com> Message-ID: <653b7547.0311202216.35018dab@posting.google.com> Dietrich Epp wrote: > Maybe I should clarify: I need to read bit fields. Neither are they > aligned to bytes or do they have fixed offsets. In fact, in one part > of the file there is a list of objects which starts with a 9 bit object > type followed by fields whose length and number depend on that object > type, ranging from a dummy 1-bit field to a tuple of four fields of > length 9, 5, 8, and 8 bits. > > I looked at the array module and can't find what I'm looking for. > Here's a bit of typical usage. > > def readStuff(bytes): > bits = BitStream(bytes[2:]) > isSimple = bits.Get(1) > objType = chr(bits.Get(8)) > objType += chr(bits.Get(8)) > objType += chr(bits.Get(8)) > objType += chr(bits.Get(8)) > count = bits.Get(3) > bits.Ignore(5) > if not isSimple: > objId = bits.Get(32) > bytes = bytes[2+bits.PartialBytesRead():] > return bytes, objType > The fact that you want to read bitfields was perfectly clear. What was not clear to me was that you were apparently asking if there was a module which does _exactly_ what you want, and I thought you might be merely asking if there was a more suitable module to build your bitstream code on than the struct module. For this task, IMO struct is unwieldy, and array is much more suitable, because the indexing works very nicely, and it is quick and painless to convert a string into an array. If you need gobs of performance, you may end up writing a C module, but if you need moderate performance, you can probably do better with an array implementation than with a struct implementation, especially if you go ahead and dump an entire file into an array. Here is a module (completely untested, because it's bedtime) which uses array to provide this sort of functionality. I call the primary function "read" instead of "Get" because it's kinda-sorta modelled on a file object. Also, I didn't provide an "Ignore", because all you have to do is call "read" without assigning the results to anything. Hope this helps. Pat """ bitarray class allows reading from a bitstream. The number of requested bits on a read are returned as a positive long integer. Limitations of this implementation: - bitstream is not writable after initialization - Must be initialized with a string (not a list or tuple) - ASSUMES LITTLE-ENDIAN BITSTREAMS - NOT TESTED Any limitation could be fixed with a six pack :) """ import array class bitarray(object): # Support the new Athlon 64's by dynamically # calculating number of bytes per long, # and optimistically assume we'll have 256-bit # processors soon :) _bytesperlong = 32/len(array.array('L',32*' ')) _bitsperlong = _bytesperlong*8 def __init__(self,source_str): self._totalbits = len(source_str) * 8 self._position = 0 # Pad to longword boundary, then make an array source_str += -len(source_str) % self._bytessperlong * chr(0) self._bitstream = array.array('L',source_str) def seek(self,offset,whence=0): self._position = offset + (0,self._position,self._totalbits)[whence] def tell(self): return self._position def read(self,numbits): bitsperlong,position = self._bitsperlong,self._position if position < 0 or position + numbits > self._totalbits: raise IndexError, "Invalid bitarray._position/numbits" longaddress,bitoffset = divmod(position,bitsperlong) # We may read bits in the final word after ones we care # about, so create a mask to remove them later. finalmask = (1L << numbits) - 1 # We may read bits in the first word before the ones we # care about, so bump the total bits to read by this # amount, so we read enough higher-order bits. numbits += bitoffset # Read and concatenate every long which contains a bit we need outval,outshift = 0L,0 while numbits > 0: outval += self._bitstream[longaddress] << outshift longaddress += 1 outshift += bitsperlong numbits -= bitsperlong # numbits is now basically a negative number which tells us # how many bits to back up from our current position. self._position = longaddress*bitsperlong + numbits # Shift right to strip off the low-order bits we # don't want, then 'and' with the mask to strip # off the high-order bits we don't want. return (outval >> bitoffset) & finalmask From joachim.durchholz at web.de Sun Nov 2 06:55:13 2003 From: joachim.durchholz at web.de (Joachim Durchholz) Date: Sun, 02 Nov 2003 12:55:13 +0100 Subject: Python from Wise Guy's Viewpoint In-Reply-To: References: <3F994597.7090807@ps.uni-sb.de> <1j5o61-co2.ln1@ID-7776.user.dfncis.de> <9eso61-mu7.ln1@ID-7776.user.dfncis.de> <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <8yn6gmic.fsf@comcast.net> <1xssqozs.fsf@comcast.net> Message-ID: prunesquallor at comcast.net wrote: > Neel Krishnaswami had a wonderful explanation in article > Sorry, that link doesn't work for me, I don't know the proper syntax for news: links, and I couldn't type one in even if I knew it. Anybody got a full reference? This thread is too long for searching... Regards, Jo From nospam at nospam.yes Mon Nov 24 05:14:32 2003 From: nospam at nospam.yes (Jan knob) Date: Mon, 24 Nov 2003 11:14:32 +0100 Subject: Redirecting Python stdout ,stderr and stdin References: Message-ID: On 24 Nov 2003 02:02:50 +0000, Alexander Schmolck wrote: >"Serge Orlov" writes: > >> "Alexander Schmolck" wrote in message news:yfssmke8vl0.fsf at black132.ex.ac.uk... >> > Jan Knop writes: >> > >> > > Hello >> > > >> > > I am writing a Windows application where I need to redirect stdin, >> > > stdout and stderr from Python. to my application >> > > Is it a simple way of do it ? >> > >> > import sys >> > sys.stdin, sys.stderr, sys.stdout = map(open, 'in.txt err.txt out.txt'.split(), >> > 'r w w'.split()) >> >> That is why map should be deprecated asap ;) >> >> sys.stdin = open("in.txt") >> sys.stdout = open("out.txt","w") >> sys.stderr = open("err.txt","w") > >The obfuscation in the above example was intended not to immediately overwhelm >the OP (who expected having to use some winsock thingy) with simplicitly and >clarity, but now you've spoilt it. > > >'as Hi Actually that what I wat in the end is a method for subsclassing the python stdio's into my application window. This means that Python runs in background with all threes stdio streams redirected . This is I believe somehow done in the Komodo program from ActiveState As far as I have found out You need to define a Input and output class and imlement Read Readline , Write and WriteLine method in these classes. Otherwise it will be necessary to somehow capture the Stdin stdout streams from python console and redirect them . with regards Jan From usenet at soraia.com Sat Nov 22 16:38:37 2003 From: usenet at soraia.com (Joe Francia) Date: Sat, 22 Nov 2003 21:38:37 GMT Subject: newbie - where can i view a python application? In-Reply-To: References: Message-ID: hernandez wrote: > hello all. > is python specific for an especific area? > > what can i do with python? > > thanks for answer 'this kind of questions' !! > http://www.python.org/ is a good place to start, especially the "What is Python?" link in the upper left corner. Peace, Joe From francisgavila at yahoo.com Wed Nov 19 07:52:39 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Wed, 19 Nov 2003 07:52:39 -0500 Subject: Callable generators (PEP 288: Generator Attributes, again) References: <55688f89.0311180211.7ab1bc30@posting.google.com> <2259b0e2.0311180616.5980fabc@posting.google.com> Message-ID: Michele Simionato wrote in message <2259b0e2.0311180616.5980fabc at posting.google.com>... >francisgavila at yahoo.com (Francis Avila) wrote in message news:<55688f89.0311180211.7ab1bc30 at posting.google.com>... > >I looked at that PEP few months ago and I came out with an iterator class. >Here it is: > >"""An object-oriented interface to iterators-generators""" > >class Iterator(object): > """__gen__ is automatically called by __init__, so must have signature > compatibile with __init__. Subclasses should not need to override __init__: > you can do it, but you must do it cooperatively or, at least, ensure that > __gen__ is called correctly and its value assigned to self.iterator. > """ > def __init__(self,*args,**kw): > super(Iterator,self).__init__(*args,**kw) > self.iterator=self.__gen__(*args,**kw) > def __gen__(self,*args,**kw): > "Trivial generator, to be overridden in subclasses" > yield None > def __iter__(self): > return self > def next(self): > return self.iterator.next() > >class MyIterator(Iterator): > def __gen__(self): > self.x=1 > yield self.x # will be changed outside the class > yield self.x > >iterator=MyIterator() > >print iterator.next() >iterator.x=5 >print iterator.next() > >Wrapping the generator in the class, I can pass parameters to it (in >this case x). IOW, here the generator has an explicit "self" rather >than an implicit "__self__" as in the PEP. I am not sure if I like the >PEP, wouldn't be easier to have a built-in iterator class? > Michele Simionato I'm suggesting the PEP's functionality, not its syntax and semantics. My contention is that the PEP regards generators as too class-like, when they are more naturally considered as function-like. For example, your iterator class/instance would look like this: def iterator(x=1)(x): yield x yield x print iterator.next() # -> 1 print iterator(5) # -> 5 The local name "x" is updated (according to the second parameter list in the function definition) right after the yield of the previous call when iterator is called, behaving like a state-persistent callable function. If it's just "nexted", it behaves like a plain old iterator. Here's what the complete example in the PEP would look like (without generator exceptions): def filelike(packagename, appendOrOverwrite) (dat, flush=False): data = [] if appendOrOverwrite == 'w+': data.extend(packages[packagename]) while not flush: data.append(dat) yield None packages[packagename] = data ostream = filelike('mydest','w') ostream.dat = firstdat ostream.dat = firstdat ostream.dat = ('', flush=True) Note that without exceptions, we need to overload the calling interface and call with dummy data, which will never go into the stream. On the other hand, it has a consistent (no "magic attributes") and obvious interface (just look at the first line of its definition). If its called incorrectly, it fails like a function call would, without disturbing the generator. Plus you get default args and keyword args and all that good stuff. Now, It's not as if you can't do any of this without classes--but it's much shorter and less cumbersome, because there's no need to deal with two different namespaces and make sure they're in sync. Here's an efficient reversable generator: def count (n=0)(step=1): while True: yield n n += step c = count() c.next() # 0 c.next() # 1 c(-1) # 0 c.next() # -1 # Now turn it into repeat(): c(0) # -1 c.next() # -1 # And of course n and step can be anything for which n+step makes sense. I was thinking to write an rpn calculator example with these, but for such simple state machines there isn't an appreciable advantage over classes wrapping a generator. Classes are more of a hassle, but not much more. I'll have to find one that's more complex; it may be a hard sell even then, but I just thought I could do better than what the PEP and discussions about it suggested. -- Francis Avila From mikit at zoran.co.il Wed Nov 26 02:28:57 2003 From: mikit at zoran.co.il (Miki Tebeka) Date: 25 Nov 2003 23:28:57 -0800 Subject: import _winreg does not work. How do I fix? References: <%Zewb.11866$sb4.10305@newsread2.news.pas.earthlink.net> <6250403b.0311232335.11757316@posting.google.com> Message-ID: <6250403b.0311252328.49a9ab0e@posting.google.com> Hello John, > Sounds reasonable, but if what you say is true, I am surprised that not > all Python 2.3.2 releases are not equal. > > How good is your information? Is it authorative? It's not authorative. It's experience :-) See Jimmy's mail about OS differences. If you want Python to be the same in all OS's you'll get the lowest common subset of functionality. > I could hack it with a true win32 python, but my gut says this is not > the way to go. You can either write a module that wraps regtool. Another way is to write a C module that does registry work and use SWIG, Boost, ... to make it a Python module. Yet another option is to write the .reg file and let Windows handle it. IMO if runtime is not that important create a winreg module the uses regtool. HTH. Miki. From invalid at hazen.net Mon Nov 24 18:22:40 2003 From: invalid at hazen.net (John Hazen) Date: Mon, 24 Nov 2003 15:22:40 -0800 Subject: Delete common entries between two lists (was dictionaries) In-Reply-To: References: <4Guwb.7197$9O5.6638@fed1read06> <97ba91-169.ln1@dman13.dyndns.org> Message-ID: <20031124232240.GA28929@gate2.hazen.net> * Amy G [2003-11-24 14:40]: > How do I do this same thing but with lists??? > > I apparently have two lists... not dictionaries. > > This is what it prints if I add > print domains_black > > [('YAHOO.COM', 118), ('buildingonline.com', 130), ('canada.com', 95), > ('china.com', 104), ('earthlink.com', 118), ('earthlink.net', 122), > ('email.com', 286), ('excite.com', 200), ('hongkong.com', 110), ('juno.com', > 233), ('lycos.com', 95), ('mail.com', 399), ('minedu.fi', 134), ('msn.com', > 764), ('shaw.ca', 259), ('stderr.windsongnews.com', 88), ('yahoo.ca', 435), > ('yahoo.co.uk', 303), ('yahoo.com.hk', 156), ('yahoo.fr', 266)] > > This is domains_white > > [('aol.com', 17), ('awci.org', 6), ('cox.net', 12), ('hotmail.com', 6), > ('yahoo.com', 11)] > > I want to be left with domains_black = > > [('YAHOO.COM', 118), ('buildingonline.com', 130), ('canada.com', 95), > ('china.com', 104), ('earthlink.com', 118), ('earthlink.net', 122), > ('email.com', 286), ('excite.com', 200), ('hongkong.com', 110), ('juno.com', > 233), ('lycos.com', 95), ('mail.com', 399), ('minedu.fi', 134), ('msn.com', > 764), ('shaw.ca', 259), ('stderr.windsongnews.com', 88), ('yahoo.ca', 435), > ('yahoo.co.uk', 303), ('yahoo.com.hk', 156), ('yahoo.fr', 266)] > > ie. minus the entries in domains_white. Well, it's hard to tell exactly what you want, given that none of the domains in the whitelist are in the original blacklist (and that you didn't answer Derrick's question about whether you want to consider entries equal if just the domain is the same, or do you require the domain and the count to be the same). (Also, I would recommend you normalize all of the domains to lowercase, since case information is not significant to DNS.) Anyway, I would solve the question you're asking with list comprehensions: >>> black = [('yahoo.com',118), ... ('buildingonline.com',130),('foo.bar',100)] >>> white = [('yahoo.com',11),('foo.bar',100)] >>> [x for x in black if x not in white] [('yahoo.com', 118), ('buildingonline.com', 130)] >>> # note the version above only removes entries that have both ... # domain and count equal. ... >>> [x for x in black if x[0] not in [y[0] for y in white]] [('buildingonline.com', 130)] >>> # I think the above is what you want. I think it'll be ... # more readable with an intermediate assignment: ... >>> w = [y[0] for y in white] >>> [x for x in black if x[0] not in w] [('buildingonline.com', 130)] >>> HTH- John -- @ From aleax at aleax.it Tue Nov 18 04:04:15 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 18 Nov 2003 09:04:15 GMT Subject: syntax philosophy References: Message-ID: Tuang wrote: ... > $dict{$color}++ > > to count up what you find. The first time that line is called, it > creates the dictionary, then creates a key for $color, initializes its > value to zero, then increments it to 1. Right: it does a lot of different things depending on context. Python tends to avoid context-dependency while Perl tends to use it with enthusiasm. > This is a very common data analysis problem. It's the SQL database > operation of GROUP BY and then returning COUNT, but applied to any > sequence. histogram = dict([ (value,seq.count(value)) for value in sets.Set(seq) ]) is a higher-order expression of the same concept. Not quite as fast as the lower-level expression, because each .count step is a separate loop over seq, but sometimes one prefers abstraction and concision to speed. When speed IS preferred, being just a tad more explicit: histogram = {} for value in seq: histogram[value] = 1 + histogram.get(value, 0) doesn't seem all that big a deal to me -- basically, you just have to initialize the histogram to be the empty dictionary (no implicit creation!) and be explicit about using 0 as "previous mapping" for values that are not keys in the histogram yet. I know that Raymond Hettinger considers bags (aka multisets) just as fundamental as sets (which he's laboring to make built-ins in the future 2.4 release), so there may be a histogram.add(value) if he has his way -- but you still will have to initialize histogram (to a bag, in that case). Python will never second-guess you in terms of "oh he's using it as a [set/bag/dict/list], and it doesn't exist, so I'll just create a [whatever type] instance on the fly". > But I may be misunderstanding Python's philosophy a bit. I'm surprised > that value++ has to be spelled out as value = value+1, too, so I'm not value += 1 is preferred these days. But in the histogram case, there is no previous "value" to increment, and guesstimating to insert a 0 there just isn't Python's way. > quite sure that I understand the philosophy. There is an ideal about "only one obvious way to do it", just as, in C (per the Rationale to the C standard) there is an ideal to "provide only one way to do an operation". So, having both value++ and value += 1 should never happen (though in C it did: ideals are ideals, the real world is sometimes messier:-). Perl's enthusiastic abundance of multiple ways to perform each task is a very different philosophy. > I agree for word frequency, but not for something as general as GROUP > BY and (some operation, such as COUNT or SUM). Maybe using some of the > functional programming constructs of Python (before they're removed in > Python 3) would be the way to build my own. List comprehensions (which Python copied from Haskell) are the key FP construct in Python, and far from being removed they're growing (with genexp's coming in 2.4 -- they're "lazy", like Haskell's LCs). A more general GROUP BY (dict of lists) is built by: histogram = {} for value in seq: histogram.setdefault(f(value), []).append(value) where f(...) represents the grouping -- e.g., to group by the value of an attribute x.key of each item x, histogram.setdefault(x.key, []).append(x) or if you want the higher-order abstraction, histogram = dict([ (key, [y for y in seq if y.key==key] ) for key in sets.Set( [x.key for x in seq] ) ]) Alex From cbrown at metservice.com Wed Nov 12 14:43:22 2003 From: cbrown at metservice.com (Colin Brown) Date: Thu, 13 Nov 2003 08:43:22 +1300 Subject: socket's strange behavior with subprocesses References: Message-ID: <3fb28c56$1@news.iconz.co.nz> "Jane Austine" wrote in message news:ba1e306f.0311120837.6e6eddf2 at posting.google.com... > Running Python 2.3 on Win XP > > It seems like socket is working interdependently with subprocesses of > the process which created socket. > and the server side tries to close the socket: ..... > Alas, the client side doesn't wake up! It doesn't wake up unless the > notepad is exited first; only after that, 'Connection reset by peer' > is raised. What does the socket has to do with subprocesses? Hi Jane I think it may be tied up with the way subprocesses are made under Windows. Below is a copy of part of a post I made some months back when inexplicable file-locking was causing me problems. It took me weeks to track down the reason. The Python default subprocess inherits open handles from the parent. Your options are: 1. Open the subprocess before the socket. 2. Create the subprocess using win32 API primitives (this is what I had to do). Let me know if want details. Colin Brown PyNZ ---------------------------------------------------------------------------- ------ I have been struggling to solve why an occasional "Permission Denied" error popped up from the following code fragment in one of my Win2K program threads: ... input_file = preprocess(raw_file) os.system('third_party input_file output_file > error_file') if os.path.exists(saved_file): os.remove(saved_file) os.rename(input_file,saved_file) ... The error occurs on the os.rename(). The third_party executable was closing input_file before terminating and anyway the subshell process has finished before the os.rename is called! Most baffling. With the aid of handle.exe from www.sysinternals.com I finally resolved the problem. To see the problem at first hand try the following script: import time, thread, os def rm(file): print 'delete x.x' os.remove(file) def wait(): if os.name == 'nt': os.system('pause') elif os.name == 'posix': os.system('sleep 3') print 'end wait' print 'create x.x' f = open('x.x','w') thread.start_new_thread(wait,()) time.sleep(1) print '\nclose x.x' f.close() rm('x.x') Although this works fine on Linux, I get a Permission Denied error on Windows. I surmise that an os.system call uses a C fork to create the subshell - an exact duplicate of the current process environment including OPEN FILE HANDLES. Because the os.system call has not returned before the os.remove is called a "Permission Denied" error occurs. Quite simple really. Now going back to my original problem, I had other threads doing os.system calls. When one of these calls happens during the preprocess file write of my above thread AND takes longer to complete than the os.system call in the above thread then the file will still be open and the os.rename will return the Permission Denied error. From phil_nospam_schmidt at yahoo.com Tue Nov 18 13:38:34 2003 From: phil_nospam_schmidt at yahoo.com (Phil Schmidt) Date: 18 Nov 2003 10:38:34 -0800 Subject: Making a maze.... References: <1PSsb.44675$jy.34613@clgrps13> <221e7b06.0311170946.3baaa2ca@posting.google.com> Message-ID: <221e7b06.0311181038.65348fab@posting.google.com> "Georgy Pruss" wrote in message news:... > Couldn't resist either :-) > > < -snip code- > Hey, that's very pretty too! Very cool! Would you care to explain the algorithm? Sure, I can read your references, or reverse-engineer it, but I'll have to save that exercise for later, when I have some more time. I want immediate gratification! ;) I like the ASCII and HTML generation too. Thanks for the entertainment! (So, who's gonna tackle the hexagonal maze?) From noemail at noemail4u.com Mon Nov 3 15:14:15 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Mon, 03 Nov 2003 20:14:15 GMT Subject: programming languages (etc) "web popularity" fun References: <3d06fae9.0310310915.4447d4ca@posting.google.com> <9Zzob.75517$e5.2773519@news1.tin.it> <2531b4fb3a153253e29f8a74f733aef1@news.teranews.com> <3FA68205.636ED781@engcorp.com> Message-ID: <7433c90b9d6a866ceaabce31235cfb59@news.teranews.com> On Mon, 03 Nov 2003 11:27:49 -0500, Peter Hansen wrote: >Dang Griffith wrote: >> >> On Sat, 01 Nov 2003 00:53:17 -0000, claird at lairds.com (Cameron Laird) >> wrote: >> >> >Note, too, that the Python one hasn't been on the street >> >as long as some of the others. It's reasonable to specu- >> >late that the ratios haven't equilibrated yet. >> >> Not sure I understand your comment. >> Python predates Java. >> --dang > >I'm sure Cameron is quite aware of that, and yet your comment >does nothing to invalidate his statement. Surely you can accept >that "Python hasn't been on the street as long as *some* of >the others" (emphasis added), can't you? > >-Peter I definitely accept that--I had glossed over the 'in a nutshell' portion of Alex' post, and thought the comment was about the language's popularity, not the nutshell books. Apologies for my confusion infusion, hopefully, now defused. --dang From aleax at aleax.it Sun Nov 2 14:35:59 2003 From: aleax at aleax.it (Alex Martelli) Date: Sun, 02 Nov 2003 19:35:59 GMT Subject: Textbox with ScrollBar References: Message-ID: PythonRAD wrote: > Hi at all, > > I looking for the widget that admit the multiline with scrollbar for > Tkinter... any idea? Top of p. 349 in "Python in a Nutshell" chapter 16. I'm biased, but I think the Nutshell can be useful. You can read it online for free for 2 weeks by subscribing to safari.oreilly.com -- the first 2 weeks are free, but make sure to cancel within 14 days to avoid paying! Still, in 2 weeks you should easily be able to study all of chapter 16 and a lot more besides. Alex From newsgroups at jhrothjr.com Fri Nov 14 18:40:03 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 14 Nov 2003 18:40:03 -0500 Subject: for what are for/while else clauses References: Message-ID: "JCM" wrote in message news:bp3ej3$n35$1 at fred.mathworks.com... > John Roth wrote: > > > "JCM" wrote in message > > news:bp3bmg$l3$1 at fred.mathworks.com... > >> John Roth wrote: > >> ... > >> > Yep. It's one of the three termination conditions for a loop. > >> > >> What are the three conditions? I know of two: > >> > >> 1 Reaching the end of the iteration > >> 2 Breaking out > > 3. Not executing at all. > > I see that as an example of #1. But it isn't. See what your code looks like with an empty file, for example. Or even worse, see what it would look like if you have to use a generator where you can't test for an empty sequence. John Roth From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Wed Nov 26 13:07:50 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Wed, 26 Nov 2003 21:07:50 +0300 Subject: polymorphism in python In-Reply-To: References: <6bWwb.40604$Fv8.39489@twister01.bloor.is.net.cable.rogers.com> Message-ID: Jay O'Connor wrote: > martin z wrote: > "Function overloading" is still one form of polymorphism. I'm not completly agree. Indeed, dispatching on arguments' types can be regarded as polymorphism. However, OP needed to dispatch on *number* of parameters that seems like classic overloading IMHO regards, anton. From larry_Goodman at yahoo.com Tue Nov 25 20:37:12 2003 From: larry_Goodman at yahoo.com (Larry goodman) Date: Tue, 25 Nov 2003 20:37:12 -0500 Subject: ZODB and python 2.3 References: <5777svgdl2kchbvg8idbm8kdefoan88o9j@4ax.com> Message-ID: im looking at the ZODB documentation and I Ran across this: "The Persistent base class is an ExtensionClass class. As a result, it not compatible with new-style classes or types in Python 2.2 and up." Does this mean ZODB wont work with python 2.3? From martin at v.loewis.de Thu Nov 20 15:10:39 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 20 Nov 2003 21:10:39 +0100 Subject: minidom questions References: Message-ID: xtian at toysinabag.com (xtian) writes: > Is this a bug? It's a bug. The attribute value should be an empty string. > I can see how to get what I want by > replacing Element.writexml with one that checks to see whether all the > childNodes are text. Is there a better way to do this? Replacing methods in classes is certainly not a good thing. What you *really* should do is to write your own traversal function which does the saving of the document. For example, you could use the PyXML xml.dom.ext.Printer module, and subclass the PrinterVisitor (if you don't want to write the traversal from scratch). If you really think you should only replace a single toxml implementation on elements, you could use extended elements. To do so, inherit from the Element class, redefining toxml, from the Document class, redefining createElement, and from the DOMImplementation class, redefining createDocument. HTH, Martin From stephendotboulet at motorola_._com Wed Nov 12 12:03:22 2003 From: stephendotboulet at motorola_._com (Stephen Boulet) Date: Wed, 12 Nov 2003 11:03:22 -0600 Subject: First Impressions of Linux GUI Programming In-Reply-To: <8a27e309.0311120842.2d873a60@posting.google.com> References: <8a27e309.0311120842.2d873a60@posting.google.com> Message-ID: R.Marquez wrote: > Now, if I could only figure out a way to interact with my utility from > Konqueror or Nautilus, as the "Send to" feature of Windows Explorer > allows, I will be even happier. ;) Thanks to all you coders that have > given us such great tools under such liberal licenses. Under Konqueror go under settings. You can map your file associations, and have multiple associations for a file type. Type in "py" as file type. Stephen From ot at matrix-vision.de Fri Nov 14 03:12:37 2003 From: ot at matrix-vision.de (Oliver Tengler) Date: 14 Nov 2003 00:12:37 -0800 Subject: SWIG: Tie lifetime of object to a result Message-ID: <6351ca36.0311140012.368a48d5@posting.google.com> Hi, I wrap the following code with SWIG: class Bar {}; class Foo { public: const Bar* getBar() { return &m_bar; } Bar m_bar; }; 'Foo::getBar' returns an internal reference to 'Bar' that is only valid as long as 'Foo' is existing. This raises a problem I am not able to solve using SWIG: >>> f = mod.Foo() >>> b = f.getBar() >>> del f After these lines 'b' is a dangeling pointer because 'f' has been deleted. My question is: How can I tie the lifetime of 'Foo' to that of 'Bar' ? Boost.Python has a special keyword to solve this problem ("return_internal_reference"). Please give me some hints how to solve this using SWIG. I already worked through the SWIG documentation and asked google but with no results. Thanks ! Regards, Oliver Tengler From bucodi at ahoo.fr Tue Nov 25 07:54:23 2003 From: bucodi at ahoo.fr (Rony) Date: Tue, 25 Nov 2003 13:54:23 +0100 Subject: Running another application from within Python References: <1069761289.460134@ananke.eclipse.net.uk> Message-ID: Peter Sparkes wrote: > Please, how do I run another application from within Python > > Regards > > Peter Sparkes > > Have a look at the os module, it may contain what you need. Rony From ramen at lackingtalent.com Wed Nov 12 15:27:14 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 12 Nov 2003 20:27:14 -0000 Subject: Linux security: mixing assignment with expression Message-ID: Hey folks, I was just reading about the attempt to insert a backdoor into the Linux kernel. You can read the details here: http://kerneltrap.org/node/view/1584 This is the code that the attacker inserted: if ((options == (__WCLONE|__WALL)) && (current->uid = 0)) retval = -EINVAL; Notice the "current->uid = 0" expression? I think it's pretty clear that the intent was to confuse the reader, to make the above code appear like it's doing a comparison, when actually it is assigning 0 to the user ID (0 being the root user). In this case, the ability to mix assignment with expression in C not only affected readability but--as a result--security. I think this clearly lends credibility to Guido's design decision to deliberately prevent this sort of "mistake". -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From mwh at python.net Fri Nov 21 12:04:21 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 21 Nov 2003 17:04:21 GMT Subject: Getting the super class via the super() function References: <63esrvs5prp0i5f27dtrlstgase1ubl8em@4ax.com> Message-ID: Fernando Rodriguez writes: > Hi, > > I need to traverse the methods defined in a class and its superclasses. This > is the code I'm using: [...] > What am I doing wrong? I'm afraid that super isn't returning a > reference to the superclass... :-? That's right, it's not. Python supports multiple inheritance -- what is *the* superclass? For new-style classes you're probably best off just looking through cls.__mro__. Cheers, mwh -- That's why the smartest companies use Common Lisp, but lie about it so all their competitors think Lisp is slow and C++ is fast. (This rumor has, however, gotten a little out of hand. :) -- Erik Naggum, comp.lang.lisp From claird at lairds.com Sat Nov 8 19:48:23 2003 From: claird at lairds.com (Cameron Laird) Date: Sun, 09 Nov 2003 00:48:23 -0000 Subject: displaying properly formatted output of ipconfig.exe References: <601be7f8.0311081449.24b3f7e2@posting.google.com> Message-ID: In article , Francis Avila wrote: > >"Joe Flynt" wrote in message >news:601be7f8.0311081449.24b3f7e2 at posting.google.com... . . . >> cmdpipe = os.popen("ipconfig","r") >> lines = cmdpipe.readlines() >> print lines > >You don't want to print a list of strings, you want to print each string in >a list.... > > lines = cmdpipe.readlines() >- print lines >+ for line in lines: >+ print line . . . OR perhaps you want simply to print the output: - lines = cmdpipe.readlines() - for line in lines: - print line + print cmdpipe.read() (There are other alternatives; these are likely to be of most interest.) -- Cameron Laird Business: http://www.Phaseit.net From adalke at mindspring.com Thu Nov 20 00:02:58 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 20 Nov 2003 05:02:58 GMT Subject: Python's simplicity philosophy References: <3FAC19F0.284DCB03@alcyone.com> <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <7xoevcf1u2.fsf@ruckus.brouhaha.com> <7xznesm1l8.fsf@ruckus.brouhaha.com> <7xznerrgx3.fsf@ruckus.brouhaha.com> Message-ID: <6WXub.6689$sb4.3133@newsread2.news.pas.earthlink.net> Me: > > And I've used what can now be written as > > > > unique_keys = dict.from_keys(lst).keys() Paul Rubin: > This from_keys operation must be something new, and consing up a > dictionary like that is a woeful amount of overhead. But I guess > it would do the job. Hmm, I misspelled it -- should be 'fromkeys' without the underscore. Got confused with 'has_key'.... It's a new class method for dict fromkeys(...) dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. v defaults to None. I said 'what can now be written as' meaning that before the class method I would write it as d = {} for x in lst: d[x] = 1 unique_keys = d.keys() I don't know what you mean by 'consing up a dictionary' taking up a 'woeful amount of overhead'. It's a bit of overhead, but not woefully so. (And what does 'consing' mean? It's a Lisp thing, yes? A 'cons cell' is the first / rest pair?) BTW, another option is unique_keys = list(sets.Set(lst)) but I still haven't internalized the sets module enough to remember it trippingly. For the case where I want a list of unique keys and where I don't care about the resulting order then either of these should work nicely. Andrew dalke at dalkescientific.com From claird at lairds.com Sun Nov 9 09:40:05 2003 From: claird at lairds.com (Cameron Laird) Date: Sun, 09 Nov 2003 14:40:05 -0000 Subject: Get more from Google (was: programming languages (etc) "web popularity" fun) References: <9Vvob.74272$e5.2721707@news1.tin.it> Message-ID: In article , Skip Montanaro wrote: > > Cameron> Alex Martelli wrote: > >> "Google Hacks" ... GET IT! > > Cameron> Also . > >The difference being? Since they are approximately the same length, "Google >Pocket Guide" is probably not a "Cliff Notes" version of "Google Hacks". > >Skip > > *Google Pocket Guide* is for civilians, *Google Hacks* for programmers. comp.lang.python readers might well want both; for our purposes, there's little redundancy between the two. -- Cameron Laird Business: http://www.Phaseit.net From not.available at na.no Tue Nov 4 15:46:06 2003 From: not.available at na.no (Noen) Date: Tue, 04 Nov 2003 20:46:06 GMT Subject: XORing long strings opimization? In-Reply-To: References: <3ISpb.24447$BD3.4566933@juliett.dax.net> Message-ID: Peter Otten wrote: > Noen wrote: > > >>Oh, didnt notice that as I wrote it. Thanks... >>Anyway, this is how it should be. >> >>def XOR(s1,s2): >> """ XOR string s1 with s2 """ >> output = "" >> # Argument check >> if (type(s1) and type(s2)) != type(""): >> raise TypeError, "Arguments are not strings" >> if len(s1) != len(s2): >> raise ValueError, "Size differs in strings" >> # Xoring >> for i in range(len(s1)): >> output += chr(ord(s1[i]) ^ ord(s2[i])) >> return output > > > Oops, I missed one: > > >>>>xor2.XOR(1, "") > > Traceback (most recent call last): > File "", line 1, in ? > File "xor2.py", line 7, in XOR > if len(s1) != len(s2): > TypeError: len() of unsized object > > Did you expect this? > > Peter nope, thought the Argument check would do it, but I used and opeartor instead of or. Well, here is XOR v.0.3b :P Any comments how to make it faster? def XOR(s1,s2): """ XOR string s1 with s2 """ output = "" # Argument check if (type(s1) or type(s2)) != type(""): raise TypeError, "Arguments are not strings" if len(s1) != len(s2): raise ValueError, "Size differs in strings" # Xoring for i in range(len(s1)): output += chr(ord(s1[i]) ^ ord(s2[i])) return output From roybrew at att.net Tue Nov 25 11:36:27 2003 From: roybrew at att.net (Roy H. Berger) Date: 25 Nov 2003 08:36:27 -0800 Subject: Subclassing ConfigParser question Message-ID: If I want to subclass ConfigParser and changed the optionxform method to not return things in lower case wouldn't I just need the following code in my subclasss module? from ConfigParser import * class MyConfigParser(ConfigParser): def __init__(self, defaults=None): ConfigParser.__init__(self, defaults) def optionxform (self, optionstr): return optionstr Or do I need to re-implement all of the methods of ConfigParser? Sorry -- haven't done much subclassing with python. Thanks in advance. Roy roybrew at att.net From amy-g-art at cox.net Mon Nov 24 17:33:27 2003 From: amy-g-art at cox.net (Amy G) Date: Mon, 24 Nov 2003 14:33:27 -0800 Subject: Delete common entries between two dictionaries References: <4Guwb.7197$9O5.6638@fed1read06> <97ba91-169.ln1@dman13.dyndns.org> Message-ID: How do I do this same thing but with lists??? I apparently have two lists... not dictionaries. This is what it prints if I add print domains_black [('YAHOO.COM', 118), ('buildingonline.com', 130), ('canada.com', 95), ('china.com', 104), ('earthlink.com', 118), ('earthlink.net', 122), ('email.com', 286), ('excite.com', 200), ('hongkong.com', 110), ('juno.com', 233), ('lycos.com', 95), ('mail.com', 399), ('minedu.fi', 134), ('msn.com', 764), ('shaw.ca', 259), ('stderr.windsongnews.com', 88), ('yahoo.ca', 435), ('yahoo.co.uk', 303), ('yahoo.com.hk', 156), ('yahoo.fr', 266)] This is domains_white [('aol.com', 17), ('awci.org', 6), ('cox.net', 12), ('hotmail.com', 6), ('yahoo.com', 11)] I want to be left with domains_black = [('YAHOO.COM', 118), ('buildingonline.com', 130), ('canada.com', 95), ('china.com', 104), ('earthlink.com', 118), ('earthlink.net', 122), ('email.com', 286), ('excite.com', 200), ('hongkong.com', 110), ('juno.com', 233), ('lycos.com', 95), ('mail.com', 399), ('minedu.fi', 134), ('msn.com', 764), ('shaw.ca', 259), ('stderr.windsongnews.com', 88), ('yahoo.ca', 435), ('yahoo.co.uk', 303), ('yahoo.com.hk', 156), ('yahoo.fr', 266)] ie. minus the entries in domains_white. Thanks again guys. AMY "Derrick 'dman' Hudson" wrote in message news:97ba91-169.ln1 at dman13.dyndns.org... > On Mon, 24 Nov 2003 13:24:17 -0800, Amy G wrote: > > I have received such good help on this message board. I wonder if I > > might not get a little more help from you on this. > > > > I am at the point where I have two dictionaries, with information of > > a domain and a frequency of that domain. > > > > Now that I have the two, I want to delete each entry from one that > > the two have in common, leaving only those that are unique to the > > dictionary? > > This would be great for sets, if a set adequately models your data. > (with two sets, this would simply be (s1-(s1&s2))) > > > Say I have a dictionary called domains_black and another > > domains_white... > > Did you want to define equality by key or by (key, value) pair? > > for key in domains_white.keys() : > if key in domains_black: del domains_black[key] > > for key in domains_white.keys() : > if key in domains_black and domains_white[key] == domains_black[key] : > del domains_black[key] > > -D > > -- > He who scorns instruction will pay for it, > but he who respects a command is rewarded. > Proverbs 13:13 > > www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From reply.in.the.newsgroup at my.address.is.invalid Mon Nov 3 15:26:03 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 03 Nov 2003 21:26:03 +0100 Subject: Does python always need to compile ENTIRE program before it can start to run it??? References: Message-ID: <1aedqvc494mggdfa5fahgdcijm9bsl23rg@4ax.com> Christian Seberino: >I can achieve something similar to Python's automatic compilation >in C/C++ by making a script that compiles and runs my program like this: > >make ; myprogram >From what I remember when I programmed in C, this would start a recursive include file dependency check that, 10 minutes later, usually decided to recompile the whole tree. -- Ren? Pijlman From logan at phreaker.nospam Tue Nov 25 21:51:36 2003 From: logan at phreaker.nospam (Logan) Date: Wed, 26 Nov 2003 03:51:36 +0100 Subject: HOWTO: Python 2.3 on Fedora Core 1 Linux Message-ID: Several people asked me for the following HOWTO, so I decided to post it here (though it is still very 'alpha' and might contain many (?) mistakes; didn't test what I wrote, but wrote it - more or less - during my own installation of Python 2.3 on Fedora Core 1 Linux for a friend of mine). Anyway, HTH, L. HOWTO: Install a separate Python 2.3.2 on Fedora Core 1 Linux without removing the preinstalled Python 2.2.3 which is needed by many of the Fedora/RedHat configuration scripts. Table of Contents: I. Some reasons for doing this II. Warning III. Dependencies IV. About the 'new' Python V. Installation - Installing Tcl/Tk 8.4 - Installing Python 2.3.2 (final) - Installing the libxml2/libxslt Python bindings - Installing PyGTK (Python bindings for GTK+ 2.x) - Installing wxPython with wxGTK (Python bindings for wxWindows) VI. Test the Installation Appendix A: Python Installation with Tkinter - edit: Modules/Setup.dist ========================================================================= I. Some reasons for doing this: (1) You want to use Python 2.3. (2) Python 2.2 (as preinstalled by Fedora) is a mess; e.g. Tkinter (as provided by Fedora) does not work (UCS-2/UCS-4 problem with Python - Tkinter - Tcl/Tk). (3) Python 2.2 (as preinstalled by Fedora) uses a lot of 3rd party packages (s. /usr/lib/python2.2/site-packages). Installing newer or older (sometimes necessary) versions of these packages can cause trouble with the Fedora/RedHat configuration scripts. Some other 3rd party packages might also have or cause problems with one or more of the preinstalled packages (e.g. XML stuff). (4) You want to know exactly what kind of Python (compiler options) and which 3rd party packages you are using. (5) etc. etc. :-) ========================================================================= II. Warning: Be aware that it is always risky to install new software; maybe you will destroy your whole system, loose data etc. This document comes with no warranty at all; following the instructions in this document is something you have to do at your own risk! Recommendation: don't follow the instructions in this document but read the documentation which comes with the distributions which are described in this document. (A good reason for doing this: installation procedures are not written in stone but often change with new releases.) ========================================================================= III. Dependencies: Since you will have to compile everything from source, you have to make sure first that all the necessary RPMs for doing this are installed on your system: - gcc, gcc-c++ (C/C++ compiler) - XFree86-devel - libxml2(-devel), libxslt(-devel) if you want to use libxml2/libxslt - ... (?) Use 'rpm -qi ...' to check this. ========================================================================= IV. About the 'new' Python: On Fedora, Python is installed in /usr/bin, /usr/lib etc. The same holds e.g. for Tcl/Tk (which is needed by Tkinter) etc. etc. So what you can do is: install the new Python (and related stuff) in the /usr/local/bin, /usr/local/lib etc. branch. The only problem is that you will end up with two 'python' commands (one in /usr/bin for Fedora's Python 2.2 and one in /usr/local/bin for the new Python 2.3). You have to delete the one in /usr/local/bin and use a tiny start-up script 'py' instead (s. further below). ========================================================================= V. Installation: Installing Tcl/Tk 8.4: ---------------------- Fedora Core 1 comes with Tcl/Tk 8.3 (actually: 8.3.5). If you want to use Tkinter with your new python, I recommend to install Tcl/Tk 8.4 first (in the /usr/local branch, where everything related to the new Python goes). tarballs: tcl8.4.4-src.tar.gz, tk8.4.4-src.tar.gz - get the above tarballs from http://www.tcl.tk and untar them with 'tar -xzf tcl8.4.4-src.tar.gz' resp. 'tar -xzf tk8.4.4-src.tar.gz' - change (cd) to the 'unix' subdir of the newly created dir with the Tcl distribution and do the usual: ./configure make make install - change (cd) to the 'unix' subdir of the newly created dir with the Tk distribution and do the usual: ./configure make make install (The above will install Tcl/Tk in /usr/local/lib etc.) Installing Python 2.3.2 (final) ------------------------------- tarball: Python-2.3.2.tgz - get the above tarball from http://www.python.org and untar it - if you want to use Tkinter, edit the file 'Setup.dist' in the subdir 'Modules' of the newly created dir with the Python distribution (see Appendix A for details) - type: LD_LIBRARY_PATH=/usr/local/lib export LD_LIBRARY_PATH (Otherwise, lbitk8.4.so in /usr/local/lib will not be found by 'make'.) - type (in the newly created directory with the Python distribution): ./configure make make install - remove (rm) /usr/local/bin/python (Otherwise /usr/bin/python (Python 2.2!) will not work any more.) - now you will need a start-up script for Python; create a file /usr/local/bin/py with the following content: #!/bin/bash LD_LIBRARY_PATH=/usr/local/lib export LD_LIBRARY_PATH /usr/local/bin/python2.3 $1 $2 $3 $4 $5 $6 $7 $8 $9 (This is necessary, because Python - when invoked via 'python2.3' does not find libtk8.4.so otherwise.) (You could also use LD_LIBRARY_PATH permanently (not recommended), use a symbolic link in /usr/lib or use 'ldconfig'; but the above solution works as long as you start your Python scripts with 'py ' and not via the shebang line #!/usr/bin/env python; (you can still use the shebang line #!/usr/bin/env py).) Installing the libxml2/libxslt Python bindings ---------------------------------------------- (This is clearly optional; I use them all the time, thus they are in this document.) tarball: libxml2-python-2.5.11.tar.gz (The version must *exactly* match the version of the installed libxml2 library; check this with 'rpm -qi libxml2'.) - get the above tarball from ftp://xmlsoft.org/python/ and untar it - type (in the newly created directory with the libxml2 distribution): py setup.py install (Important: use 'py' here (and not 'pyhton'); otherwise the package gets installed in the 'site-packages' subdir of Python 2.2 and not in the 'site-packages' subdir of the new Python 2.3.) (The installation will trigger a 'Deprecation' warning: "xmllib should not be used anymore; use xml.sax instead"; simply ignore this.) Installing PyGTK (Python bindings for GTK+ 2.x) ----------------------------------------------- (This is clearly optional; I use it, thus it is in this document.) tarball: pygtk-2.0.0.tar.gz - get the tarball from ftp://ftp.gtk.org/pub/gtk/python/v2.0/ and untar it - type: PYTHON=/usr/local/bin/python2.3 export PYTHON (Otherwise PyGTK goes into the 'site-packages' subdir of Python 2.2 and not in the 'site-packages' subdir of the new Python 2.3.) - type (in the newly created subdir with the PyGTK distribution): ./configure make make install Installing wxPython with wxGTK (Python bindings for wxWindows) -------------------------------------------------------------- (This is clearly optional; I use it, thus it is in this document.) tarball: wxPythonSrc-2.4.2.4.tar.gz (s. furter below for optional tarballs with demos, documentation etc.) - get the tarball from http://www.wxpython.org and untar it - change (cd) to the newliy created directory with the wxPython distribution - type: export WXPREF=/usr/local/lib/wxPython - create a 'build' dir and use it; type: mkdir build cd build - first, we have to install wxGTK, since wxPython uses GTK+ 2.x on Linux; type (we use \ for 'line continuation'; type everything on one line): ../configure --with-gtk \ --prefix=$WXPREF \ --enable-rpath=$WXPREF/lib \ --with-opengl \ --enable-geometry \ --enable-optimise \ --enable-debug_flag \ --with-libjpeg=builtin \ --with-libpng=builtin \ --with-libtiff=builtin \ --with-zlib=builtin \ --enable-gtk2 \ --enable-unicode \ (This will configure wxGTK for GTK 2.x with Unicode. Moreover, some 'builtin' image libraries are used and not the image libraries of your system. See the file 'README.1st.txt' in the distribution for further information.) - type: make make install - now we can install wxPython itself; type (again, type everything on one line (without the '\')): cd ../wxPython py setup.py \ WX_CONFIG=$WXPREF/bin/wx-config \ WXPORT=gtk2 UNICODE=1 \ build install (Use 'py' in the above; not 'python'! That will tell wxPython where to install the package ('site-packages' of Python 2.3) and for which version of Python to build for.) - optionally (but highly recommended): install the wxPython demo (incl. the samples) and the wxWindows documentation: tarballs: wxPythonDemo-2.4.2.4.tar.gz, wxPythonDocs-2.4.2.4.tar.gz - get the tarballs from http://www.wxpython.org and untar them - move (mv) the subdirs of the newly created dir with the demo, samples and docs to /usr/local/lib/wxPython ========================================================================= VI. Test the Installation Open a new console (*not* as user root; old consoles might not find the new commands etc. properly). Then try out the following: - Python 2.2 still OK? start a python shell with 'python' the shell should tell you that you are running Python 2.2 (Under Linux, you can quit a python shell with 'Ctrl-d'.) (You could also try to run one of the 'redhat-config-...' scripts; (depends on which of these scripts are installed on your system).) - Python 2.3 OK? start a python shell with 'py' the shell should tell you that you are running Python 2.3 - libxml2/libxslt Python bindings OK? start a python shell with 'py' type: import libxml2 type: import libxslt both should work without any errors or warnings - Tkinter (Tcl/Tk) OK? type: py /usr/local/lib/python2.3/lib-tk/Tkinter.py a Tk window should open telling you that you are running Tk 8.4 - PyGTK OK? run (with the 'py' command) any of the examples in the subdirs of: /usr/share/doc/pygtk2-2.0.0/examples (e.g.: py /usr/share/doc/pygtk2-2.0.0/examples/pygtk-demo/demos/menu.py should pop up a window with menu examples) - wxPython OK? type: py /usr/local/lib/wxPython/demo/demo.py this should start the wxPython demo ( to view the wxWindows documentation, do the following: type: cd /usr/local/lib/wxPython/docs/ py viewdocs.py ) ========================================================================= Appendix A: Python Installation with Tkinter - edit: Modules/Setup.dist The Modules/Setup.dist file must be modified in the following way: # -- BEGINNING OF CHANGES -- # The _tkinter module. # # The command for _tkinter is long and site specific. Please # uncomment and/or edit those parts as indicated. If you don't have a # specific extension (e.g. Tix or BLT), leave the corresponding line # commented out. (Leave the trailing backslashes in! If you # experience strange errors, you may want to join all uncommented # lines and remove the backslashes -- the backslash interpretation is # done by the shell's "read" command and it may not be implemented on # every system. # *** Always uncomment this (leave the leading underscore in!): _tkinter _tkinter.c tkappinit.c -DWITH_APPINIT \ # *** Uncomment and edit to reflect where your Tcl/Tk libraries are: -L/usr/local/lib \ # *** Uncomment and edit to reflect where your Tcl/Tk headers are: -I/usr/local/include \ # *** Uncomment and edit to reflect where your X11 header files are: -I/usr/X11R6/include \ # *** Or uncomment this for Solaris: # -I/usr/openwin/include \ # *** Uncomment and edit for Tix extension only: # -DWITH_TIX -ltix8.1.8.2 \ # *** Uncomment and edit for BLT extension only: # -DWITH_BLT -I/usr/local/blt/blt8.0-unoff/include -lBLT8.0 \ # *** Uncomment and edit for PIL (TkImaging) extension only: # (See http://www.pythonware.com/products/pil/ for more info) # -DWITH_PIL -I../Extensions/Imaging/libImaging tkImaging.c \ # *** Uncomment and edit for TOGL extension only: # -DWITH_TOGL togl.c \ # *** Uncomment and edit to reflect your Tcl/Tk versions: -ltk8.4 -ltcl8.4 \ # *** Uncomment and edit to reflect where your X11 libraries are: -L/usr/X11R6/lib \ # *** Or uncomment this for Solaris: # -L/usr/openwin/lib \ # *** Uncomment these for TOGL extension only: # -lGL -lGLU -lXext -lXmu \ # *** Uncomment for AIX: # -lld \ # *** Always uncomment this; X11 libraries to link with: -lX11 # -- END OF CHANGES -- -- mailto: logan at phreaker(NoSpam).net From eric.brunel at pragmadev.N0SP4M.com Fri Nov 21 06:09:27 2003 From: eric.brunel at pragmadev.N0SP4M.com (Eric Brunel) Date: Fri, 21 Nov 2003 12:09:27 +0100 Subject: tkinter window geometry References: <3FBD31BC.3070203@wildmail.com> Message-ID: Zora Honey wrote: > I'm trying to get a Tkinter window to open up in the same place on my > screen that I left it the last time I quit the application. To do this, > I simply write the position to a file at "exit" and at startup, I read > the file. Simple enough, but it doesn't work. Oftentimes it's "close", > but over several iterations, the window will wander all over the screen. > In the output below, you can see that the x offset is "off" by +4 each > iteration. Until I move the window. Then x and y are off for one > iteration. Then back to just x. > > Anybody know what the heck is going on here? Window geometry is handled by the window manager you're using, so knowing your platform and your window manager would help. Anyway: [snip script output] > -------Code-------- > from Tkinter import * > > if __name__=="__main__": > def die(): > root.update_idletasks() > newGeometry='+%d+%d' % (root.winfo_x(), root.winfo_y()) That's one problem: you cannot be assured that winfo_rootx() and winfo_rooty() will actually return the same coordinates as geometry() does. AFAICT, the only valid input for geometry() is a former output from geometry(). So I'd do something like: newGeometry = root.geometry() i = newGeometry.find('+') if i != -1: newGeometry = newGeometry[i:] print "out=", newGeometry if newGeometry != geometryConfig: ... root.quit() # Better than a sys.exit(0) > print "out=", newGeometry > if (newGeometry!=geometryConfig): > config=open("alarm.config", 'w') > config.write(newGeometry+'\n') > sys.exit(0) > > root=Tk() > try: > config=open("alarm.config") > geometryConfig=config.readline()[:-1] > config.close() > print "in=", geometryConfig > print "before=,", root.geometry(newGeometry=None) Here, you set the geometry before the root window is actually built. It may be a problem. So I'd pack the button in the window and do an update_idletasks before reading and setting the geometry. I don't know if it will change anything to the behavior you get, but it may make your script more portable. > root.geometry(newGeometry=geometryConfig) > root.update() > print "after=", root.geometry(newGeometry=None) > except : > pass Another (unrelated) problem: if the file alarm.config does not exist, geometryConfig is never set and the die function will crash... And I won't repeat here how much a bad habit it is to use "except:" without an exception type... ;-) > exitb=Button(root, text="Exit", command=die) > exitb.pack(side=LEFT) > > root.mainloop() > Your script with all the modifications I've described works as expected on Linux Mandrake 8 with Python 2.1 and tcl/tk 8.3.4, with the KDE window manager. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From aahz at pythoncraft.com Wed Nov 5 13:55:09 2003 From: aahz at pythoncraft.com (Aahz) Date: 5 Nov 2003 13:55:09 -0500 Subject: prePEP: Decimal data type References: Message-ID: In article , Emile van Sebille wrote: > >The Context still needs to be defined, but Aahz says: >> Context applies only to operations, not to Decimal instances; >> changing the Context does not affect existing instances if >> there are no operations on them. > >...from which I infer that Context exists in part to limit/round >calculated results. Even if it were possible for me, as a user of >Decimal, to set Context appropriately to achieve these ends, what >if I use a library that also changes Context? The integrity of my >calculations may be impacted. That's correct. There needs to be a social convention that libraries intended for use by other people *CANNOT* muck with Context, and if they do so for their own internal calculations, they must save and restore Context. You can probably find additional information about this in Cowlishaw. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From bucodi at ahoo.fr Fri Nov 28 08:39:45 2003 From: bucodi at ahoo.fr (Rony) Date: Fri, 28 Nov 2003 14:39:45 +0100 Subject: Standard way of documenting python code ? Message-ID: A question on python source documentation. Does there exist a standard for documenting code ? I've included here an example generated by pydoc of one of my modules. Is this the right way or is it overkill ? Comments are appreciated Thanks, Rony Help on module sqlquery: NAME sqlquery FILE m:\plymouth\sqlquery.py DESCRIPTION ######################################################################### # Module : sqlquery.py # Abstract : General, simple, SQL class # Contains some simple classes # connection(connectstring): connect to db and define cursor # cmd(command,logflag=None) : execute sql-command # selcmd(dict,logflag=None) : execute select statement # inscmd(dict,logflag=None) : execute insert statement # Dependancies : mylibs.sqlerreur.py # mylibs.string_man.py ######################################################################### CLASSES connection class connection | Connection to odbc source defined in connecstring | Public methods : | - close : close connection | - cmd : execute cmd and return result set | | Methods defined here: | | __init__(self, connectstring) | Create db connection from connectstring | Connect string must have the format 'odbc-source/user' | Will create cursor called self.cursor | | close(self) | Close database connection | | cmd(self, command, logresult=None) | Execute a SQL-statement, returns the resultset als list | if logresult != None then write result in log.txt | | inscmd(self, dict, logresult=None) | Execute a INSERT command. | The command is constructed out of a dictionary (dict) | The dict should contain : | "tocols" : list of destination cols as a string | "tables" : table where to insert as a string | "values" : list of values to insert as a string | Ex : | {'tocols':'AC_ID,AC_NOM', | 'table':'TBL_ACHETEUR', | 'values':'1,'+quote('RONY')} | will create : INSERT INTO TBL_ACHETEUR (AC_ID,AC_NOM) | VALUES(1,'RONY) | If logresult != None then write result in log.txt | Returns nothing | | selcmd(self, dict, logresult=None) | Execute a SELECT command. | The command is constructed out of a dictionary (dict) | The dict should contain : | "cols" : list of cols as a string | "tables" : list of tables as a string | "order" : list of orders as a string | Ex : | {'cols':'AC_ID,AC_NOM', | 'tables':'TBL_ACHETEUR', | 'order':'AC_ID'} | will create : SELECT AC_ID,AC_NOM FROM TBL_ACHETEUR | ORDER BY AC_ID | If logresult != None then write result in log.txt | Returns self.result DATA achtdict = {'cols': 'AC_ID,AC_NOM', 'order': 'AC_NOM', 'tables': 'TBL_... connectstring = 'plymouth/sa/' insachdict = {'tables': 'TBL_TMP', 'tocols': 'TP_ID,TP_NOM', 'values':... -- Rony /_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ / bucodi at yahoo.fr / | www.bucodi.com - My work \ www.ifrance/karamusique -- My hobby \_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ From dont_use at nowhere.com Sat Nov 29 14:56:22 2003 From: dont_use at nowhere.com (Glenn Reed) Date: Sun, 30 Nov 2003 08:56:22 +1300 Subject: ActiveState Python won't call module function. Message-ID: Hi, This is probably a really easy question and I apologize if it is already covered in some faq somewhere. These are my two source files: ------- module1.py ------------- class module2: def __init__(self): self.x=23 self.y=14 self.z=33 self.x1=self.x=3 #thisClass=module2() # I added the above line in just to test it works here and it does. ------- tmod.py --------------- # Test Module import module1 thisClass = module2() ---------------------------------------------- It generates the following error: Traceback (most recent call last): File "C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "C:\My Documents\PythonSrc\Temp\tmod.py", line 4, in ? thisClass = module1() NameError: name 'module2' is not defined >>> I realize I have created a different class name 'module2' to the filename 'module1' but I was thinking at the time the error may be due to a namespace clash between the name of the file and the name of the class or the filename hiding the classname etc. But this has got me stumped and I would appreciate any help on it. Thanks in advance. Glenn. From edreamleo at charter.net Fri Nov 7 20:20:26 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 7 Nov 2003 19:20:26 -0600 Subject: Problems with regexps References: <87fzgz98vh.fsf@internal.daycos.com> Message-ID: I've just added script-based find-changed commands to Leo 4.1 beta 1. So Leo can execute a script to find the next match, and optionally executes a script to do the replacement. This gives Leo the full power of languages like Icon or Snobol, using the plain Python language. There is a dead simple way for the find script to communicate with the change script, and for the find script to continue or not in the case of the Find All or Change All commands. BTW, scripts could search anywhere, not just in a Leo outline. For example, the find script could pull in the found text from any file to any Leo node (creating an outline node if you like). Etc. I'm very excited about this new feature. At long last we are not limited to non-extensible, wimpy tools like re. Fully interactive if you want; fully batch if you want. Undo is easy, etc. The sky is the limit, and when you are done, you will be able to understand the scripts you wrote. End of re. Yeah! Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From claird at lairds.com Sun Nov 30 10:26:08 2003 From: claird at lairds.com (Cameron Laird) Date: Sun, 30 Nov 2003 15:26:08 -0000 Subject: Ques From CS Grad Student References: <3FC66963.2F74392F@engcorp.com> Message-ID: In article , Martin v. L?wis wrote: >Peter Hansen writes: > >> > 1. How many members are involved directly, and how many peripherally? . . . >Likewise, answers for question 1 are also very easy to find, as is >question 4 (actually, once 4 is answered, 1 falls out automatically, >atleast partially). . . . While I'm a leading advocate of the proposition that one can know answers without understanding their cor- responding questions, in this case I don't get either. Give me a hint: what does 1. mean? Here's what *I* suspect is the answer: it's more inter- esting to describe the different categories of pertinent involvement in Python development than to try to quantify them (although I have nothing against doing both). -- Cameron Laird Business: http://www.Phaseit.net From mbabcock at fibrespeed.net Wed Nov 12 12:01:00 2003 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Wed, 12 Nov 2003 12:01:00 -0500 Subject: Python's simplicity philosophy In-Reply-To: References: <2259b0e2.0311112248.3be2d304@posting.google.com> <17lsb.109042$fl1.4548960@twister.southeast.rr.com> Message-ID: <20031112170100.GA32388@godzilla.fibrespeed.net> On Wed, Nov 12, 2003 at 08:28:29AM +0000, Robin Becker wrote: > sequence.sum() > sequence.reduce(operator.add[,init]) > sequence.filter(func) etc etc > > That would make these frighteningly incomprehensible ;) > concepts seem less like functional programming. Personally I wouldn't > like that to happen. I'm hoping you were being sarcastic ... but I get the feeling you aren't. Why, pray-tell, would you want an OO program to do: results = [ func(x) for x in sequence ] ... instead of ... results = sequence.map(func) ?? I can understand if you're writing highly LISP-like Python (see IBM's articles on functional programming with Python for example). However, I don't see the 'harm' in offering functional methods to lists/arrays. Looking at this code I wrote today: matches = [ get_matches(file) for file in duplicates ] todelete = [ get_oldest(files) for files in matches ] ... would end up being ... matches = duplicates.map(get_matches) todelete = matches.map(get_oldest) ... or better ... todelete = duplicates.map(get_matches).map(get_oldest) ... and I somewhat like that as I look at it. -- Michael T. Babcock CTO, FibreSpeed Ltd. (Hosting, Security, Consultation, Database, etc) http://www.fibrespeed.net/~mbabcock/ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 671 bytes Desc: not available URL: From aleax at aleax.it Fri Nov 14 08:10:17 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Nov 2003 13:10:17 GMT Subject: case-sensitivity References: <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> Message-ID: Ron Adam wrote: ... > Maybe someone will try it. I've only just started with Python about a > month ago. However I did pick up your 'Python in a Nutshell' last > night and have already read though the first 4 chapters. Great book > Alex! Thanks! > I've programmed lightly in c, c++, java, several basics, and even a > little assembly. Took a course in fortran, although I don't remember > any of it. Also learned pascal once upon a time. You do have just about the perfect background in term of target audience for the Nutshell -- several varied, typical lower-level languages, plus a smattering of Python. Though one doesn't NEED as many different languages as you've used and studied, of course. > Python addresses many if not most of the complaints I've had with > those other languages. Most of which were either low level languages > that lacked high level functionality, or high level languages that > were difficult to extend. And then there are the visual stuff that > requires 3/4 of the code just to initialize everything. ack! What > surprises me most is why I haven't found Python sooner? Good question; I asked it of myself just a few years ago, when I finally did "find" it. I have no satisfactory answer, though. Alex From stashluk at codem.com Tue Nov 25 14:00:34 2003 From: stashluk at codem.com (stash) Date: 25 Nov 2003 11:00:34 -0800 Subject: swig c binding Message-ID: I have the following struct in my c header file: typedef struct _Foobar { double foo; double bar[3]; } Foobar; I have wrapped it in swig and it appears to have worked... In my python file now: import foobar x = foobar.Foobar() x.foo = 3.14 #works x.bar = (1.2, 2.3, 3.4) #returns an error What have I gotten confused here? I've tried some things with the carrays.i, but didn't really get anywhere. What is the proper syntax? I eventually want to turn x into a byte stream and send it over a serial port. From francisgavila at yahoo.com Mon Nov 10 11:15:31 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 10 Nov 2003 11:15:31 -0500 Subject: __slots__ References: <9d5f9ae4.0311070836.7503de86@posting.google.com> <9d5f9ae4.0311100749.362e8cdf@posting.google.com> Message-ID: "flori" wrote in message news:9d5f9ae4.0311100749.362e8cdf at posting.google.com... > fgrimm at inneo.de (flori) wrote in message news:<9d5f9ae4.0311070836.7503de86 at posting.google.com>... > > i try to greate somthing like this > my question is is their a nicer way to do this? Yes. Don't use slots! Why are you using slots?! -- Francis Avila From peter at engcorp.com Mon Nov 10 17:10:34 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Nov 2003 17:10:34 -0500 Subject: Matrix - Metaphors, Analogies and the REAL References: <3FAFF339.E499F960@engcorp.com> Message-ID: <3FB00CDA.581D19C6@engcorp.com> Scott Chapman wrote: > > If everyone posted their latest advertisement for some pet web site that > happened to be written in python, we'd be flooded with CLEARLY > OFF-TOPIC posts regarding CLEARLY OFF-TOPIC subject matter. At this point, it's unclear whether the web site itself is written in Python. I think the web site is just where Tim posts his Matrix theories, and has no connection to Python. Ah, wait... there's the connection, distant though it is. In some of the posts in that weblog/BBS, Tim talks again about his infamous "VIC" project, which as he points out is implemented in Python now. One more of life's great mysteries solved... -Peter From jfranz at neurokode.com Wed Nov 19 15:17:10 2003 From: jfranz at neurokode.com (Jon Franz) Date: Wed, 19 Nov 2003 15:17:10 -0500 Subject: Fw: Python Database Objects (PDO) 1.2.0 Released Message-ID: <031801c3aeda$1d1b2e50$7401a8c0@voidmk9> ----- Original Message ----- From: "Jon Franz" To: "Serge Orlov" Sent: Wednesday, November 19, 2003 2:39 PM Subject: Re: Python Database Objects (PDO) 1.2.0 Released > > Yes, if the .open() is an generator then it must return a sequence of > items > > but only one at a time. If the loop body doesn't keep the result object > > it will be garbage collected pretty soon. You don't need to return > > a dictionary you can return a special "coupler" object that will bind > > the column description data (created only one time) with the column > > values. Of course, it means one more allocation per row and extra > > references, but I don't really think it's very expensive. After all it is > > idiomatic iteration over a sequence. Without hard data to prove > > that it's really expensive I don't think it's right to say it's expensive. > > Well, it is, hard data following, but first an aside: generators are > something we want to avoid right now, since we support older > versions of python that do not support generators. Thus, older > interpreters would suffer from the memory bloat I've already > described. > > Sorry for the caps below, DB2 uses caps everywhere and I'm just > trying to be correct. > > However, the creation of the mapping object for each result adds up > over time. Coupling objects perform bad as well - I think it has to do > with the sheer # of objects that are created as you loop over the > results - gcing them takes time. > > * Hard data. > I populated the SAMPLE.STAFF table of my DB2 installation with > 5235 records. > I created two methods that grab all records from this table and loop > over them, outputting each field for every record. The regtimer > method used the .next() call, meanwhile the itertimer method > used an generator function to get a mapping object per record. > > Note that this test is not very optimized - for every record I loop > over the .fields member of the Resultset, or in the iterator case, > I loop over the members of the returned mapping object. > The iterator mapping object is a python dictionary - I do no > tricks to provide associated column data - it's just name:value. > 'Coupler' objects were even more expensive, and I didn't want to > lose the use of my test server for too long, so I dropped them > before progressing to the 100 run tests. > > I used the timeit module to call each method 100 times, > and reran the tests 3 times. > Python was restarted in between runs. > Output was identical between the tests. > > regtimer method: 281.4 seconds (avg) > itertimer method: 627.1 seconds (avg) > > Building 5235 * 3 * 100 mapping objects seems very expensive > (even when using an iterator/generator system) versus providing > a mapping-object interface and keeping track of indexes > internally. > > With smaller numbers of records, the difference is less pronounced, > but it's always there. > > > > It may help to quit thinking of a Resultset as a sequence of > dictionaries - > > > PDO explicitly avoids that. > > Isn't it premature optimization? > > Nope, we'd already through about this and investigated it - until you > asked, no one knew that we had. Our older tests showed that memory > bloat was a problem, since we created the mapping objects all > at once, and that performance was horrible. > > the iterator/generator version is faster than our old tests, but is still > slower. > > cheers. > > ~Jon Franz > NeuroKode Labs, LLC > From strombrg at dcs.nac.uci.edu Sat Nov 22 11:26:43 2003 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Sat, 22 Nov 2003 16:26:43 GMT Subject: small program with strange behavior Message-ID: The below small program is giving strange behavior. At the bottom of the code, please find "this works" and "this doesn't work" comments. Why does one work and the other not? TIA. #!/usr/bin/python import string class move_class: bad = 'Invalid initializer' def __init__(self,str,rank_black,rank_white): self.text = str self.children = [] self.rank_black = rank_black self.rank_white = rank_white if str[0:2] == 'B[': #if move_class.prior != '' and move_class.prior != 'W': # raise move_class.bad if str[1:2] != '[' or str[4:5] != ']': raise move_class.bad self.letters = string.lower(str[2:4]) move_class.prior = 'B' self.color = 'B' self.ranks=[rank_black] elif str[0:2] == 'W[': #if move_class.prior != 'B': # raise move_class.bad if str[1:2] != '[' or str[4:5] != ']': raise move_class.bad self.letters = string.lower(str[2:4]) #move_class.prior = 'W' self.color = 'W' self.ranks=[rank_white] else: raise move_class.bad self.strrow = self.letters[0:1] self.strcol = self.letters[1:2] trow = ord(self.strrow) - ord('a') if trow >= 11: trow = trow - 1 self.row = trow tcol = ord(self.strcol) - ord('a') if tcol >= 11: tcol = tcol - 1 self.col = tcol def rotate90(self): size=19 self.row,self.col = self.col,size - self.row - 1 def copy(self): newmove = move_class(self.text,self.rank_black,self.rank_white) return newmove def __str__(self): t = '' for i in self.ranks: t = t + str(i) + ' ' return str(self.row)+','+str(self.col)+' '+str(self.color)+' '+\ t move=move_class('B[qp]',-4,-1) newgame=[move] for r in range(4): for move_no in range(0,len(newgame)): # this doesn't work newmove = newgame[move_no].copy() # this works #newmove = newgame[move_no] newmove.rotate90() newgame[move_no]=newmove print newgame[move_no] From usenet_spam at janc.invalid Mon Nov 3 22:03:06 2003 From: usenet_spam at janc.invalid (JanC) Date: Tue, 04 Nov 2003 03:03:06 GMT Subject: best GUI toolkit for python: tkinter, wxPython or what? References: <87y8uxbntt.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) schreef: > JanC writes: > [...] >> Some people outside of Trolltech are working on a GPL'ed version for >> Win32: >> (This should compile using mingw.) > > Are these people popular with TT? Don't know, I guess not. ;-) But they include several KDE application developers (who want to port their applications), and they don't do anything illegal... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From richie at entrian.com Wed Nov 12 09:53:02 2003 From: richie at entrian.com (Richie Hindle) Date: Wed, 12 Nov 2003 14:53:02 +0000 Subject: asyncore.loop() blocks In-Reply-To: References: Message-ID: [F.G.] > Is there a way to perform other operations while still looping with > asyncore.loop() without spawning a new thread? while something(): asyncore.poll(timeout=0.1) # Or other suitable timeout in seconds doOtherWork() -- Richie Hindle richie at entrian.com From pekka.niiranen at wlanmail.com Tue Nov 11 04:19:00 2003 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Tue, 11 Nov 2003 11:19:00 +0200 Subject: What do you think of this Python logo? In-Reply-To: References: Message-ID: <3fb0a9a9$0$16834$1b6aedd2@news.songnet.fi> Cool, I like it -pekka- Brandon J. Van Every wrote: > What do you think of this Python logo? > http://pythonology.org/logos > Good, bad, indifferent, love it, hate it? > From asp16 at alu.ua.es Mon Nov 24 18:57:13 2003 From: asp16 at alu.ua.es (Adeodato =?iso-8859-1?Q?Sim=F3?=) Date: Tue, 25 Nov 2003 00:57:13 +0100 Subject: Strange import bug In-Reply-To: <3fc2960a@news.iconz.co.nz> References: <3fc2854a$1@news.iconz.co.nz> <3fc2960a@news.iconz.co.nz> Message-ID: <20031124235712.GA5050@chistera> * Colin Brown [Tue, 25 Nov 2003 12:41:52 +1300]: > "Adeodato Sim?" wrote in message > news:mailman.1043.1069714565.702.python-list at python.org... > ... > The first (default) entry in sys.path is '', which means (I think) the > current directory. So sys.path.append('./abc') appends after this entry; > then, on "import abc", python uses first '' entry, which means it looks > under current directory where it finds "abc" which gets imported *as a > module*. > ... > Okay, but why does python not complain when it tries to import the > current directory as a module? I would expect an error, maybe: > "ImportError: xxx is not a valid python module" It doesen't try to import the current directory as a module. If first looks *inside* the current directory for a module named abc (which can be a directory named abc with a __init__.py file inside OR an abc.py file OR an abc.pyc compiled file). So it finds abc, which is a dir but also a *module* because of the __init__.py file, and imports it. > If it is considered a valid python module and is executing it then who > knows what it is doing. -- Adeodato Sim? (a.k.a. thibaut) EM: asp16 [ykwim] alu.ua.es | IM: my_dato [jabber.org] | PK: DA6AE621 Truth is the most valuable thing we have, so let's economize it. -- Mark Twain -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 204 bytes Desc: Digital signature URL: From secchi at sssup.it Thu Nov 27 06:04:18 2003 From: secchi at sssup.it (Angelo Secchi) Date: Thu, 27 Nov 2003 12:04:18 +0100 Subject: Newbie problem Message-ID: <20031127120418.4bb0e7f2.secchi@sssup.it> Hallo, I have the following problem. I'm trying to clean a database whose lines look like: "2/G DM" "HOE" 0 "R5D2" 1 0 0 0 in particular I need to remove the ". Here my code def wash(a) : a=string.replace(a,'"','') return a data=file("prova.txt",'r') data_clean=file("prova_clean.txt",'w') temp_string = data.readline() while len(temp_string) != 0: temp_field=string.split(temp_string,'\t') print temp_field temp_field=map(wash,temp_field) print temp_field data_clean.write(temp_field) temp_string = data.readline() data.close() data_clean.close() Of course I receive an error in line "data_clean.write(temp_field)" saying "TypeError: argument 1 must be string or read-only character buffer, not list". I'm a newbie and reading tutorials around I was not able to find the best solution to my problem. Could anybody help me? I also read in this mailing list that there exists a specific list for newbie (called python tutor mailing list) but I was not able to find it. Any suggestions? Thanks Angelo From kylotan at hotmail.com Tue Nov 25 23:16:48 2003 From: kylotan at hotmail.com (Kylotan) Date: 25 Nov 2003 20:16:48 -0800 Subject: Pychecker under Windows Message-ID: <153fa67.0311252016.2e02b575@posting.google.com> Is there a practical way to use Pychecker in Windows? It doesn't work under IDLE. (In fact, it seems to end up breaking everything, and every subsequent statement and expression I execute gets ignored.) Running it from the Python interpreter in DOS means everything scrolls off the screen. Ideally I'd like to redirect it to a file, or be able to use it in IDLE. -- Ben Sizer From max at cNvOiSsiPoAnMtech.com Mon Nov 3 13:50:53 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Mon, 03 Nov 2003 18:50:53 GMT Subject: pdf2exe trouble Message-ID: I got into some hot waterhere: I have a service writted in Python (py2exe-wrapped) that worked ok with 2.2. I upgraded to 2.3 and got an "IOException bad file descriptor" in a print "something" line. I used 'import trace' at the top of the file and used to be able to see the print statements in win32traceutil window. I uncommented 'import trace' and got the same ting. Does anyone have an idea/advice as to get the print to go to normal trace route or do something else reasonable short of removing the print statements (which is what I basically did)? thanx. max. From mis6 at pitt.edu Tue Nov 11 09:50:56 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 11 Nov 2003 06:50:56 -0800 Subject: make order of function definitions irrelevant References: <87he1beug3.fsf@pobox.com> Message-ID: <2259b0e2.0311110650.2cea16b0@posting.google.com> Joerg Schuster wrote in message news:... > Thank you all, so far. I had asked the question because I am writing a > program that translates linguistic grammars into python functions. The > python functions are supposed to be called by another program of mine > that does regular expression matching. If you wrap all your functions in a class and make them staticmethods, the order of definition does not matter. Is this enough for you? Michele From peter at engcorp.com Mon Nov 24 12:09:26 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Nov 2003 12:09:26 -0500 Subject: Why should input(prompt="hello:") fail? References: <37ba82ff.0311240831.6e0dfba7@posting.google.com> Message-ID: <3FC23B46.8E2BF00B@engcorp.com> zhi wrote: > > Really confused, when I use keyword style argument as following: > > >>> input(prompt="hello") > > Traceback (most recent call last): > File "", line 1, in -toplevel- > input(prompt="hello") > TypeError: input() takes no keyword arguments > > While the library reference says the function is: input( [prompt]) > so, it should work.:( No, it shouldn't. The argument is not shown with a name, so you are supposed to use just a position argument, as in input('hello'). Note however that input() is a poor choice for serious work: you should quickly get past the point of wanting to use it and learn why raw_input() is a better choice. -Peter From nessus at mit.edu Mon Nov 10 18:57:23 2003 From: nessus at mit.edu (Douglas Alan) Date: Mon, 10 Nov 2003 18:57:23 -0500 Subject: What do you think of this Python logo? References: <7dVrb.117193$mZ5.792532@attbi_s54> Message-ID: "Rainer Deyke" writes: > -1. The snake doesn't look like a snake, the globe is gratuitious, and the > typeface looks boring. I think you miss the point. The snake is more simple and elegent than your typical snake, yet it still manages to swallow its own tail. The globe is the iris in it's all-encompassing eye. |>oug From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Nov 8 17:35:33 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 08 Nov 2003 23:35:33 +0100 Subject: Help for unicode In-Reply-To: References: Message-ID: <3fad6fb5$0$58715$e4fe514c@news.xs4all.nl> Noixe wrote: > Why this istruction: > > print u"\u00" + str(41) > > generate an error and this: > > print u"\u0041" no? because they are doing very different things. The first is first evaluating u"\u00" and only if that succeeds (but it doesn't) add the string "41" at the end. The second is evaluating the unicode escape sequence \u0041 that is part of the string. You cannot combine strings like that to form arbitrary unicode escape sequences. Try this instead; some_variable=0x0041 print unichr(some_variable) > Can I use all 65536 symbols of unicode in my program? For example, I need to > use the mathematic symbol of void set. It has a 0198 number in a table of > symbol that there is in Windows. No problem to use all unicode symbols. But I don't think the empty set symbols is Unicode code point U+0198: >>> import unicodedata >>> unicodedata.name(u'\u0198') 'LATIN CAPITAL LETTER K WITH HOOK' >>> unicodedata.lookup("EMPTY SET") u'\u2205' So I think you should use U+2205 instead? --Irmen From bgailer at alum.rpi.edu Sat Nov 22 18:33:02 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 22 Nov 2003 16:33:02 -0700 Subject: update a word-bookmark with the win32.com extension In-Reply-To: <48bafd6d.0311180542.5f7582ea@posting.google.com> References: <48bafd6d.0311180542.5f7582ea@posting.google.com> Message-ID: <6.0.0.22.0.20031122153409.02c68e10@mail.mric.net> At 06:42 AM 11/18/2003, Christian Lehmann wrote: >Hello, > >I want to update a bookmark in a word file. >My code looks like this: > >def UpdateBookmark(BookmarkToUpdate, TextToUse): > FieldRange = Document.Bookmarks(BookmarkToUpdate).Range > FieldRange.Text = TextToUse # error message > ActiveDocument.Bookmarks.Add(BookmarkToUpdate,FieldRange) > > >UpdateBookmark ("Bookmarkname","newString") > > >when i assign the new string an error message occurs. Please include the error message in your postings. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.538 / Virus Database: 333 - Release Date: 11/10/2003 From anthony at interlink.com.au Wed Nov 12 20:44:48 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Thu, 13 Nov 2003 12:44:48 +1100 Subject: looking for a name for a python SIP phone In-Reply-To: Message-ID: <200311130144.hAD1imXS027604@localhost.localdomain> >>> "Robert Brewer" wrote > 3. Piranha Brothers: Palin as Luigi while interviewed at his 'escort > service', answers the phone, saying, "Stumm! Stumm. Yes, the _watch_ > will be ready at midnight. The *watch*. The Chinese 'watch'. OK. So > long... mother." Aha! This will do nicely. I'd forgotten about this one, much to my shame ;) Thanks very muchly. Anthony -- Anthony Baxter It's never too late to have a happy childhood. From newsgroups at jhrothjr.com Sat Nov 1 07:06:58 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 1 Nov 2003 07:06:58 -0500 Subject: global variables ? References: Message-ID: "ruari mactaggart" wrote in message news:bo04ou$382$1 at news8.svr.pol.co.uk... > how do I assign a value to a variable inside a function then use it in the > main body ? > > i am trying to unpickle a dictionary in a function to use it in the program Since Alex has already mentioned the 'global' statement, I won't dwell on it. I'd just mention that it's a whole lot simpler to use a global dictionary or an object instance than to use a simple variable that has to be rebound. For example: foobar = "huh?" def snafu(): global foobar foobar = "what?" Using a dictionary, it looks like this: foodict = {foobar: "huh?"} def snafu(): foodict["foobar"] = "what?" That lets you consolidate all of those messy global variables in one place as well as giving you a name you can use for better internal documentation. John Roth > > ruari > > From j at submersion.com Tue Nov 11 16:10:19 2003 From: j at submersion.com (Jeff Davey) Date: Tue, 11 Nov 2003 21:10:19 GMT Subject: Python 2.3.2 & Netware References: Message-ID: <%ecsb.28908$jy.14367@clgrps13> "Jeff Davey" wrote in message news:SGbsb.28840$jy.14513 at clgrps13... > The new abend I'm getting is a General Protection Fault :), tracking that > one down right now. Will let you know when I figure it out. I have a bunch of printfs going to see what's up, basically, it finished the 'Type' type from _Py_ReadyTypes, and starts into bool... Interesting enough, the printf I have at the end of the PyType_Ready function, gets corrupted (as in, the static string is overwritten by something else) as it finished the 'Type' type. It then proceeds to try and PyType_Ready the bool type, it gets to the bases = Py_BuildValue("(0)", .base); line, inside there it dies: bases = type->tp_bases; if (bases == NULL) { if (bases == NULL) bases = PyTuple_New(0); else bases = Py_BuildValue("0", base); // ABEND is HERE } I was going to keep following, but I've sort of come to the conclusion there's some major memory management problems (overwriting buffers, or something along that way) with getting Python to run on Netware. Now, I'm not sure if it'some setting I shouldn't have enabled in the pyconfig.h, or something else, but I do know that Netware is a LOT pickier than Linux when it comes to memory. Any ideas maybe why I'm having so many problems with Python & Memory Mangament ? Jeff From oest at soetu.eu Thu Nov 13 19:50:13 2003 From: oest at soetu.eu (Carlo v. Dango) Date: Fri, 14 Nov 2003 01:50:13 +0100 Subject: conceiling function calls.. References: Message-ID: Thanks for your reply... Unfortunately, I cannot truly see your suggestions before my eyes.. >> It is possible to conceil access to methods using the "property()" >> function so method access looks like field access.. is the same possible >> for functions (not taking any args... ) > > It's possible as long as the functions are accessed as attributes of > some object -- it may be horrible, but you CAN, if you wish, write a > __getattribute__ for the "some object" to force any access to the > attribute to become a CALL to that attribute. but then I'm forced to use the self pointer.. I want to conceil it. > You could, of course, wrap the function into an object (of the > same name if you wish) that calls it whenever "an attribute of that > name" is accessed (SHUDDER). hmm Im not sure what you are suggesting here. Are you still making use of the self reference? or how would you construct this... please note that it's my purpose to hide the user from whats really going on.. -carlo.. -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From drlinux at columbus.rr.com Wed Nov 26 18:04:21 2003 From: drlinux at columbus.rr.com (Dave Reed) Date: Wed, 26 Nov 2003 18:04:21 -0500 Subject: portable development -- python for the pda? In-Reply-To: <20031126220246.GA63148@clarkevans.com> References: <20031126220246.GA63148@clarkevans.com> Message-ID: <200311261804.21013.drlinux@columbus.rr.com> On Wednesday 26 November 2003 17:02, Clark C. Evans wrote: > Hello. I'm going to be doing quite a bit of travel in January and > I'd like to continue to program on-the-road. So, I'm in the market > to buy a PDA with a fullsize (foldable) keyboard. Does anyone have > this sort of setup working? I typically use python and vim, with > postgresql. I don't strictly need postgresql, but having python > run on the PDA would be nice. Any suggestions? Python runs great on the Sharp Zaurus. I can personally speak for the 5500 but I suspect it runs fine on the 5600 and the new one that's only officially available in Europe and/or Asia. I'm currently using OpenZaurus instead of the Sharp ROM but Python did run on the Sharp ROM last time I checked. At least on OpenZaurus, Python is split into a number of packages (i.e., the math module and many other modules are in separate packages) to limit the amount of storage required. If you're using any specific Python modules, you may want to check if someone has created them. I have not checked to see if postgresql is available. I use a foldable pocketop keyboard ($99 last time I checked) - it's not quite fullsize, but it's close. For serious programming I'd recommend a small laptop vs. a PDA if you can afford the price difference. HTH, Dave From emile at fenx.com Sun Nov 30 21:02:15 2003 From: emile at fenx.com (Emile van Sebille) Date: Sun, 30 Nov 2003 18:02:15 -0800 Subject: speed of spambayes? References: <7xznedqxyx.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin: > Can someone using spambayes tell me about how fast it runs? IIRC, Tim Peters did some specific measurements during spambayes development. ... aah - here it is: (from message id LNBBLJKPBEHFEDALKOLCMEJFAOAB.tim.one at comcast.net) in http://mail.python.org/pipermail/python-dev/2002-August.txt.gz [Eric S. Raymond] > I'm in the process of speed-tuning this now. I intend for it to be > blazingly fast, usable for sites that process 100K mails a day, and I > think I know how to do that. This is not a natural application for > Python :-). [Tim Peters] > I'm not sure about that. The all-Python version I checked in added 20,000 > Python-Dev messages to the database in 2 wall-clock minutes. The time for > computing the statistics, and for scoring, is simply trivial (this wouldn't > be true of a "normal" Bayesian classifier (NBC), but Graham skips most of > the work an NBC does, in particular favoring fast classification time over > fast model-update time). This was 15 months ago, and I'm not sure how that relates to GBs per howlongs, but it's something to start with. -- Emile van Sebille emile at fenx.com From jbublitzno at spamnwinternet.com Wed Nov 19 15:36:55 2003 From: jbublitzno at spamnwinternet.com (Jim Bublitz) Date: Wed, 19 Nov 2003 20:36:55 GMT Subject: This is getting ridiculous (Re: PyQt, Qt, Windows and Linux) References: Message-ID: <1wQub.5843$Fr1.1731600481@twister2.starband.net> Gerhard H?ring wrote: > email9898989 at yahoo.com wrote: >>>The "official" Qt3 book is due in February of 2004, and the >>>included CD will include a non-commerical version of Qt 3.2.1 >>>for Windows [...] it appears that you will be able to >>>distribute the Qt runtime DLLs with your non commerical >>>application [...] >> >> So if I just want to make free software that works >> cross-platform, I'd have to buy this crappy C++ book to get a >> special restricted version >> of Qt3 for Windows that may or may not work with Python. This >> is ridiculous. > > If that's what you want ("make free software that works > cross-platform") you're probably better off using an > alternative GUI toolkit. Or a smaller value of "cross-platform". Jim From eugine_kosenko at ukr.net Sun Nov 30 18:29:21 2003 From: eugine_kosenko at ukr.net (=?windows-1251?b?xeLj5e3o6SDK7vHl7eru?=) Date: Mon, 1 Dec 2003 01:29:21 +0200 Subject: Unicode output to file Message-ID: <200312010129.21021.eugine_kosenko@ukr.net> Hi! The next program f = file("content.new", "wb") print f.encoding f.write(u"??????") Gives the next results: sys:1: DeprecationWarning: Non-ASCII character '\xcf' in file xp.py on line 10, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details None Traceback (most recent call last): File "xp.py", line 10, in ? f.write(u"??????") UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128) I use here Russian letters, and need special encoding for them. The property 'encoding' is read-only, and is None by default. How to cast the encoding for a file? From bokr at oz.net Wed Nov 19 14:02:47 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Nov 2003 19:02:47 GMT Subject: Reading a Bitstream References: <653b7547.0311181810.786118af@posting.google.com> Message-ID: On Wed, 19 Nov 2003 01:47:26 -0800, Dietrich Epp wrote: > >On Nov 18, 2003, at 6:10 PM, Patrick Maupin wrote: > >> Dietrich Epp wrote: >> >>> Are there any good modules for reading a bitstream? Specifically, I >>> have a string and I want to be able to get the next N bits as an >>> integer. Right now I'm using struct.unpack and bit operations, it's a >>> bit kludgy but it gets the right results. >> >> As Miki wrote, the array module will probably give you what >> you want more easily than struct.unpack. If you need more >> help, just post a few more details and I will post a code >> snippet. (As to the rest of Miki's post, I'm not sure that >> I really want to know what an "Upnacker" is :) > >Maybe I should clarify: I need to read bit fields. Neither are they >aligned to bytes or do they have fixed offsets. In fact, in one part >of the file there is a list of objects which starts with a 9 bit object >type followed by fields whose length and number depend on that object >type, ranging from a dummy 1-bit field to a tuple of four fields of >length 9, 5, 8, and 8 bits. > >I looked at the array module and can't find what I'm looking for. >Here's a bit of typical usage. > >def readStuff(bytes): > bits = BitStream(bytes[2:]) > isSimple = bits.Get(1) > objType = chr(bits.Get(8)) > objType += chr(bits.Get(8)) > objType += chr(bits.Get(8)) > objType += chr(bits.Get(8)) > count = bits.Get(3) > bits.Ignore(5) > if not isSimple: > objId = bits.Get(32) > bytes = bytes[2+bits.PartialBytesRead():] > return bytes, objType > >This is basically the gamut of what I want to do. I have a string, and >create a bit stream object. I read fields from the bit stream, some >may not be present, then return an object and the string that comes >after it. The objects are aligned to bytes in this case even though >their fields aren't. > >I can't figure out how to get array to do this. Array does not look at >all suited to reading a bit stream. struct.unpack *does* work right >now, with a lot of help, I was wondering if there was an easier way. > > > Maybe this will do something for you? Note that this is a response to your post, and not something previously tested, (in fact not tested beyond what you see ;-) and it will be slow if you have huge amounts of data to process. You pass a string to the constructor, specifying big-endian if not little-endian, and then you use the read method to read bit fields, which may optionally have their most significant bits interpreted as sign bits. E.g., reading 4-bit chunks or bits, little-endian and big-endian: >>> import sbits >>> sb = sbits.SBits('01234567') >>> for i in xrange(8*2): print sb.read(4), ... 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 >>> sb = sbits.SBits('01234567',False) >>> for i in xrange(8*2): print sb.read(4), ... 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 >>> sb = sbits.SBits('\x05') >>> for i in xrange(8): print sb.read(1), ... 1 0 1 0 0 0 0 0 >>> sb = sbits.SBits('\x05',False) >>> for i in xrange(8): print sb.read(1), ... 0 0 0 0 0 1 0 1 >>> sb = sbits.SBits('01234567') >>> hex(sb.read(64)) '0x3736353433323130L' >>> sb = sbits.SBits('01234567',False) >>> hex(sb.read(64)) '0x3031323334353637L' >>> sb = sbits.SBits('01234567') >>> hex(sb.read(32)) '0x33323130' >>> hex(sb.read(32)) '0x37363534' >>> sb = sbits.SBits('01234567',False) >>> hex(sb.read(32)) '0x30313233' >>> hex(sb.read(32)) '0x34353637' Sorry for the lack of doc strings ;-/ Please let me know if/when you find a bug. ====< sbits.py >========================================= import itertools class SBits(object): def __init__(self, s='', little_endian=True): self.le = little_endian self.buf = 0L self.bufbits=0 self.getbyte = itertools.imap(ord, s).next def read(self, nb=0, signed=False): try: while self.bufbits>= nb else: ret = self.buf>>self.bufbits self.buf &= ((1L<0) for wid in xrange(37)] hexis = map(hex,bits) shouldbe = [ '0x0', '0xffffffff', '0x1', '0x0', '0xc', '0x0', '0x6', '0x18', '0x30', '0x30', '0x18', '0xfffffe06', '0xc0', '0xc0c', '0x2060', '0x181', '0x303', '0xffff0303', '0x18181', '0x6060', '0xc0c0c', '0xc0c0', '0x60606', '0x181818', '0x303030', '0x303030', '0x181818', '0xfe060606', '0xc0c0c0', '0xc0c0c0c', '0x20606060', '0x1818181', '0x3030303', '-0xFCFCFCFDL', '0x181818181L', '0x60606060', '0xC0C0C0C0CL'] for i,h in enumerate(hexis): print '%12s%s'%(h,'\n'[:i%4==3]), print '\n-----\nThat was%s what was expected.\n-----'%((' not','')[hexis==shouldbe],) sb = SBits('\xc0'*(sum(xrange(37))+7), False) bits = [sb.read(wid, wid&1>0) for wid in xrange(37)] hexis = map(hex,bits) shouldbe = [ '0x0', '0xffffffff', '0x2', '0x0', '0x3', '0x0', '0x18', '0xc', '0xc', '0x18', '0x60', '0x303', '0x30', '0x606', '0x181', '0xffffc0c0', '0xc0c0', '0xffff8181', '0x20606', '0x3030', '0x30303', '0x6060', '0x181818', '0xc0c0c', '0xc0c0c', '0x181818', '0x606060', '0x3030303', '0x303030', '0x6060606', '0x1818181', '0xc0c0c0c0', '0xC0C0C0C0L', '0x81818181', '0x206060606L', '0x30303030', '0x303030303L'] for i,h in enumerate(hexis): print '%12s%s'%(h,'\n'[:i%4==3]), print '\n-----\nThat was%s what was expected.\n-----'%((' not','')[hexis==shouldbe],) if __name__ == '__main__': test() ========================================================= Regards, Bengt Richter From paddy3118 at netscape.net Tue Nov 18 00:47:08 2003 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 17 Nov 2003 21:47:08 -0800 Subject: PEP 321: Date/Time Parsing and Formatting References: Message-ID: <2ae25c6b.0311172147.65058189@posting.google.com> Gerrit Holl wrote: > Posted with permission from the author. > I have some comments on this PEP, see the (coming) followup to this message. > > PEP: 321 > Title: Date/Time Parsing and Formatting <> > > Abstract > ======== > > Python 2.3 added a number of simple date and time types in the > ``datetime`` module. There's no support for parsing strings in various > formats and returning a corresponding instance of one of the types. > This PEP proposes adding a family of predefined parsing function for > several commonly used date and time formats, and a facility for generic > parsing. > > The types provided by the ``datetime`` module all have > ``.isoformat()`` and ``.ctime()`` methods that return string > representations of a time, and the ``.strftime()`` method can be used > to construct new formats. There are a number of additional > commonly-used formats that would be useful to have as part of the > standard library; this PEP also suggests how to add them. > <> > > Unresolved questions: > > * Naming convention to use. > * What exception to raise on errors? ValueError, or a specialized exception? > * Should you know what type you're expecting, or should the parsing figure > it out? (e.g. ``parse_iso8601("yyyy-mm-dd")`` returns a ``date`` instance, > but parsing "yyyy-mm-ddThh:mm:ss" returns a ``datetime``.) Should > there be an option to signal an error if a time is provided where > none is expected, or if no time is provided? > * Anything special required for I18N? For time zones? > I am in favour of there being an intelligent 'guess the format' routine that would be easy to use, but maybe computationally inefficient, backed up by a computationally efficient routine where you specify the format. This latter case being split into two sub items: first where the parsing routine is passed a constant representing one of the standard formats and another where the parsing routine is passed a string representing the format. datetime.datetime.parse(" datetime.datetime.parse("1985-08-13 15:03") gives: datetime(1985, 8, 13, 13, 5) datetime.date.parse("1985-08-13 15:03") gives: date(1985, 8, 13) # You asked for the date, date was found # first in string and converted datetime.date.parse("13/08/1985", "%d/%m/%Y") gives: date(1985, 8, 13) datetime.datetime.parse("1985-08-13 15:03", datetime.ISO8601) gives: datetime(1985, 8, 13, 13, 5) The idea being for the parser to be able to automatically extract a date from one of the standard formats it knows, or to accept a strptime type string for unknown formats. (Apologies to Gerrit for using values from his reply) Cheers, Paddy. From thorsten at pferdekaemper.com Wed Nov 19 10:36:06 2003 From: thorsten at pferdekaemper.com (Thorsten Pferdekämper) Date: Wed, 19 Nov 2003 16:36:06 +0100 Subject: MP3-Player in Python? Message-ID: Hi, I am currently trying to code a little MP3-Player in Python. I do not try to do all the decoding stuff in Python, I am just looking for a (more or less...) platform independent way to play MP3s. I also want to display information like these stored in the ID3-tag and information like the length in seconds, the scan frequency etc. So far, I have found the following solutions, but I am not really happy with all of them: 1. pygame.mixer.music: Pros: Seems to be very platform independent Cons: I was not able to get the length in seconds etc. 2. tksnack Pros: Lots of functionality. Really cool. Cons: Needs Tkinter to run. (I would like to run this without X in Linux.) 3. popen mplayer or something like this Pros: ? Cons: Don't know how to control volume, position etc. Dont' know how to close mplayer in Windows... So far for the MP3 playing stuff. Concerning the ID3 tags, I have found the id3-py package (id3-py.sourceforge.net). It worked, but I dislike the automatic saving of changes on deconstruction. It also causes problems with german umlauts... It also seems not to support ID3v2. I also know mmpython, but I do not know how to run this with Windows XP. (It works fine with Linux...) So, what do you think? Regards, Thorsten From soundwave56 at yahoo.ca Tue Nov 18 12:58:08 2003 From: soundwave56 at yahoo.ca (Hank) Date: 18 Nov 2003 09:58:08 -0800 Subject: good ways to convert string into time Message-ID: <731fc603.0311180958.32135957@posting.google.com> hi, i have a string as follows 18Nov2003:18:23:43:405 Is there an easy way to convert that to absolute time? What i really want to do is to parse these times from a log file and do time comparisons, averages, stop minus start (elapsed). Probably create my own conversion table i guess? thanks From mlh at furu.idi.ntnu.no Sat Nov 15 15:22:56 2003 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 15 Nov 2003 20:22:56 +0000 (UTC) Subject: PEP 289: universal and existential operators References: <5d83790c.0310231158.65595858@posting.google.com> <9f76ee00.0311051257.45461381@posting.google.com> Message-ID: In article , Greg Ewing (using news.cis.dfn.de) wrote: >Will Stuyvesant wrote: >> Oh no! Their mathematical names are "forall" and "exists" and that is >> what they should be IMO. > >Actually, their mathematical names are an upside-down "A" >and an upside-down "E", which are often pronounced "for >all" and "there exists", but other pronunciations are >possible. While we're nit-picking, I'd like to point out that the "E" isn't upside-down -- it's mirrored (or rotated 180 degrees or whatever), so it's horizontal edges point left. :) As for the "forall" and "exists" -- these are the LaTeX names for these symbols. Given that Guido has already used LaTeX as a motivation for enumerate(), that might speak in favor of these names (even though "all" and "any" seem better to me too...) -- Magnus Lie Hetland "In this house we obey the laws of http://hetland.org thermodynamics!" Homer Simpson From aleax at aleax.it Mon Nov 17 08:00:58 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 17 Nov 2003 13:00:58 GMT Subject: Python's simplicity philosophy References: Message-ID: Arthur wrote: > Rainer writes - > >>In one line: > >>x = sum(seq) > >>And that is why 'sum' is a worthwhile part of the Python >standard library > > The issue that concerns me is the analysis, decision-making on this kind > of issue on what is essentially an "as if" basis - as if Numeric and its > line of descent were not defacto standard library for numeric processing > in Python. Oh, they are -- particularly for _advanced_ array processing involving multi-dimensional arrays. That's why I covered Numeric in the Nutshell. Of course, net of multi-dimensional arrays, Numeric.sum does offer exactly the same functionality as the built-in sum -- it's just slower for sequences that are not Numeric.array's, faster for ones that ARE: [alex at lancelot tmp]$ timeit.py -c -s'import Numeric' 'Numeric.sum(Numeric.arrayrange(234))' 10000 loops, best of 3: 30 usec per loop [alex at lancelot tmp]$ timeit.py -c -s'import Numeric' 'sum(Numeric.arrayrange(234))' 10000 loops, best of 3: 79 usec per loop So, the built-in sum is 2.5 times slower than Numeric.sum when the sequence you're summing is a Numeric.array; but, vice versa: [alex at lancelot tmp]$ timeit.py -c -s'import Numeric' 'sum(range(234))' 10000 loops, best of 3: 36 usec per loop [alex at lancelot tmp]$ timeit.py -c -s'import Numeric' 'Numeric.sum(range(234))' 1000 loops, best of 3: 540 usec per loop Numeric.sum is 15 times slower than the built-in sum when the sequence you're summing is a list. I'm not sure what you're objecting to. Is it the fact that the same name (built-in or within module Numeric) is used for very similar (but not identical, due to implementation optimizations -- as well as to multidimensional array issues) functionality? To me, that seems a very good thing (that's part of why I never even considered other names for sum, such as add or total, when I first proposed it as a builtin). > I don't know that any conclusions would change with current Numeric > functionality, and the effect of such changes on Numeric, taken under > consideration. But I do wonder why it doesn't seem to be condered > essential to consider these kinds of issues in this light. Numeric and numarray are designed and evolved by different groups of people than those active on python-dev (with some overlap, of course). They also address very different target audiences. So, why would you expect either group to be constrained (is that what you mean by "considered essential"?) by design decisions made by the other...? Maybe one day numarray will become part of the Standard python libraries, and then everything will substantially change, of course. But, until then, I do expect different evolution speeds and quite possibly directions -- indeed, that's the _advantage_ of keeping the two projects separate, avoiding excessive mutual constraints. Alex From Kepes.Krisztian at peto.hu Tue Nov 25 12:47:12 2003 From: Kepes.Krisztian at peto.hu (Kepes Krisztian) Date: Tue, 25 Nov 2003 18:47:12 +0100 Subject: How to access my module global vars ? Message-ID: <1736761179.20031125184712@peto.hu> Hi ! How to access my module global vars ? Some applications I want to declare global vars (constants). But in the module I cannot access them: DEF_X=120 class N: def DO(y): return(DEF_X*y) It creates error. But if I create an aux. unit in other file: ===file1=== DEF_X=120 ===main=== from file1 import *; class N: def DO(y): return(DEF_X*y) it works good. So: how I can create local (unit level) constants ? Thanx: KK From dw-google.com at botanicus.net Wed Nov 19 18:45:38 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 19 Nov 2003 15:45:38 -0800 Subject: beeping under linux References: Message-ID: <99dce321.0311191545.228fffbd@posting.google.com> Alexander Schmolck wrote in message news:... > This is only partly a python question, but what is the easiest way to get > python to (reliably) beep under linux? By reliably I mean that ``print "\b"`` > won't do because it depends on the terminal settings -- so I guess I'm looking > for some simple way to more or less directly access the internal speaker > (maybe writing to something in /dev/). [cape:1:dw]$ setterm -blen 1234 -bfreq 4321 | xxd 0000000: 1b5b 3131 3b31 3233 345d 1b5b 3130 3b34 .[11;1234].[10;4 0000010: 3332 315d 321] [cape:2:dw]$ echo $TERM linux If by 'reliably', you mean 'override the users choice of having the speaker on or off', then I think you need a rethink. :) There are several utilities about that can do the beeping (and music) for you, and IIRC even ones that work across platforms. > [The usage scenario is simply to have an effective way of signalling that a > long running-process finshed, without me having to constantly look at the > screen] Suggestion: allow a configurable command to be called, so that users can choose their own notification method, eg. /usr/bin/play (a part of 'sox'). David. From cjw at sympatico.ca Tue Nov 25 14:08:30 2003 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 25 Nov 2003 14:08:30 -0500 Subject: PyMatrix: Announcement Message-ID: <3FC3A8AE.6030204@sympatico.ca> In response to a number of requests, the PyMatrix package is now available for download as a zip file. Colin W. > PyMatrix is available for test and review. > http://www3.sympatico.ca/cjw > > PyMatrix provides access to basic matrix arithmetic, using Python and > numarray. > > Examples: > A * B => the product of matrices A and B > A.I => the inverse of matrix A > A.EVectors => the eigenvectors of A > A.var(0) => the variances of the columns of A > (a.T*a).I * a.T*b => the solution (x) for a * x = b, > where a is a matrix and b a column vector > > This package was developed on a Windows XP. I would appreciate > comments, particularly with respect to usage on other systems. > > Colin W. > From frr at easyjob.net Tue Nov 18 03:54:27 2003 From: frr at easyjob.net (Fernando Rodriguez) Date: Tue, 18 Nov 2003 09:54:27 +0100 Subject: trouble with os.path.exists() and wildcards References: <3FB8A5B8.3D359C27@alcyone.com> <698f09f8.0311170717.23136927@posting.google.com> <3FB91D06.5DCB381@alcyone.com> Message-ID: On 17 Nov 2003 22:17:25 GMT, bokr at oz.net (Bengt Richter) wrote: >>Besides, what else could expanding a wildcard mean except enumerating >>every possible match? > >Sure, but then what? Maybe the OP was only interested if _any_ matches existed. E.g., Yes, that exactly what I wanted, and the glob trick works fine. Thanks. :-) From max at alcyone.com Sun Nov 2 18:29:45 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 02 Nov 2003 15:29:45 -0800 Subject: round() problem? References: <334bqv4q3gi2s7mi219nl32h560r56bsih@4ax.com> Message-ID: <3FA59369.52006A7A@alcyone.com> JZ wrote: > >>> round(3999.0) == round(3990) > False > >>> round(3990.0) == round(3990) > True > >>> > > What is going on here?? Um, why would you think that's wrong? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Never had very much to say / Laugh last, laugh longest \__/ Des'ree From and-google at doxdesk.com Tue Nov 4 14:40:30 2003 From: and-google at doxdesk.com (Andrew Clover) Date: 4 Nov 2003 11:40:30 -0800 Subject: Converting GIFs with Python Image Library References: Message-ID: <2c60a528.0311041140.55e2fe9c@posting.google.com> larsdoer at yahoo.com (Lars) wrote: > Is there a way to specify the background color when converting images > with transparency? Not as far as I am aware, last time I tried at least. I wrote this to work around the problem: http://www.doxdesk.com/software/py/gifwriter.html Deals with transparency, low-bpp and LZW compression (so you may need a patent licence to use it, depending on where you live). Doesn't deal with animated GIFs, and is pretty slow (as it's pure-Python). May or may not fit your needs. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From try_vanevery_at_mycompanyname at yahoo.com Fri Nov 14 20:59:16 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Fri, 14 Nov 2003 17:59:16 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> <84fc4588.0311140319.3778de15@posting.google.com> Message-ID: Steve Lamb wrote: > > Now that we've presented anecdotal evidence both both sides care > to share why you think that your way of thinking is the predominant > one; IE more books on the shelf means you're going to buy more books > on that topic? Steve, an important question is what programmer demographic you represent, vs. how many demographics can be sold to. I, for instance, will never buy a big-picture big-print tech manual, I don't care what subject it's on. In fact, as years have progressed I'm unlikely to buy any books at all. When I did so in the past, my tastes tended towards the exceedingly dense, dry, and academic. I'm fully aware, however, that "Learn C++ in 21 days" and "C++ for Dummies" do sell copies to somebody. Somebody with different needs and a different brain than my own. As for total volume of books, I seriously doubt that you can sell more Python books simply by having more of such books available. You have to look at the strategic realities: according to one survey I saw recently, Java is being used by 53% of people on projects, C# is 25%, Python is 8%. All surveys I've ever seen about language use have roughly the same orders of magnitude, and most are much less generous to Python than 8%. Truthfully, people will not buy more Python books until Python is used more prevailantly. That's where real marketing efforts "like the big boys" come in. The Python community can either grow the market for the language, or it can atrophize and be regarded as a has-been 5 years from now. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA Brandon's Law (after Godwin's Law): "As a Usenet discussion grows longer, the probability of a person being called a troll approaches one RAPIDLY." From seberino at spawar.navy.mil Sat Nov 22 23:28:56 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 22 Nov 2003 20:28:56 -0800 Subject: Problems sending list/tuple to a C extension. References: Message-ID: Martin I hope the mistake in this simple code is obvious to you: ====================================================================== #include static PyObject* test(PyObject* self, PyObject* args) { int a; PyArg_ParseTuple(args, "(i)", &a); printf("a = %d\n",a); return Py_BuildValue("i", &a); }; static char test_doc[] = "Does nothing.\n"; static PyMethodDef mapper[] = { {"test", (PyCFunction) test, METH_VARARGS, test_doc}, {NULL} }; void inittest(void) { Py_InitModule3("test", mapper, test_doc); }; ====================================================================== Here is me compiling and running... % gcc test.c -I /usr/include/python2.2 -fpic -shared -o test.so % python 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 test >>> test.test( (3) ) a = 135386744 -1073750864 >>> Thanks again for the help. Chris martin at v.loewis.de (Martin v. L?wis) wrote in message news:... > seberino at spawar.navy.mil (Christian Seberino) writes: > > > I was not able to get parens (tuples) to work for either > > successfully. Any ideas? > > You probably did something wrong. Without seeing the code, it is hard > to tell what that might be. > > Regards, > Martin From aleax at aleax.it Mon Nov 3 03:15:37 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 03 Nov 2003 08:15:37 GMT Subject: PEP 289: Generator Expressions (please comment) References: <62d9521c.0311022349.d85fd92@posting.google.com> Message-ID: kirby urner wrote: > So list comprehensions don't just produce iterables, they produce > indexables, i.e. [func(j) for j in range(n)][10] makes sense (if > n>10). list comprehensions produce lists. They are indexable, sliceable, and everything else that lists always are, yes. > So presumably a list generator, as a kind of "lazy list comprehension" There's no such thing (neither existing nor proposed) as a "list generator". There are (going to be) "generator expressions", which will produce iterators, not lists. They will not be indexable, etc. > would be forced to iterate up to whatever index was called on it (via > __getitem__), in order to return (genexpr)[n]. Of course simple > generators don't implement __getitem__. Neither will the results of generator expressions, which will in fact also be simple generators. > So what happens to members of the list that have been evaluated? > Cached somehow? Generator expressions will behave exactly as an equivalent generator would. No caching, no indexability, etc. > I'm wondering if there's any confusion about how a generator *inside* > a list generator would be evaluated i.e. right now it makes sense to > go [r for r in gen(r)] if gen(r) has a stop condition -- the > comprehension syntax will force gen(r) to the end of its run. Lazy Yes, whatever kind of iterator gen(r) returns, it will be exhausted by this notation just as it would be by e.g. list(gen(r)) [which happens to be exactly equivalent to the list comprehension you write]. > evaluation would suggest generators with no terminus might be enclosed > e.g. d=(p for p in allprimes()). After which, d[100] would return a d is not going to be indexable. I would be interested in understanding what part of the PEP gave you these misconceptions regarding what we are proposing, so we can fix the PEP and the future docs. > hundredth prime (d[0] --> 2). So d[50] would now be retained in > memory somewhere, but d[1000] would trigger further iterations? And > we can do slices too? d = (p for p in allprimes()) will produce results exactly equivalent to d = iter(allprimes()) [type(d) may happen to be different in the two cases, but d's capabilities will be essentially identical]. More generally, e.g: d = (f(p) for p in X if g(p)) will have the same semantics as: def _aux(): for p in X: if g(p): yield f(p) d = _aux() del _aux no more, no less. Alex From aleax at aleax.it Thu Nov 13 11:49:07 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Nov 2003 16:49:07 GMT Subject: 'while' in list comprehension? References: <20031022175924.GA10716@jsaul.de> <20031024125923.GC27460@jsaul.de> <840592e1.0310270216.47ff13cf@posting.google.com> Message-ID: <7COsb.21418$hV.780067@news2.tin.it> Greg Ewing (using news.cis.dfn.de) wrote: > Hannu Kankaanp?? wrote: >> Another variation: >> >> foo = [i for i in bar, break if len(i) == 0] >> >> This wouldn't need a new keyword. > > My thoughts on all this are that if you want to do > something that procedural, it would be better written > out as nested statements. List comprehensions are > meant to be read declaratively. Yes, they are. Still, [ i for i in bar while len(i) ] DOES read pretty declaratively to me (while the "break" version admittedly doesn't). Alex From kylotan at hotmail.com Wed Nov 26 15:06:02 2003 From: kylotan at hotmail.com (Kylotan) Date: 26 Nov 2003 12:06:02 -0800 Subject: Pychecker under Windows References: <153fa67.0311252016.2e02b575@posting.google.com> Message-ID: <153fa67.0311261206.648e73c6@posting.google.com> "Duncan Smith" wrote in message news:... > > It seems to work for me in IDLE (well enough for my purposes, anyway). Yeah. I see what the issue is now - after Pychecker.checker is imported, import statements work fine, but nothing else does at all. So I just have to make sure that I set up the sys.path before I import Pychecker, so that I am able to import my files. (Is there another way?) -- Ben Sizer From tjreedy at udel.edu Tue Nov 18 20:26:28 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Nov 2003 20:26:28 -0500 Subject: syntax philosophy References: Message-ID: "Tuang" wrote in message news:df045d93.0311172120.7e753552 at posting.google.com... > $dict{$color}++ > to count up what you find. Your wish is Python's command: class cdict(dict): def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return 0 h=cdict() for item in [1,1,2,3,2,3,1,4]: h[item]+=1 >>> h {1: 3, 2: 2, 3: 2, 4: 1} > $dict{$salesperson} += $amount Trivial modification: t=cdict() for key,amt in ((1,2), (1,3), (2,5), (3,1), (3,2), (3,3)): t[key] += amt >>> t {1: 5, 2: 5, 3: 6} Terry J. Reedy From testa at allos.sytes.net Thu Nov 6 11:01:51 2003 From: testa at allos.sytes.net (F.G.Testa) Date: Thu, 6 Nov 2003 14:01:51 -0200 Subject: C STDOUT -> IDLE? (Windows) References: Message-ID: You may find some explanations (but probably not solutions) on this issue in comp.python.c++ a thread from nov/5 "stdout from c++". thid = 000501c3a3b2$ba89b900$7b64a8c0 "Rolf Wester" wrote in message news:bocv5v$9dl$1 at nets3.rz.RWTH-Aachen.DE... > Hi, > > I have some C-extension that write to C-STDOUT. When running python in > IDLE (under Windows) IDLE doesn't show the output of the C-extensions. > Is there a (simply?) way to get the extensions output displayed in IDLE? > Thanks in advance. > > Regards > > Rolf Wester > > -- > http://mail.python.org/mailman/listinfo/python-list > From a.schmolck at gmx.net Wed Nov 5 12:10:54 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 05 Nov 2003 17:10:54 +0000 Subject: Emacs mode: Display higher level References: Message-ID: "Thomas Guettler" writes: > Hi! > > I use xemacs. Is it possible to show the next higher > level in the status bar? > > Up to now it looks like this: > > Noconv-----XEmacs: foo.py (Python Font)----L1177-C0--79%--- > > It would be nice if it could look like this: > > Noconv-----XEmacs: foo.py/MyClass (Python Font)----L1177-C0--79%--- > > if the cursor is inside "class MyClass ....." > > Or better, like this, if the cursor is inside > myFunc of MyClass: > > Noconv-----XEmacs: foo.py/MyClass/myFunc (Python Font)----L1177-C0--79%--- >From memory (I switched to GNU Emacs): how about (require 'speedbar)? 'as From bokr at oz.net Sun Nov 23 12:52:52 2003 From: bokr at oz.net (Bengt Richter) Date: 23 Nov 2003 17:52:52 GMT Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> <7xwu9svyny.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 22 Nov 2003 23:40:09 -0500, Daniel Berlin wrote: > >On Nov 22, 2003, at 5:33 PM, Rainer Deyke wrote: [...] >> The FSF has no >> legal right to restrict the distribution of any software unless that >> software contains code which is copyrighted by the FSF. > >This is, of course, incorrect, unfortunately. I see the DMCA effect, but other than such (what I'd call) restraints on trade in tools-that-COULD-be-put-to-illegal-use, or patent infringement, or possibly obscenity and such laws if there is public distribution, what can prevent the distribution of an original program by itself? >For example, the FSF could own the exclusive right to license some >piece of code. Not saying that they do, but they could, and thus, even >without being the copyright owner, would have the right to enforce it's >license. >Any of the rights granted by copyright can be licensed without having >to transfer the copyright itself. What does that have to do with distributing separate software? It may prevent the recipient from making legal use of it, but that is not the originator's responsibility, so that should not be a basis for preventing the distribution, unless you want to get into prohibition/preemptive-morality-enforcement legislation. > >I passed copyright law in law school, so i'm at least sure of this much. > >In addition, DMCA grants them the right to prevent distribution of >certain other types of code (code that circumvents effective access >controls). > Overreaching IMO, and the wrong solution for a real problem. Regards, Bengt Richter From francisgavila at yahoo.com Fri Nov 7 15:41:31 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Fri, 7 Nov 2003 15:41:31 -0500 Subject: Why does changing 1 list affect the other? References: <8ufjqvc24b7o1v0c32p2cpv7us32gtsdic@4ax.com> Message-ID: "Louis Pecora" wrote in message news:pecora-9C8FEE.14325507112003 at ra.nrl.navy.mil... > So the action is on the binding end? Only one 5 is created, but the x=4 > following statement UNbinds x and rebinds it to '4', rather than > changing the object. y remains bound to '5'. Did that come out right? > > Then for lists, when we do x[0]=4 we are NOT unbinding x, but rather > just changing the object? > > Sounds like if we try harder we will get to the _binding_ actions of the > '=' operator. Let me try harder right here (off the top of my head). > > So, let's see, we view '=' as a binding operation. > > x=list > > binds x to the list, but each list element is bound to something else (I > refer to this as a second level binding). > > For lists we are allowed to change that second level binding. This > second level action does NOT affect the first level y=x binding. > > Now, does that sound right? Anyone? > > -- Lou Pecora This "first order, second order" binding is just confusing things, I think. Try this: There are two kinds of "things" in Python--names and objects. 1) Names point to objects, and only to objects 2) Names are not objects. It follows from this that names never point to names, AND that objects can CONTAIN names. So, names are THINGS, but not OBJECTS. Names are like arrows that you can hold and point at things with, but that can't be pointed to. If you say something like "y = x", you're saying, "whatever object x points to, make y point to the *same* object." (NOT a *copy* of that object!) Further, some names are explicit, some implicit (or "anonymous," if you don't mind the slight contradiction that entails....). Container objects (dictionaries, lists, tuples) contain "anonymous names" which point to objects. These implicit names are accessed indirectly only by an index or key, not directly by a name in a namespace. If the container is "mutable", then the implicit names contained within the container object can be made to point to different objects after the container object's creation. This is the behavior we see in a list: >>> firstlist=['item1','item2','item2'] Make a list-type container object with three implicit names. Make those implicit names point to three different string objects. Then make the name firstlist point to that just-created list object. >>> secondlist=firstlist Make a name secondlist which points to the same list firstlist points to. >>> print (firstlist,secondlist) (['item1', 'item2', 'item2'], ['item1', 'item2', 'item2']) Create a tuple-type container object, with two implicit names, which point to the objects pointed to by firstlist and secondlist (which end up being the same identical object.) Note that this tuple is never bound to a name, so it will be garbage collected eventually. >>> firstlist[0]='strangeness' Make the zeroth implicit name (which is contained in the object pointed to by "firstlist") point at the new string object 'strangeness'. >>> print (firstlist,secondlist) (['strangeness', 'item2', 'item2'], ['strangeness', 'item2', 'item2']) firstlist and secondlist *still* point to the same object. It's just that the object was changed. -- Francis Avila From martin at v.loewis.de Sat Nov 1 03:49:52 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 01 Nov 2003 09:49:52 +0100 Subject: Distutils: bdist_wininst. System integration use. (--silent option?, etc.) References: Message-ID: "Peter Schmiedeskamp" writes: > So, is anyone else using python for systems integration work? Would > someone familiar with the bdist suite care to speculate on the > difficulty/sensibility in extending the bdist package for this > purpose? It should certainly be possible - it is open source, so you can see for yourself what precisely it does. It being open source, changes occur only when volunteers contribute them, though. > Ultimately, maybe a bdist_msi might be possible. Yes, I've been looking into creating MSI through the installer automation interface. Unfortunately, there is too little documentation about *creating* databases - much of the documentation deals with the setup process itself. For example, my current questions are: - how do I get a package initialized with the default schema? In particular, how do I get the _Validation table filled? - how do can I add the file content to the database (I know how I can put things into the Files table). Regards, Martin From fperez528 at yahoo.com Sun Nov 2 01:23:35 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Sat, 01 Nov 2003 23:23:35 -0700 Subject: Why I love Python: More rambling... References: <20031028061245.12451.00000133@mb-m01.aol.com> <92c59a2c.0311011455.45b2f5e4@posting.google.com> Message-ID: MetalOne wrote: >> >> The sad part (to my ego, at least:)? The python runs faster! The C++ >> version >> is now in the dustbin. At least I learned a bunch about the STL and >> templates. The consolation... > > Out of curiosity, was the C++ compiled without any debugging > information. The STL is really slow with debug on. Full optimizations on, all debugging off. The bottleneck was not the STL, but the Blitz++ array code. The problem is that blitz template expressions are extremely complicated, and g++ is just not up to the task. Tests made by a blitz developer with the SGI C++ compiler show far better scaling (with the rank of the tensors), but I needed to run this on linux boxes using g++. Cheers, f From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Thu Nov 20 10:47:49 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Thu, 20 Nov 2003 18:47:49 +0300 Subject: trouble with regex with escaped metachars (URGENT please O:-) In-Reply-To: <3amprvo6n734ovhg5ekatp0539q738809t@4ax.com> References: <3amprvo6n734ovhg5ekatp0539q738809t@4ax.com> Message-ID: Fernando Rodriguez wrote: > Hi, > > I have a filewhose contents looks like this: > > Compression=bzip/9 > OutputBaseFilename=$ > OutputDir=$ > LicenseFile=Z:\apps\easyjob\main\I18N\US\res\license.txt > > The tokens $<...> must be susbtituted by some user-provided string. The > problem is that those user-provided strings might contain metacharacters, so I > escape them. And that's where I get into trouble. > > Here's the code I'm using: > > def substitute(name, value, cts): > """ > Finds all the occs in cts of $ > and replaces them with value > """ > > pat = re.compile("\$<" + name + ">", re.IGNORECASE) > > return pat.sub(val, cts) # this line causes the error (see below) > > def escapeMetachars( s ): > """ > All metacharacters in the user provided substitution must > be escaped > """ > meta = r'\.^$+*?{[|()' > esc = '' > > for c in s: > if c in meta: > esc += '\\' + c > else: > esc += c > > return esc > > cts = """Compression=bzip/9 > OutputBaseFilename=$ > OutputDir=$ > LicenseFile=Z:\apps\easyjob\main\I18N\US\res\license.txt""" > > name = 'OutputDir' > value = "c:\\apps\\whatever\\" # contains the backslash metachar > > print substitute( escapeMetachars(name), value, cts) > > I get this error: > Traceback (most recent call last): > File "", line 1, in -toplevel- > pat.sub(s,cts) > File "C:\ARCHIV~1\python23\Lib\sre.py", line 257, in _subx > template = _compile_repl(template, pattern) > File "C:\ARCHIV~1\python23\Lib\sre.py", line 244, in _compile_repl > raise error, v # invalid expression > error: bogus escape (end of line) > > What on earth is this? O:-) > > PS: I can't use string.replace() for the susbtitution,because it must be > case-insensitive: the user might enter OUTPUTDIR, and it should still work. The following works: import re cts = """Compression=bzip/9 OutputBaseFilename=$ OutputDir=$ LicenseFile=Z:\\apps\\easyjob\\main\\I18N\\US\\res\\license.txt""" name = 'OutputDir' pat = re.compile("\$<" + name + ">", re.IGNORECASE) value = "c:\\apps\\whatever\\" def escape(s): return s.replace('\\', '\\\\') print pat.sub(escape(value), cts) Note, that you should double \ in cts too (at least my snake prints some garbage otherwise). regards, anton. From ahatzis at ithcorp.com Wed Nov 12 19:01:07 2003 From: ahatzis at ithcorp.com (Anastasios Hatzis) Date: Thu, 13 Nov 2003 01:01:07 +0100 Subject: Check of a Page About Python In-Reply-To: References: <3FAE6776.4040609@ithcorp.com> Message-ID: <3FB2C9C3.5000805@ithcorp.com> Hello yeah, good question. First it has been 'scripting language', but it seems that there is something missing. But I guess by '4GL' it's gone worse. Any suggestion? cu Anastasios Eric Williams wrote: > Hallo, > > Looks alright, but I'd be interested to know why you designate python a 4GL? > You might want to check your jargon lexicon on that one. > > cya, > Eric > > Anastasios Hatzis wrote: > > >>Hi >> >>I have set up a page for a project on SourceForge. This project is about >>a bundled tech platform, which contains Python (among other OSS tools), >>so I also included a page with regard to Python. Indeed my English isn't >>that good, thus the information given on this page really needs a >>check-up. >> >>I would be very happy, if someone has the time and willingness to read >>this page (English, orthographical, and textual). The URL is: >> >> > > http://freegee.sourceforge.net/FG_EN/products/freegee/modules/python_html.html > >>There are also Python related information on some other web >>pages/documents of the project, but they are just abstracts/copies of >>this page. >> >>Many thanks! >> >>Anastasios > > From pkropf at legato.com Wed Nov 12 13:15:49 2003 From: pkropf at legato.com (Peter Kropf) Date: Wed, 12 Nov 2003 10:15:49 -0800 Subject: GUI - Qt Designer Message-ID: <96F3EC4BDF504540BB9715CBE9DACB8B019488D0@pa-mail1.legato.com> Take a look at PyQt (http://www.riverbankcomputing.co.uk/pyqt/index.php). It has a pyuic component that will compile the .ui files into .py. - Peter > -----Original Message----- > From: John Bradbury [mailto:john_bradbury at skiptalk21.com] > Sent: Wednesday, November 12, 2003 10:05 AM > To: python-list at python.org > Subject: GUI - Qt Designer > > > Is there any way to take the output produced by Qt designer > (or any other > GUI designer) and use it in Python to create a screen? There > must be a > better way of creating screens than having to use the TkInter > routnes and > add every widget one by one in the program. > > John Bradbury > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleax at aleax.it Wed Nov 12 05:14:55 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 12 Nov 2003 10:14:55 GMT Subject: Metaclass' __init__ Does not Initialize References: Message-ID: achan wrote: > As I was trying to create a metaclass, I found out that __init__ defined > in it does not initializes at all: ... > def __init__(self): > for k in self.__slots__: > k = 'something' Haven't looked at the rest of your code, but this part can't possibly be right -- you're just rebinding local variable k over and over, uselessly. Perhaps you want the loop's body to be setattr(self, k, 'something') ...? Alex From bobx at linuxmail.org Sat Nov 8 12:04:34 2003 From: bobx at linuxmail.org (Bob X) Date: Sat, 08 Nov 2003 17:04:34 GMT Subject: Sleepycat DBXML included? References: Message-ID: "Martin v. L?wis" wrote in message news:m3oevnrnlm.fsf at mira.informatik.hu-berlin.de... > "Bob X" writes: > > > I read on the Sleepycat site that dbXML was included in the 2.3 release. > > Where did you read that? > > Regards, > Martin Martin, I am 99% sure that I read it on the Sleepycat site itself in the little news blurbs they have there. Bob From nessus at mit.edu Fri Nov 14 18:10:38 2003 From: nessus at mit.edu (Douglas Alan) Date: Fri, 14 Nov 2003 18:10:38 -0500 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: Message-ID: Mahesh Padmanabhan writes: >> > Besides, there could be alternate distorted "images" for the disabled: >> > A distorted braille image could be formed >> Thank you - you just made my day. I just pictured people running their >> fingers over their monitors ... >> Tim Delaney > Heh that is a good one Hey, people *do* have braille monitors, and they do run their fingers all over them. |>oug From Raaijmakers, Vincent (IndSys, Mon Nov 10 14:38:04 2003 From: Raaijmakers, Vincent (IndSys, (Raaijmakers, Vincent (IndSys,) Date: Mon, 10 Nov 2003 13:38:04 -0600 Subject: web guru advise needed. Message-ID: <971323274247EB44B9A01D0A3B424C850304C976@FTWMLVEM02.e2k.ad.ge.com> Thnx. Regarding the SimpleTAL, can you give me an example of one of your heinous URLs and explanation why you had to do it that way? Vincent -----Original Message----- From: Eric Williams [mailto:s-rube at uselessbastard.net] Sent: Monday, November 10, 2003 1:25 PM To: python-list at python.org Subject: Re: web guru advise needed. Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: > > 1) simple presentation layer processing. The HTML pages produced by server > will be more focused on presenting images (dynamic), rather that fancy > tables, frames, buttons. 2) the framework has to be robust and FAST on > performance. 3) runs only on Linux, well not really a requirement, more a > statement. 4) runs on Apache (and/or Tomcat) > > What technology gives me the best performance? > I'm so afraid that adapters like WebKit kills my performance but because > of my jsp experience, psp seems the best option. > > Vincent FWIW, I recently complete a CMS project with the following constellation: 1) Apache with mod_python 2) PostgreSQL for content storage, mostly in the form of blob'd Pickles 3) Templating using SimpleTAL (elegant and leightweight, but requires some downright heinous URLs) 4) Everything running behind Squid in accelerator mode It's pretty dang snappy on performance, but you'd need a dedicated server/processor for dynamic images, I would think. cya, Eric -- --- s- should be removed to contact me... -- http://mail.python.org/mailman/listinfo/python-list From neal at metaslash.com Tue Nov 18 22:08:48 2003 From: neal at metaslash.com (Neal Norwitz) Date: Tue, 18 Nov 2003 22:08:48 -0500 Subject: PyChecker lives! Version 0.8.13 released. Message-ID: <20031119030848.GP16931@epoch.metaslash.com> A new version of PyChecker is (finally) available for your hacking pleasure. It's been quite a while since the last release--11 months. I wish there was more progress, but such is life. Many bug fixes and some new warnings were added. I hope to get future releases out faster. I have several patches queued up and ideas for more warnings. As always, I'd like to hear your suggestions for common mistakes and bugs than can/should be found by PyChecker. I'm very interested to know what version(s) of Python you use (or would like to use) PyChecker with. Even if you don't use PyChecker, please take a moment to answer this short poll so I can get an idea of how many people use each version of Python. Please take a moment and visit: http://metaslash.com/pyversion.html It would be great if you could help out the Python Software Foundation and make a donation: http://python.org/psf/donate.html In return for your generous donation, I will send you a very personal email. ;-) Comments, criticisms, new ideas, and other feedback is welcome. Changes from 0.8.12 to 0.8.13: * Add -s/--shadowbuiltin option to warn when overriding a builtin * Add warning when assigning a variable to itself * Add warning when dividing a variable by itself * Add warnings when using a bit-wise operator with the same variable (a & a) * Add warning when passing a constant string to getattr()/setattr() * Add --special option to check for __special__ (reserved) method names and that their signature (argument count) is correct * Add warning for using __getattribute__ in an old-style class * Suppress 'self as first argument' warning for static and class methods * Add --classmethodargs option to specify first argument name for class methods PyChecker is available on Source Forge: Web page: http://pychecker.sourceforge.net/ Project page: http://sourceforge.net/projects/pychecker/ Mailing List: pychecker-list at lists.sourceforge.net PyChecker is a tool for finding bugs in Python source code. It finds problems that are typically caught by a compiler for less dynamic languages, like C and C++. It is similar to lint. Neal -- pychecker-list at lists.sourceforge.net From peter at engcorp.com Fri Nov 7 23:07:36 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 07 Nov 2003 23:07:36 -0500 Subject: try...finally is more powerful than I thought. References: <3faab4e8$0$559$b45e6eb0@senator-bedfellow.mit.edu> <3FAABC88.5A696162@engcorp.com> <3FAB1FB9.75E5A787@engcorp.com> Message-ID: <3FAC6C08.C47EA809@engcorp.com> Lee Harr wrote: > > On 2003-11-07, Peter Hansen wrote: > > Lee Harr wrote: > >> interesting. > > > > Why? It just proves that "finally" works, and > > executes when the return statement is encountered. > > Yes. I just found the entire thread interesting. I know that > people who are unfamiliar with the try ... finally syntax can > easily fire up the interpreter and play around with it for > themselves, but I thought the "basic functionality" example > might make the rest of the thread more clear. > > I have written a lot of python code and have never used finally. Ah, good point. :-) -Peter From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Mon Nov 10 15:33:04 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Mon, 10 Nov 2003 23:33:04 +0300 Subject: make order of function definitions irrelevant In-Reply-To: <3FAFF284.8EA7AEFB@engcorp.com> References: <3FAFF284.8EA7AEFB@engcorp.com> Message-ID: Peter Hansen wrote: > anton muhin wrote: > >> As was said, you usually don't need such a thing. If you desperatly >>looking for it, something like this might work: >> >>func = None >> >>def caller(): >> assert func, 'func is None' >> return func() >> >>def foo(): >> return 'foo' >> >>def bar(): >> return 'bar' >> >>func = foo >> >>print func() >> >>Of course, in this case you'd better pass an actual function as a >>parameter. But, again, almost for sureit's a flaw in your design. > > > As it stands, the first line in the above code is still redundant, > and can be removed with no ill effects, as "func" is not actually > called until it is bound to a real function. > > -Peter Sure, thanks. It just a little bit clearer. best regards, anton. From testa at allos.sytes.net Wed Nov 12 11:43:00 2003 From: testa at allos.sytes.net (F.G.Testa) Date: Wed, 12 Nov 2003 14:43:00 -0200 Subject: async_chat close socket notification Message-ID: Hi folks! How to receive a notification when a async_client is closed? class AcmePopupChannel(asynchat.async_chat): .... def handle_close(self): print 'Closed channel' def handle_error(self): print 'Error in channel' This seems not work for me. Thanks! Testa Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 From sfb at alysseum.com Sun Nov 2 07:33:37 2003 From: sfb at alysseum.com (Simon Bayling) Date: Sun, 2 Nov 2003 12:33:37 +0000 (UTC) Subject: simple echo server References: <3fa3fab9$0$58702$e4fe514c@news.xs4all.nl> <3FA4284A.6010701@zg.htnet.hr> <3fa4395a$0$58698$e4fe514c@news.xs4all.nl> <3FA4CB41.8080306@zg.htnet.hr> Message-ID: Haris Bogdanovic wrote in news:3FA4CB41.8080306 at zg.htnet.hr: >>> It's the example from python docs (socket section). If you have >>> somewhere your personal user account you can try it aswell. >> > I ment telnet account. Is that the place where people normally put > their server part of the application or can I put somewhere else (is > there a common way to do this) ? Telnet account to what? You can put it anywhere you can run Python code on an operating system with TCP/IP. >>> Tell me what you managed to do. I copied the server example and ran it. I copied the client example, altered the HOST to 127.0.0.1 and ran it. It connected and sent/recieved "Hello, world", then finished. Just as it should do. Now, what error message are you getting? -- Simon. From keflimarcusx at aol.comNOSPAM Mon Nov 3 22:19:27 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 04 Nov 2003 03:19:27 GMT Subject: Please explain the meaning of 'stealing' a ref References: Message-ID: <20031103221927.08116.00000258@mb-m15.aol.com> > what exactly is the meaning of a function >"stealing a reference"? It decrements the reference count. If you still need the reference, Py_INCREF() it beforehand. - Kef From duncan at NOSPAMrcp.co.uk Wed Nov 5 04:56:25 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 5 Nov 2003 09:56:25 +0000 (UTC) Subject: Why no try-except-finally ? References: <20031105040556.29079.00000209@mb-m22.aol.com> Message-ID: keflimarcusx at aol.comNOSPAM (KefX) wrote in news:20031105040556.29079.00000209 at mb-m22.aol.com: > This may have been discussed before, but I'm kind of confused as to > why Python doesn't support having both an except ~and~ a finally > clause, like this: > > try: > raise RuntimeException > except: > print "What is the answer?" > finally: > print 42 > > This doesn't work because I use both 'except' and 'finally'. I'm not > saying that it SHOULD work, I'm wondering why it doesn't. The first thing to ask yourself when wondering why something doesn't work in Python, is exactly what you expect it should do. The 'try' block can exit normally; by throwing an exception that is caught by an 'except'; or by throwing an exception that is not caught and propogates outside. Do you want the 'finally' block executed in all of those cases, or only for some of them? The answer to your question, given by Tim Peters in http://groups.google.com/groups?selm=LNBBLJKPBEHFEDALKOLCMEONGIAA.tim_one%4 0email.msn.com is that Python used to allow this, and people got caught out because it didn't work the way everyone expected. By writing try/except/else and try/finally separately you can clearly communicate what you expect to happen. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From see_signature__ at hotmail.com Tue Nov 18 17:33:35 2003 From: see_signature__ at hotmail.com (Georgy Pruss) Date: Tue, 18 Nov 2003 22:33:35 GMT Subject: Too much builtins (was Re: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com><653b7547.0311121826.65b6b2d4@posting.google.com> Message-ID: <37xub.23208$C14.952050@twister.southeast.rr.com> "Andrew Dalke" wrote in message news:J4tub.4889$sb4.2295 at newsread2.news.pas.earthlink.net... | Georgy Pruss: | > I guess, the same as for | > hex(30+44j) | > oct(3.1415926) | ... | | Which means you want | str(obj) -> result as usual; takes any object, returns a string, all | numbers | are represented in base 10 | str(obj, [base=10]) -> converts integer objects (only!) to the given base, | defaults to base 10. | | That feels wrong to me. Base conversion is enough of a special | case that it doesn't warrant being part of the standard str constructor. | As an 'int.to_base' method or class method, perhaps, but not in str. | | Andrew | dalke at dalkescientific.com To me, it's very wrong that you can read any radix numbers, but can't print them. If str(int(s)) == s and int(str(n)) == n (with some limits), I don't see why str(n,radix) can't be symmetrical to int(s,radix). BTW there's no symmetry for str() and list()/tuple()/dict() etc. -- Georgy Pruss E^mail: 'ZDAwMTEyMHQwMzMwQGhvdG1haWwuY29t\n'.decode('base64') From guettli at thomas-guettler.de Wed Nov 5 10:50:12 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 05 Nov 2003 16:50:12 +0100 Subject: Template-engine References: Message-ID: Am Wed, 05 Nov 2003 14:24:00 +0100 schrieb Jan-Erik Meyer-L?tgens: > Miika Keskinen wrote: >> Hi all >> >> I was in need for a simple template engine (like PEAR::IT.php) and didn't >> find any suitable. Yes, there is many templating engines available but >> most are far too complex or does implement some additional features in >> their syntax. >> > Try Cheetah: http://www.cheetahtemplate.org/ try python: def foo(self): ret=[] ret.append(self.header()) ret.append(""" Time is too short to rewrite parsers
... """) ret.append(self.footer()) return ''.join(ret) thomas From http Mon Nov 17 12:23:26 2003 From: http (Paul Rubin) Date: 17 Nov 2003 09:23:26 -0800 Subject: Python's simplicity philosophy References: <3FAC19F0.284DCB03@alcyone.com> <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <7xoevcf1u2.fsf@ruckus.brouhaha.com> <7x7k1zc0si.fsf@ruckus.brouhaha.com> <61Ztb.3481$sb4.1708@newsread2.news.pas.earthlink.net> Message-ID: <7xk75ysycx.fsf@ruckus.brouhaha.com> "Andrew Dalke" writes: > > Surely he was talking about implementing "list-alikes"...? > > Yes, I think you're right about that, and I misinterpreted > his statement. Yes, I was talking about "list-alikes". > Then again, is the change that "all Python list-alikes must > implement stable sort" or that "Python native lists shall > now and forever implement stable sort"? The change was that native lists will implement stable sort. My gripe is that if native lists are required to sort stably and list-alikes can sort unstably, then list.sort and listalike.sort act differently in a way that can lead to subtle bugs. > That's a statement only that list.sort shall be stable and > not that all .sort() methods must be stable. It would be icky if some .sort() methods are required to be stable but others are not. Note that the most obvious way to implement sort() in C is to call the standard C library qsort function, which is unstable. From roy at panix.com Wed Nov 5 23:05:30 2003 From: roy at panix.com (Roy Smith) Date: Wed, 05 Nov 2003 23:05:30 -0500 Subject: Why does changing 1 list affect the other? References: <8ufjqvc24b7o1v0c32p2cpv7us32gtsdic@4ax.com> Message-ID: oom wrote: > I am a bit of a newbie when it comes to python, when working with > lists today I noticed some very odd behaviour, any suggestions > welcome: > > Python 2.2.3 (#1, Nov 6 2003, 14:12:38) > [GCC 3.3.2 20031022 (Gentoo Linux 3.3.2-r2, propolice)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> firstlist=['item1','item2','item2'] > >>> secondlist=firstlist > >>> print (firstlist,secondlist) > (['item1', 'item2', 'item2'], ['item1', 'item2', 'item2']) > >>> firstlist[0]='strangeness' > >>> print (firstlist,secondlist) > (['strangeness', 'item2', 'item2'], ['strangeness', 'item2', 'item2']) > >>> > > why does altering one list affect the other list ? it is driving me > insane! > Because when you say secondlist = firstlist, you're not making a copy of the list, you're just making another reference to the existing list object. If you're used to C/C++, think of it as passing a pointer around. If you really wanted to make a new list, you should look at the copy module (specifically copy.deepcopy). Or, somewhat simplier, you could have just said secondlist = list (firstlist), which creates a new one (kind of like a copy constructor might do in C++). From timr at probo.com Fri Nov 21 00:41:58 2003 From: timr at probo.com (Tim Roberts) Date: Thu, 20 Nov 2003 21:41:58 -0800 Subject: win32gui_dialog problem? Message-ID: I'm running Python 2.3 and win32all-155 on Windows 2000. The win32gui_dialog.py sample in win32\demos dies with this: C:\Apps\Python23\Lib\site-packages\win32\demos>python win32gui_dialog.py Fatal Python error: This thread state must be current when releasing abnormal program termination C:\Apps\Python23\Lib\site-packages\win32\demos> It dies at the end of DemoWindow._DoCreate when calling CreateWindow. I'm boggled. Is this a known problem? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mensanator at aol.compost Sat Nov 29 00:17:40 2003 From: mensanator at aol.compost (Mensanator) Date: 29 Nov 2003 05:17:40 GMT Subject: GMPY compare warning Message-ID: <20031129001740.25982.00001230@mb-m05.aol.com> In the program that follows, I get the following warning message: collatz_.py:37: RuntimeWarning: tp_compare didn't return -1, 0 or 1 while b>1: In this case, b is a gmpy.mpz number. The program operates as it should, which I guess is why it's a warning. Is there some reason why I shouldn't use gmpy numbers with relational operators? Is this warning something that can safely be ignored? import sys import time import gmpy i = long(sys.argv[1]) n = 2**(i) - 1 r1 = 0 r2 = 0 t0 = time.time() a = n while a>1: z = divmod(a,2) if z[1]==0: a = z[0] r1 += 1 else: a = a*3 + 1 r2 += 1 t1 = time.time() print "r1",r1,"r2",r2,"in",t1-t0,"seconds\n" b = gmpy.mpz(n) r1 = 0 r2 = 0 t0 = time.time() while b>1: z = gmpy.scan1(b) if z==0: b = b*3 + 1 r2 += 1 else: b = b/(2**z) r1 += z t1 = time.time() print "r1",r1,"r2",r2,"in",t1-t0,"seconds\n" """ C:\Python23\user>python collatz_.py 1000 r1 7841 r2 4316 in 0.109000086784 seconds r1 7841 r2 4316 in 0.375 seconds C:\Python23\user>python collatz_.py 10000 r1 86278 r2 48126 in 6.42199993134 seconds r1 86278 r2 48126 in 4.85900008678 seconds C:\Python23\user>python collatz_.py 100000 r1 863323 r2 481603 in 604.766000032 seconds r1 863323 r2 481603 in 121.859999895 seconds """ -- Mensanator Ace of Clubs From christopher_culver_ForiguCxiTion at yahoo.com Tue Nov 18 00:16:32 2003 From: christopher_culver_ForiguCxiTion at yahoo.com (Christopher Culver) Date: Tue, 18 Nov 2003 05:16:32 GMT Subject: OO design, Python, and GUIs Message-ID: <0bc1371b047abbb6ab299bf1c1f167ae@news.teranews.com> I'm creating a home-library management program with Python 2.2, PyGTK, and Glade. While I've been many little programs before, this is my first large application in Python. My question is how I should organise the OO design of such a program. There should be, I gather, a core class "MainClass", which coordinates everything, other specialised classes which report to MainClass, and the GUI should ideally be in its own class "GuiClass". Now GuiClass at the moment doesn't know anything about MainClass. When the program is started, an instance "mainClass" is created, which in turn creates an instance "guiClass". But how can guiClass report anything to the mainClass? For example, when the user selects a new file in the GUI, how can I send the chosen pathname to mainClass? I imagine that I have to initalise the GuiClass instance in such a way that it knows about mainClass enough to be able to call its methods, but I've been unable find out how mainClass could pass itself to the GuiClass __init__. Be gentle, I'm somewhat of a newbie. If there's documentation out there on this, I'll happily take a look. Christopher Culver From lion-freddie at zebra-madcowdisease.giraffe-org Sun Nov 2 18:04:23 2003 From: lion-freddie at zebra-madcowdisease.giraffe-org (Freddie) Date: Mon, 03 Nov 2003 09:34:23 +1030 Subject: Weird asyncore behaviour Message-ID: <3fa58d78_1@news.adelaide.pipenetworks.com> Hi, I've been playing around with asyncore for one of my projects, currently using it to fetch HTTP pages without blocking things. Having a few issues, though. With the code below, I would start a new async_http instance with "async_http(url, returnme)". If it encountered a redirect, that object would start a new one as "async_http(url, returnme, seen=self._seen)" to remember what URLs it had seen. The problem is that after a while (usually after several async_http objects are active at once), newly created async_http objects would have the seen parameter with URLs filled in already! I have absolutely no idea how that could be happening :\ I 'solved' it by explicitly passing "seen={}" for new objects, but I would still like to know why this is happening :) Freddie class async_http(asyncore.dispatcher): def __init__(self, parent, returnme, url, seen={}): asyncore.dispatcher.__init__(self) self.parent = parent self.returnme = returnme self.url = url self._seen = seen # split url, connect, etc # at some point in here, we would find a redirect and go: def at_some_point(self): self._seen[self.url] = 1 async_http(self.parent, self.returnme, self.url, self._seen) self.close() From ramen at lackingtalent.com Mon Nov 3 00:01:10 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 03 Nov 2003 05:01:10 -0000 Subject: On PEP 322 (ireverse) References: Message-ID: In article , Alex Martelli wrote: > > Nope -- even though I'd STILL like "iter.reversed", we can't make > iter a type, backwards compatibly, in a DECENT way; we'd really need > a new subtype of "builtin function" which can have attributes. Pardon me for missing this, but what was the rationale for not just calling it "reverse" and putting it in builtins? And likewise for "sort"? -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From nessus at mit.edu Tue Nov 18 12:46:23 2003 From: nessus at mit.edu (Douglas Alan) Date: Tue, 18 Nov 2003 12:46:23 -0500 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> <84fc4588.0311140319.3778de15@posting.google.com> Message-ID: "A.M. Kuchling" writes: > Andrew Dalke wrote: >> At the last bioinformatics open-source software developer meeting >> I went to, everyone was running either Linux or OS X. People >> booted into MS Windows mostly to check comptability. > Similar anecdotal evidence indicates the same is true for astronomers, at > least the astronomers my SO hangs out with. A friend also recently told me > of a family reunion where pretty much everyone had an Apple laptop except > him. I work for astronomers too, and we're slowly but steadily giving up on Solaris and moving to Linux and OS X. I also went to a conference on "Lightweight Languages" a week ago, and 8 out of 10 notebook computers in the audience were Apples. |>oug From achrist at easystreet.com Sat Nov 1 12:32:37 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Sat, 01 Nov 2003 09:32:37 -0800 Subject: py2exe question References: <3FA36D0A.45BCA44B@easystreet.com> <6FKob.391474$R32.12987108@news2.tin.it> Message-ID: <3FA3EE35.F382B493@easystreet.com> The error I'm getting is in module imputil.pyo, line 601, in import_file, module does not define init function initpywintypes23. Please, can anyone tell what this means and how to fix? TIA Al From mwh at python.net Fri Nov 21 12:01:58 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 21 Nov 2003 17:01:58 GMT Subject: Using an interable in place of *args? References: Message-ID: Nick Vargish writes: > Is there a general method for calling a function that expects *args > with an iterable instead (tuple or, even better, a list)? I can see > how I could do something funky with exec, but I'd like to avoid that > if possible. Are you just asking for *arg? >>> struct.pack('c'*4, *(['e']*4)) 'eeee' Cheers, mwh -- Get out your salt shakers folks, this one's going to take more than one grain. -- Ator in an Ars Technica news item From max at alcyone.com Fri Nov 7 17:17:20 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 07 Nov 2003 14:17:20 -0800 Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> Message-ID: <3FAC19F0.284DCB03@alcyone.com> Alex Martelli wrote: > However, so many of reduce's practical use cases are eaten up by sum, > that reduce is left without real use cases to justify its existence. Any reduction that doesn't involve summing won't be handled by sum. Flattening a list of (non-recursive) lists is a good example. reduce is already in the language; removing an existing, builtin function seems totally inappropriate given that it's there for a reason and there will be no replacement. > But comparing plain Python code to a built-in that's almost bereft of > good use cases, and finding the plain Python code _faster_ on such a > regular basis, is IMHO perfectly legitimate. reduce will be at least as fast as writing an explicit loop. Potentially more if the function object used is itself a builtin function. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ A man cannot be comfortable without his own approval. \__/ Mark Twain From max at alcyone.com Wed Nov 19 00:10:55 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 18 Nov 2003 21:10:55 -0800 Subject: scalar references References: Message-ID: <3FBAFB5F.EEE6C0AE@alcyone.com> John Hunter wrote: > My current approach (which works) is > > class RRef: > 'A read only ref' > def __init__(self, val): > self._val = val > > def get(self): > return self._val > > class RWRef(RRef): > 'A readable and writable ref' > def set(self, val): > self._val = val Yep, this is the kind of thing I usually do. If you'd like to write shorter, but less self-documenting code, you can just use a one-element list. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ Perfect situations must go wrong -- Florence, _Chess_ From martin at v.loewis.de Sat Nov 22 07:17:44 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 22 Nov 2003 13:17:44 +0100 Subject: gettext crazy question References: <43e3984e.0311201935.64aac584@posting.google.com> Message-ID: ulysses_dm at yahoo.com.cn (ulysses) writes: > So I debug gettext module. I find following interest question. > -=gettext line 154=- > buf = fp.read() > > I sure fp(file object) has open. > > It can't read all binary code. buf 's lengh smaller than real file. > exp ,whole file 1000 byte. gettext only read 187 . It looks like the file is opened in text mode, not in binary mode. Did you, by chance, open the file yourself? You should use binary mode, then. Regards, Martin From thorsten at pferdekaemper.com Mon Nov 10 05:11:48 2003 From: thorsten at pferdekaemper.com (Thorsten Pferdekämper) Date: Mon, 10 Nov 2003 11:11:48 +0100 Subject: Talking through pipes interactively (on win32) References: Message-ID: "Jane Austine" wrote in message news:ba1e306f.0311091118.24d80000 at posting.google.com... > I need to control a command line program via python. > > I first tried popen2 and 3 but I couldn't find a way to talk to the > subprocess interactively; that is, read some and then write some, and > read some more again... (suppose controlling an interactive shell > program) When I try this with popen family, it just hangs. I have to > close one pipe before reading from the other. > > I know that there is a wonderful thing called Expect, but it's not > available on my machine(win32). > > Can anyone help me out? Hi, in "Python in a nutshell", I have found a remark about that. It seems that this depends on some buffering mechanisms the programs use. The program you are running with popen just waits until the input stream is closed. As long as you can not control the behaviour of this program, you hardly can do anything, espacially on win32. Perhaps you can try spawn(). Kind Regards, Thorsten From __peter__ at web.de Mon Nov 24 04:41:55 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Nov 2003 10:41:55 +0100 Subject: sys.path.append('/my/new/path') References: Message-ID: Jeff Wagner wrote: > Is it possible to append a new Path to some file permanently? It seems > like a sys.path.append('/my/new/path') statement is temporary. > > In other words, where and in what file on a Win32 box or Linux box is the > sys.path info kept. I have a couple of paths I keep practice files in I > want to add to the path permanently. The easiest way to extend the list of paths is to put a .pth file (a text file with an arbitrary name, the .pth extension containing one path per line) in the site-packages directory. For details, see http://www.python.org/doc/current/inst/search-path.html Peter From SEE_AT_THE_END at hotmail.com Fri Nov 7 19:28:29 2003 From: SEE_AT_THE_END at hotmail.com (Georgy Pruss) Date: Sat, 08 Nov 2003 00:28:29 GMT Subject: try...finally is more powerful than I thought. References: <3faab4e8$0$559$b45e6eb0@senator-bedfellow.mit.edu> <3FABB15C.6BB2C44A@hotmail.com> Message-ID: "Mauro Cicognini" wrote in message news:bogm9e$bn3$1 at grillo.cs.interbusiness.it... > > <,,,> > try: > try: > ... > finally: > ... > except: > ... > > to achieve the same effect. > > Am I right? I.e. (again) how do you people use try .. finally in real > use cases? > > Does anyone else think Python could have a nicer syntax for this one? That's probably why they called it begin...rescue in Ruby :) G-: > > Mauro From pclinch at internet-glue.co.uk Mon Nov 17 15:53:23 2003 From: pclinch at internet-glue.co.uk (Paul Clinch) Date: 17 Nov 2003 12:53:23 -0800 Subject: check for the presence of an external program on the path References: Message-ID: <8cf2994e.0311171253.d579f72@posting.google.com> Fernando Rodriguez wrote in message news:... > Hi, > > How can I find out if an executable is available in the path? > > TIA This works on linux:- import os ls=os.environ['PATH'] for d in ls.split(':'): if 'executable' in os.listdir(d): print 'found it!' break Regards, Paul Clinch From aleax at aleax.it Thu Nov 13 08:49:17 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Nov 2003 13:49:17 GMT Subject: True inconsistency in Python References: <3FB364A3.1060701@users.ch> Message-ID: Borcis wrote: > Scott Chapman wrote: > >> >> if var == True: # only works if var is 1 >> blah >> >> ' Must use: >> >> if var: # works if var is not 0 >> blah > > there's the equivalent, and more explicit : > > if bool(var)==True : blah Why stop there? If adding one useless and redundant check is better, surely having more will be merrier and merrier...: if ( bool(var) == True) == True: doubleblah oh wait, we should add ANOTHER level of uselessness...: if (( bool(var) == True) == True) == True: tripleblah oh wait... "if var:" is the Pythonic way. You could argue that each level of "== True" makes it ``more explicit'', but I just consider them all equally silly in their utter redundancy. [[ we TOLD Guido people would start on this absurd path, when he added bool, True, and False, but he wouldn't listen... ]] Alex From emile at fenx.com Thu Nov 13 10:09:39 2003 From: emile at fenx.com (Emile van Sebille) Date: Thu, 13 Nov 2003 07:09:39 -0800 Subject: True inconsistency in Python References: Message-ID: Ben Finney > You many want to read the PEP that led to the creation of the 'bool' > type (and True and False objects): ... or vise versa Emile van Sebille emile at fenx.com From glauco at sferacarta.com Fri Nov 28 05:47:17 2003 From: glauco at sferacarta.com (Glauco) Date: Fri, 28 Nov 2003 10:47:17 GMT Subject: Best SOAP library? In-Reply-To: <873ccbxfu3.fsf@heinrich.complete.org> References: <87y8u432u2.fsf@heinrich.complete.org> <873ccbxfu3.fsf@heinrich.complete.org> Message-ID: John Goerzen wrote: > "Diez B. Roggisch" writes: > > >>>Which Python-based SOAP implementation is preferred today? Which ones >>>are still being actively developed? >> >>ZSI just had a new release - IMHO its the most complete implementation. I >>was quite satisfied with it, however I encountered problems with a >>moderately complex apache-axis-based WSDL - but I didn't investigat >>further, instead I used the generated axis-client and jython :) > > > How would you say ZSI compares to SOAPpy? I've heard that SOAPpy is > easier to use for some cases. Are there things that ZSI does that > SOAPpy doesn't (or not as well)? > > Thanks, > John I've builded a complex library for standardize the use of some Webservices published in .NET . In 1 year of implementation i've done a lot of manipulation to SOAPpy because it cannot do something. I think SOAPpy is not in developing . Probably ZSI is updated. Glauco From achin at eminence32.cjb.net Sun Nov 2 22:04:37 2003 From: achin at eminence32.cjb.net (Andrew) Date: Mon, 03 Nov 2003 03:04:37 GMT Subject: simple echo server References: <3fa3fab9$0$58702$e4fe514c@news.xs4all.nl> <3FA429EF.5090407@zg.htnet.hr> Message-ID: i beleive that the problem is that your shell is rather restrictive on network access. i used arbornet a while ago and recall they dont allow anonoymous non-members to do much. find another linux box (like a friends, or your own) and try it there. -andrew On Sat, 01 Nov 2003 22:47:27 +0100, Haris Bogdanovic wrote: > Irmen de Jong wrote: >> Haris Bogdanovic wrote: >> >>> When client is trying to connect to the server everything works fine >>> but when server tries to echo what it receieved from client I get >>> access denied error. >>> Why is that happening ? >> >> >> Because the server has no access? >> >> No really-- you have to give much more detailed information. >> Preferrably the exact code fragment and exact error message >> that you're getting. >> >> --Irmen >> > It's the example from python docs (socket section). If you have > somewhere your personal user account you can try it aswell. > Tell me what you managed to do. > > Thanks > Haris > -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From bokr at oz.net Sun Nov 9 17:40:57 2003 From: bokr at oz.net (Bengt Richter) Date: 9 Nov 2003 22:40:57 GMT Subject: recursion vs iteration (was Re: reduce()--what is it good for?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> Message-ID: On Sun, 09 Nov 2003 21:07:31 +0100, anton at vredegoor.doge.nl (Anton Vredegoor) wrote: >Alex Martelli wrote: > >>def Ack(M, N, _memo={}): >> try: return _memo[M,N] >> except KeyError: pass >> if not M: >> result = N + 1 >> elif not N: >> result = Ack(M-1, 1) >> else: >> result = Ack(M-1, Ack(M, N-1)) >> _memo[M,N] = result >> return result >> >>M>=0 and N>=0 (and M and N both integers) are preconditions of the Ack(M, N) >>call. > >Defined as above the number of recursions is equal to the return >value, because there is only one increment per call. > >Have a look at the paper about the ackerman function at: > >http://www.dur.ac.uk/martin.ward/martin/papers/ > >(the 1993 paper, halfway down the list, BTW, there's also something >there about automatically translating assembler to C-code, maybe it >would also be possible to automatically translate C-code to Python? >Start yet another subthread :-) > >Another thing is that long integers cannot be used to represent the >result values because the numbers are just too big. > >It seems possible to make an iterative version that computes the >values more efficiently, but it suffers from the same number >representation problem. > >Maybe Bengt can write a class for representing very long integers as Thanks Anton ;-) >formulas. For example an old post by Fran?ois Pinard suggests that: > >ackerman(4, 4) == 2 ** (2 ** (2 ** (2 ** (2 ** (2 ** 2))))) - 3 > If they are too big to represent, they are probably also too big to arrive at in practical time counting by one ;-) It is interesting to trace the composition of the args to successive calls and label which recursive calls they were due to, though I don't know what to make of it ;-) A quick hack (I may have goofed) shows: >>> sAck(2,2) 2 2 root: M N 2 1 M&N argev: M (N-1) 2 0 M&N argev: M ((N-1)-1) 1 1 not N: (M-1) 1 1 0 M&N argev: (M-1) (1-1) 0 1 not N: ((M-1)-1) 1 0 2 M&N: ((M-1)-1) (1+1) 1 3 M&N: (M-1) ((1+1)+1) 1 2 M&N argev: (M-1) (((1+1)+1)-1) 1 1 M&N argev: (M-1) ((((1+1)+1)-1)-1) 1 0 M&N argev: (M-1) (((((1+1)+1)-1)-1)-1) 0 1 not N: ((M-1)-1) 1 0 2 M&N: ((M-1)-1) (1+1) 0 3 M&N: ((M-1)-1) ((1+1)+1) 0 4 M&N: ((M-1)-1) (((1+1)+1)+1) 1 5 M&N: (M-1) ((((1+1)+1)+1)+1) 1 4 M&N argev: (M-1) (((((1+1)+1)+1)+1)-1) 1 3 M&N argev: (M-1) ((((((1+1)+1)+1)+1)-1)-1) 1 2 M&N argev: (M-1) (((((((1+1)+1)+1)+1)-1)-1)-1) 1 1 M&N argev: (M-1) ((((((((1+1)+1)+1)+1)-1)-1)-1)-1) 1 0 M&N argev: (M-1) (((((((((1+1)+1)+1)+1)-1)-1)-1)-1)-1) 0 1 not N: ((M-1)-1) 1 0 2 M&N: ((M-1)-1) (1+1) 0 3 M&N: ((M-1)-1) ((1+1)+1) 0 4 M&N: ((M-1)-1) (((1+1)+1)+1) 0 5 M&N: ((M-1)-1) ((((1+1)+1)+1)+1) 0 6 M&N: ((M-1)-1) (((((1+1)+1)+1)+1)+1) (7, '((((((1+1)+1)+1)+1)+1)+1)') Is there a fast formula for computing results, ignoring the representation problem? Regards, Bengt Richter From pushcold at hotpop.foo Sat Nov 22 09:56:25 2003 From: pushcold at hotpop.foo (Thomas) Date: Sat, 22 Nov 2003 15:56:25 +0100 Subject: Tkinter / Unicode and UTF-8 References: <3FBF133C.8050503@v.loewis.de> Message-ID: On Sat, 22 Nov 2003 08:41:48 +0100, Martin v. L?wis wrote: > Because you are using incorrect binaries. You will have to build Python > from source on Fedora 1, or wait for Redhat to fix the package. I think that will not happen (at least not for the Fedora 1 Release). (My experience with RedHat is: security fixes: yes; bug fixes: no). > The pydotorg RPM assumes that Tk uses UCS-4 internally, as it does on > Redhat 9. On Fedora 1, Tk uses UCS-2, so copying a Python Unicode string > into a Tcl Unicode string copies twice as many character as you have > (and overwrites some unrelated memory in the process). Thanks for the explanation! Now I got it. > There is, unfortunately, no way to detect the problem at run-time. So > I repeat: You *have* to compile from source. I just did that, following your advice. (Compiled Tcl/Tk 8.4 and Python 2.3 from the sources without deleting the Fedora 1 installation of Python 2.2 and Tcl/Tk 8.3; now - with my new Python/Tkinter 2.3, Tcl/Tk 8.4 - everything works as usual. Both, Python and Tcl/Tk, use UCS-2 now. I only had to rename the Python executable for Python 2.3 (so that it does not get executed when the system actually wants to use its own Python 2.2) and I have to use a startup script for Python 2.3 setting LD_LIBRARY_PATH, because otherwise libtk8.4.so is not found by Python in /usr/local/lib. The 'LD_LIBRARY_PATH'-script could be avoided with a permanent solution (symlink resp. ldconfig), but at the moment, this solution is OK for me.) Thanks a lot for your help! This really drove me nuts :-) Regards, Thomas. -- mailto: pushcold at hotpop.foo (where: foo = com) From claird at lairds.com Tue Nov 18 17:06:29 2003 From: claird at lairds.com (Cameron Laird) Date: Tue, 18 Nov 2003 22:06:29 -0000 Subject: pros and cons of Tkinter in comparison with other GUI toolboxes, please? References: Message-ID: In article , John Benson wrote: >-=-=-=-=-=- > >Hi, I'm seeing a lot of discussion about different GUIs. I understand >that there are reasons you might want to integrate more closely with >KDE, or Gnome, or Win32, but for standalone applications, I assume that >plain, old Tkinter is fine. Any comments? . . . Plain, old Tkinter is indeed fine enough to be the basis for quite a few interesting and useful applications, including the IDLE which is part of the standard distri- bution. -- Cameron Laird Business: http://www.Phaseit.net From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Fri Nov 21 07:20:11 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Fri, 21 Nov 2003 15:20:11 +0300 Subject: list of all functions defined in the current module In-Reply-To: References: Message-ID: Fernando Rodriguez wrote: > Hi, > > How can I get the list of all the functions defined in the current module? Here's what I managed to do: import inspect def listfunc(): me = __import__(inspect.getmodulename(__file__)) for name in dir(me): obj = getattr(me, name) if inspect.isfunction(obj): yield obj def foo(): pass def bar(): pass import listfunc for func in listfunc.listfunc(): print func It prints: regards, anton. From tim.one at comcast.net Tue Nov 25 17:51:31 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 25 Nov 2003 17:51:31 -0500 Subject: looking for 2.1.3 Windows binary with large file support In-Reply-To: <3FC3CF47.6040907@yeates.tv> Message-ID: >> Sorry, no version of Python 2.1 exists that supports large files on >> Windows. [Mathew] > Holy crud. That means my Plone Data.fs file is dead since its over 2 > Gigs in size. Hmmmmmm. Not good. You should take this to a Zope mailing list -- few people on c.l.py will know anything about this. Toby Dickenson's DirectoryStorage stores one object per file, and Shane Hathaway's PartitionedFileStorage spreads a large "virtual" Data.fs file over multiple physical files. Either can be used to overcome OS and Python limitations on file size. If you're going to stick with the combination of Python 2.1 and Windows, you really have no other choices if you need such a large database file. If I were you, I'd try moving to Python 2.3.2 first, along with the most recent Zope 2.7 beta release. At least use Python 2.3.2 and a current ZODB release to pack your Data.fs file until it's under 2GB again. Then it will be easier to switch to a different storage. But, again, ask about this stuff on a Zope list (if you want to make progress ). From aahz at pythoncraft.com Thu Nov 6 10:18:52 2003 From: aahz at pythoncraft.com (Aahz) Date: 6 Nov 2003 10:18:52 -0500 Subject: prePEP: Decimal data type References: Message-ID: In article , Jp Calderone wrote: >On Wed, Nov 05, 2003 at 01:55:09PM -0500, Aahz wrote: >> In article , >> Emile van Sebille wrote: >>> >>>...from which I infer that Context exists in part to limit/round >>>calculated results. Even if it were possible for me, as a user of >>>Decimal, to set Context appropriately to achieve these ends, what >>>if I use a library that also changes Context? The integrity of my >>>calculations may be impacted. >> >> That's correct. There needs to be a social convention that libraries >> intended for use by other people *CANNOT* muck with Context, and if they >> do so for their own internal calculations, they must save and restore >> Context. You can probably find additional information about this in >> Cowlishaw. > > Enter the context stack. Well, sure. And it won't be hard to add given that Decimal will already need to track thread-specific Context. But modules changing Context will still need to explicitly push and pop Context because usually you will just want to replace the current Context. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From newsgroups at jhrothjr.com Mon Nov 3 14:20:41 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 3 Nov 2003 14:20:41 -0500 Subject: Does python always need to compile ENTIRE program before it can start to run it??? References: Message-ID: "Christian Seberino" wrote in message news:bf23f78f.0311031044.478bf786 at posting.google.com... > I can achieve something similar to Python's automatic compilation > in C/C++ by making a script that compiles and runs my program like this: > > > make ; myprogram > > > I am trying to think of an advantage Python has over this hack.... > > Is it true that unlike C/C++ that Python programs can start executing > before compilation is COMPLETELY done??? I think so but I'm not sure. Since Python is a compiled language, yes, the programs have to be compiled before they run. However, Python saves the compiled version of all modules *except* the top level script, so it doesn't have to be redone on each execution. I've never gotten a satisfactory explanation of why it doesn't save the compiled version of the top level script, but then, I've never really looked into it. It's just curious. Compilation must be finished before the import statement can complete. John Roth > > Chris From bhicking at bhicking.plus.com Wed Nov 12 08:45:12 2003 From: bhicking at bhicking.plus.com (Limey Drink) Date: Wed, 12 Nov 2003 13:45:12 -0000 Subject: Automating FTP file transfers Message-ID: Hi all, Firstly :-) , is there any where I can search through archived newsgroup posts so I am not cluttering up the newsgroup with repeated queries ? And secondly :-), I know this has probably been discussed before but. I am wanting to do some scripting to automate a few administration tasks, one of the first tasks is automating FTP file transfers. I would like to know if the following could be made more robust using python and its FTP libraries rather than executing native OS commands in a shell script. Basically I need to... 1. Check on the local system for new files in a specific directory If new files exist then... 2. Connect to a remote FTP server. 3. Transfer local files to a specific directory on the remote FTP server. 4. Then remove/archive local files and end session. This is critical operation and though while in the past I have written DOS scripts etc. to do simple tasks I have not needed to check for errors as they weren't absolutely critical tasks. I am going to need to run this overnight using AT or CRON then I need to know about file transfer errors etc. and other problems that f I were actually performing the FTP transfer manually I would get feedback of the problem and could re-try the operation. Any help would be very appreciated. From andy at wild-flower.co.uk Sun Nov 9 16:45:00 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Sun, 9 Nov 2003 22:45:00 +0100 Subject: sharing dictionaries amongst class instances In-Reply-To: References: Message-ID: <200311092145.00823.andy@wild-flower.co.uk> On Sunday 09 Nov 2003 8:22 pm, Kerry Neilson wrote: > Hi, > Really hung up on this one. I'm trying to get all the fields of a > dictionary to be unique for each class: > > class A { > my_dict = [] > dict_entry = { 'key1':0, 'key2':0 } > > __init__(self): > for x in range(10): > tmp = copy.deepcopy(self.dict_entry) > tmp['key1'] = x > self.my_dict.append(tmp) > } > > in a driver, I have > > inst0, inst1 = A.A(), A.A() > inst0.my_dict[1]['key2'] = "ted" > inst1.my_dict[5]['key2'] = "steve" > inst0.display() > inst1.display() > > printing them out shows that both objects have ted and steve in their > dictionaries. I have done this very thing outside of a class, and it works > wonderfully. All other attributes in the class are able to remain unique. > ie, inst0.data = 5 and inst1.data = 8 works fine. > I believe I could set the dictionaries up beforehand, but they will be > substatially different sizes, and it certainly wouldn't be proper. > > Any ideas? Thanks very much for any insight. Kerry, two observations: 1) That's not proper Python! ;-) and 2) I think the behaviours you want are only available in 'new style' classes, i.e. classes based upon 'object'. Did you mean: ---8<--- class A(object): my_dict = [] dict_entry = { 'key1':0, 'key2':0 } def __init__(self): for x in range(10): tmp = copy.deepcopy(self.dict_entry) tmp['key1'] = x self.my_dict.append(tmp) ---8<--- A.my_dict is a /class variable/, i.e. it is tied to the class, not the instance - there's only one of them, viz: ---8<--- >>> inst0,inst1=A(),A() >>> id(inst0),id(inst1) # get the id of the instances: (1083256236, 1083254732) >>> id(inst0.my_dict),id(inst1.my_dict) # and the id of their my_dict lists: (1083253228, 1083253228) >>> inst0.my_dict is inst1.my_dict True >>> ---8<--- If you move the initial assignment of my_dict into the __init__() procedure, and call it self.my_dict() instead, then you'll get a new instance of a list each time - maybe this is what you want. BTW, is there any particular reason for choosing the word 'my_dict' to describe a list? hope this helps you arrive at a solution ;-) -andyj From mis6 at pitt.edu Thu Nov 13 05:02:54 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 13 Nov 2003 02:02:54 -0800 Subject: screensaver References: <2259b0e2.0311060704.754a4b6e@posting.google.com> Message-ID: <2259b0e2.0311130202.2f2d2e8d@posting.google.com> "Michael Geary" wrote in message news:... > Thomas Heller: > > A google search for 'disable screensaver windows' turns up VB code, > > which easily translates into this Python code: > > > > ----- > > import ctypes > > SPI_SETSCREENSAVEACTIVE = 17 > > > > def StartScreenSaver(on): > > ctypes.windll.user32.SystemParametersInfoA( > > SPI_SETSCREENSAVEACTIVE, on, None, 0) > > > > StartScreenSaver(1) > > ----- > > > > Unfortunately, it doesn't seem to work (for me, on XP. At least it has > > no visible effect). > > Your StartScreenSaver() function should probably be called > EnableScreenSaver(). Call it with a 0 parameter to disable the screen saver, > or 1 to enable it. > > The function won't have any immediate visible effect--it simply enables or > disables the screen saver, it doesn't start or stop it. > > Try setting your screen saver timeout to one minute. Let the computer sit > for a minute to verify that the screen saver is working. Then call > EnableScreenSaver(0) to disable the screen saver, and let the computer sit > for a minute again to see if you've disabled it. > > -Mike I have just installed ctypes and tried this solution. It works perfectly well !;) Thanks to everybody who helped here, Michele From eppstein at ics.uci.edu Tue Nov 4 11:25:36 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 04 Nov 2003 08:25:36 -0800 Subject: nearest neighbor in 2D References: Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > This is of course all premature optimization as the most promising approach > is to try hard to reduce the number of candidate points, as David Eppstein > seems to have done. But then, he could use complex numbers, too. Well, yes, but then my code wouldn't work very well in dimensions higher than two... -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From jponiato at chartermi.nojunk Fri Nov 7 19:00:31 2003 From: jponiato at chartermi.nojunk (news.chartermi.net) Date: Fri, 7 Nov 2003 19:00:31 -0500 Subject: NEWBIE: lists as function arguments References: Message-ID: Thanks, everyone - I knew you folks could help me understand. This is still me, JP, posting from another account. "Joe Poniatowski" wrote in message news:bogkj1$cfk11 at eccws12.dearborn.ford.com... > From what I've read in the tutorial and FAQ, I should be able to pass a > mutable object like a list as a function argument, and have the caller see > changes made to the list by the function. I must be doing something wrong - > the function in this case assigns items to the list, but in the main module > it's still empty: > > Python 2.3.2 (#1, Oct 23 2003, 11:10:37) > [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-81)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> ls = [] > >>> def f1(l2=[]): > ... l2 = ['word1','word2'] > ... print l2 > ... > >>> f1(ls) > ['word1', 'word2'] > >>> ls > [] > >>> > > However, I can return the list and it works OK: > >>> ls = [] > >>> def f1(l2=[]): > ... l2 = ['word1','word2'] > ... print l2 > ... return l2 > ... > >>> ls = f1(ls) > ['word1', 'word2'] > >>> ls > ['word1', 'word2'] > > Am I missing something or just interpreting the documentation wrong? > Jp > > From Matteo.Risoldi at cern.ch Tue Nov 25 10:25:37 2003 From: Matteo.Risoldi at cern.ch (Matteo Risoldi) Date: Tue, 25 Nov 2003 16:25:37 +0100 Subject: win32com (VBScript to Python) problem References: <6e24de564c.tim@worthy.demon.co.uk> <4700e5564c.tim@worthy.demon.co.uk> <4428ee564c.tim@worthy.demon.co.uk> Message-ID: Just a comment: is shutdown.exe leaves the machine in the "you can switch off", try shutdown -s, it does the job for me. M. From no.spam at no.smap.com Mon Nov 10 03:23:22 2003 From: no.spam at no.smap.com (Maciej Sobczak) Date: Mon, 10 Nov 2003 09:23:22 +0100 Subject: Inter-Process comunication In-Reply-To: References: Message-ID: Hi, Zunbeltz Izaola wrote: > I'm no proffesional programmer and i don't know > wich technique is the best, signals, theread, anothero one ... > Any sugestions? Please take a look at YAMI: http://www.msobczak.com/prog/yami/ You may wish to see the Python tutorial: http://www.msobczak.com/prog/yami/impl/files/pythontut.html to see if it's easy enough and whether it fits your needs. In case of any questions, please do not hesitate to contact me. -- Maciej Sobczak : http://www.msobczak.com/ Programming : http://www.msobczak.com/prog/ From Pierre-et-Liliane.DENIS at village.uunet.be Sun Nov 16 15:18:01 2003 From: Pierre-et-Liliane.DENIS at village.uunet.be (Pierre Denis) Date: Sun, 16 Nov 2003 21:18:01 +0100 Subject: ANN: Unum 4.0 beta Message-ID: <3fb7dbfd$0$241$4d4efb8e@news.be.uu.net> Unum 4.0 beta is now available on http://home.tiscali.be/be052320/Unum.html. This Python module allows you to work with units like volts, hours, meter-per-second or dollars-per-spam. So you can play with true quantities (called 'unums') instead of simple numbers. Consistency between units is checked at each expression evaluation and an exception is raised when something is wrong, for instance, when trying to add apples to bananas. Unit conversion and unit output formatting are performed automatically when needed. The main goals are to avoid unit errors in your calculations and to make unit output formatting easy and uniform. This new version encompasses all the SI units and allows you to define your own libraries of units, with specific names and symbols. Other improvements makes this version more solid : compatibility with NumPy, packages, misc optimizations, true exceptions, new-style class, static methods, etc. The installation also should be easier and more standard through installation files. The site and tutorial page have been updated to give more accurate information. This 4.0-beta version is stable, fairly. The term 'beta' essentially means that problems may potentially occur at installation on specific OS. I made successful installation tests on Windows 98, XP and Red Hat Linux 7.2. Besides this, the choices I made for unit names and symbols are subject to change if I receive more sensible suggestions. Of course, any other ideas, comments or criticisms are welcome before releasing the official Unum 4.0 (no planning yet). This version requires Python 2.2 (at least). The license is GPL. Thanks for your interest, Pierre Denis From http Fri Nov 21 12:08:13 2003 From: http (Paul Rubin) Date: 21 Nov 2003 09:08:13 -0800 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <7xad6sb7cd.fsf@ruckus.brouhaha.com> <87smkjw55g.fsf@pobox.com> <7xy8ubdl1f.fsf@ruckus.brouhaha.com> <87smkitutw.fsf@pobox.com> Message-ID: <7xr801zm2q.fsf@ruckus.brouhaha.com> Nick Vargish writes: > > the act of obtaining such a program is itself a psychological > > barrier to decryption: you can't fool yourself about what you're > > doing. > > Not just a psychological barrier, but a legal one, if your aim is to > provide a possible basis for future litigation. Rotor is not needed to provide that barrier. You can do the same thing with a simple xor against the key. From peter at engcorp.com Tue Nov 11 12:49:17 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Nov 2003 12:49:17 -0500 Subject: Writing UTF-8 string to UNICODE file References: <4e9sb.154$s8.2312@news.on.tac.net> Message-ID: <3FB1211D.27E2150F@engcorp.com> Michael Weir wrote: > > I'm sure this is a very simple thing to do, once you know how to do it, but > I am having no fun at all trying to write utf-8 strings to a unicode file. > Does anyone have a couple of lines of code that > - opens a file appropriately for output > - writes to this file I can't give you an example, never having done this, but if you would post a few lines of your own code which you thought would work, someone can probably point out the error of your ways more easily than writing something from scratch. (Of course, we'll shortly see a complete working solution from someone anyway, but in general this is the better way to proceed with such a problem.) -Peter From ville.spammehardvainio at spamtut.fi Tue Nov 18 02:00:40 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 18 Nov 2003 09:00:40 +0200 Subject: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <8hfsb.7707$nz.895@newsread2.news.pas.earthlink.net> <1069126283.450927@yasure> Message-ID: "Donn Cave" writes: > Python may be a hybrid, but certainly none of its parents were FPLs. > Trying to make it one gives both Python and FP a bad name. If you I don't think there is much "trying to make Python a FPL" involved w/ making lots of tried-and-true FPL constructs available in Python. It's just taking stuff that works and enabling us to use it w/o encumbering the language (because it's in the modules). It's all good as long as we don't go the way of doing everything w/ recutrsion. > want a language that really supports both functional and procedural > styles, I think you need Lisp. Look at Dylan, I haven't tried it but > it may be quite a bit more comfortable for Python and C programmers. Lisp is too verbose for my tastes (I don't want to write 'let' ot 'setq'), doesn't have much in the way of libs and generally doesn't feel as 'right' as Python (I do use Emacs Lisp occasionally, though.. and will try out some CL one of these days). Dylan, OTOH, doesn't seem to be all that active a project, at least the last time I checked. -- Ville Vainio http://www.students.tut.fi/~vainio24 From tinmean.bbs at wretch.csie.nctu.edu.tw Fri Nov 21 01:09:53 2003 From: tinmean.bbs at wretch.csie.nctu.edu.tw (tinmean) Date: 21 Nov 2003 06:09:53 GMT Subject: Chinese input for python and MySQL Message-ID: <49LZ6H$DO6@wretch.csie.nctu.edu.tw> hi, I have some problem when I use MySQLdb.connect.cursor() to create some Chinese(Big5) strings data, but it is no use. The reference is from the Deitel's "How to program:Python". The code can't work when the strings are Chinese. Thanks --Tinmean ---------------------------------------------------------------- # Fig. 17.30: fig17_30.py # Inserts into, updates and searches a database. import MySQLdb from Tkinter import * from tkMessageBox import * import Pmw class AddressBook( Frame ): """GUI Database Address Book Frame""" def __init__( self ): """Address Book constructor""" Frame.__init__( self ) Pmw.initialise() self.pack( expand = YES, fill = BOTH ) self.master.title( "Address Book Database Application" ) # buttons to execute commands self.buttons = Pmw.ButtonBox( self, padx = 0 ) self.buttons.grid( columnspan = 2 ) self.buttons.add( "Find", command = self.findAddress ) self.buttons.add( "Add", command = self.addAddress ) self.buttons.add( "Update", command = self.updateAddress ) self.buttons.add( "Clear", command = self.clearContents ) self.buttons.add( "Help", command = self.help, width = 14 ) self.buttons.alignbuttons() # list of fields in an address record fields = [ "ID", "First name", "Last name", "Address", "City", "State Province", "Postal Code", "Country", "Email Address", "Home phone", "Fax Number" ] # dictionary with Entry components for values, keyed by # corresponding addresses table field names self.entries = {} self.IDEntry = StringVar() # current address id text self.IDEntry.set( "" ) # create entries for each field for i in range( len( fields ) ): label = Label( self, text = fields[ i ] + ":" ) label.grid( row = i + 1, column = 0 ) entry = Entry( self, name = fields[ i ].lower(), font = "Courier 12" ) entry.grid( row = i + 1 , column = 1, sticky = W+E+N+S, padx = 5 ) # user cannot type in ID field if fields[ i ] == "ID": entry.config( state = DISABLED, textvariable = self.IDEntry, bg = "gray" ) # add entry field to dictionary key = fields[ i ].replace( " ", "_" ) key = key.upper() self.entries[ key ] = entry def addAddress( self ): """Add address record to database""" if self.entries[ "LAST_NAME" ].get() != "" and \ self.entries[ "FIRST_NAME"].get() != "": # create INSERT query command query = """INSERT INTO addresses ( FIRST_NAME, LAST_NAME, ADDRESS, CITY, STATE_PROVINCE, POSTAL_CODE, COUNTRY, EMAIL_ADDRESS, HOME_PHONE, FAX_NUMBER ) VALUES (""" + \ "'%s', " * 10 % \ ( self.entries[ "FIRST_NAME" ].get(), self.entries[ "LAST_NAME" ].get(), self.entries[ "ADDRESS" ].get(), self.entries[ "CITY" ].get(), self.entries[ "STATE_PROVINCE" ].get(), self.entries[ "POSTAL_CODE" ].get(), self.entries[ "COUNTRY" ].get(), self.entries[ "EMAIL_ADDRESS" ].get(), self.entries[ "HOME_PHONE" ].get(), self.entries[ "FAX_NUMBER" ].get() ) query = query[ :-2 ] + ")" # open connection, retrieve cursor and execute query try: connection = MySQLdb.connect( "localhost","root","wuhwetin",db = "AddressBook" ) cursor = connection.cursor() cursor.execute( query ) except MySQLdb.OperationalError, message: errorMessage = "Error %d:\n%s" % \ ( message[ 0 ], message[ 1 ] ) showerror( "Error", errorMessage ) else: cursor.close() connection.close() self.clearContents() else: # user has not filled out first/last name fields showwarning( "Missing fields", "Please enter name" ) def findAddress( self ): """Query database for address record and display results""" if self.entries[ "LAST_NAME" ].get() != "": # create SELECT query query = "SELECT * FROM addresses " + \ "WHERE LAST_NAME = '" + \ self.entries[ "LAST_NAME" ].get() + "'" # open connection, retrieve cursor and execute query try: connection = MySQLdb.connect( "localhost","root","wuhwetin",db = "AddressBook" ) cursor = connection.cursor() cursor.execute( query ) except MySQLdb.OperationalError, message: errorMessage = "Error %d:\n%s" % \ ( message[ 0 ], message[ 1 ] ) showerror( "Error", errorMessage ) self.clearContents() else: # process results results = cursor.fetchall() fields = cursor.description if not results: # no results for this person showinfo( "Not found", "Nonexistent record" ) else: # display person's info. in GUI self.clearContents() # display results for i in range( len( fields ) ): if fields[ i ][ 0 ] == "ID": self.IDEntry.set( str( results[ 0 ][ i ] ) ) else: self.entries[ fields[ i ][ 0 ] ].insert( INSERT, str( results[ 0 ][ i ] ) ) cursor.close() connection.close() else: # user did not enter last name showwarning( "Missing fields", "Please enter last name" ) def updateAddress( self ): """Update address record in database""" if self.entries[ "ID" ].get() != "": # create UPDATE query command entryItems = self.entries.items() query = "UPDATE addresses SET" for key, value in entryItems: if key != "ID": query += " %s='%s'," % ( key, value.get() ) query = query[ :-1 ] + " WHERE ID=" + self.IDEntry.get() # open connection, retrieve cursor and execute query try: connection = MySQLdb.connect( "localhost","root","wuhwetin",db = "AddressBook" ) cursor = connection.cursor() cursor.execute( query ) except MySQLdb.OperationalError, message: errorMessage = "Error %d:\n%s" % \ ( message[ 0 ], message[ 1 ] ) showerror( "Error", errorMessage ) self.clearContents() else: showinfo( "database updated", "Database Updated." ) cursor.close() connection.close() else: # user has not specified ID showwarning( "No ID specified", """ You may only update an existing record. Use Find to locate the record, then modify the information and press Update.""" ) def clearContents( self ): """Clear GUI panel""" for entry in self.entries.values(): entry.delete( 0, END ) self.IDEntry.set( "" ) def help( self ): """Display help message to user""" showinfo( "Help", """Click Find to locate a record. Click Add to insert a new record. Click Update to update the information in a record. Click Clear to empty the Entry fields.\n""" ) def main(): AddressBook().mainloop() if __name__ == "__main__": main() ########################################################################## # (C) Copyright 2002 by Deitel & Associates, Inc. and Prentice Hall. # # All Rights Reserved. # # # # DISCLAIMER: The authors and publisher of this book have used their # # best efforts in preparing the book. These efforts include the # # development, research, and testing of the theories and programs # # to determine their effectiveness. The authors and publisher make # # no warranty of any kind, expressed or implied, with regard to these # # programs or to the documentation contained in these books. The authors # # and publisher shall not be liable in any event for incidental or # # consequential damages in connection with, or arising out of, the # # furnishing, performance, or use of these programs. # ########################################################################## -- ????????????????????????????????????? ?????BBS telnet://wretch.twbbs.org ????????BBS??????? ????????????????????????????????????? ????????????????????????????????????? ?????????????????????????evpc178.ev.nctu.edu.tw? From inyeol.lee at siimage.com Wed Nov 19 20:17:49 2003 From: inyeol.lee at siimage.com (Inyeol Lee) Date: Wed, 19 Nov 2003 17:17:49 -0800 Subject: strange behaviour of sum() In-Reply-To: References: Message-ID: <20031120011749.GB21561@siliconimage.com> On Wed, Nov 19, 2003 at 11:46:07PM +0100, Jan-Erik Meyer-L?tgens wrote: [...] > I'd ran into trouble when I've used sum() naively: [...] > The other strange behaviour is: > > sum(['my', 'pet', 'fish', 'eric'], '') > > results in: > > TypeError: sum() can't sum strings [use ''.join(seq) instead] > > If there is a special treatment for strings, why doesn't sum() > use ''.join(seq) itself, instead of telling me that I should > use it? But in fact sum() should call operator.add(), even > for strings: There was a duscussion on this in python-dev. See thread starting from http://mail.python.org/pipermail/python-dev/2003-April/034767.html and Guido's summary at http://mail.python.org/pipermail/python-dev/2003-April/034853.html . -Inyeol Lee From csad7 at yahoo.com Mon Nov 24 12:11:21 2003 From: csad7 at yahoo.com (christof hoeke) Date: Mon, 24 Nov 2003 18:11:21 +0100 Subject: XML and Python by Ogbuji - book at amazon? In-Reply-To: References: Message-ID: Uche Ogbuji wrote: > christof hoeke wrote in message news:... > >>hi, >>does anyone know about this book which sounds great? unfortunately i >>could not find anything more about it apart from the following entry at >>amazon (germany only, strange...) >> >>http://www.amazon.de/exec/obidos/ASIN/0764547798/qid=1069188100/sr=1-4/ref=sr_1_8_4/302-8869636-4168805 >> >>at least Uche should know about it? > > > My apologies for the confusion. This book was in the works, but ended > up in the can aprtly from Mine and Mike Olson's lack of time, and > partly because of the drying up of the market in technical books. > > I'm afraid that what knowledge I have to offer on Python and XML is > available either in my XML.com column: > > http://www.xml.com/pub/q/pyxml > > or in my Python/XML Akara project > > http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/pyxml-akara > > Good luck. > > thanks for the info. i consult all the above sites anyway but a good updates printed book would have been great as one has to dig through all the sites and available books to find answers. i thought your planned book would have been a great updated kind of "python and xml" book. but thanks and best regards chris From http Sat Nov 29 15:30:39 2003 From: http (Paul Rubin) Date: 29 Nov 2003 12:30:39 -0800 Subject: Filtering through an external process Message-ID: <7xllpyyl1s.fsf_-_@ruckus.brouhaha.com> Anyone know if there's code around to filter text through an external process? Sort of like the Emacs "filter-region" command. For example, say I have a program that reads input in English and outputs it in Pig Latin. I want my Python script to call the program, pipe some input into it and read the output: english = "hello world" pig_latin = ext_filter("pig_latin", english) should set pig_latin to "ellohay orldway". Note that you can't just call popen2, jam the english through it and then read the pig latin, because the subprocess can block if you give it too much input before reading the output, and in general there's no way to know how much buffering the subprocess is willing to do. So a proper solution has to use asynchronous i/o and keep polling the output side, or else separate threads for reading and writing. This is something that really belongs in the standard library. I've needed it several times and rather than going to the trouble of coding and debugging it, I've always ended up using a temp file instead, which is a kludge. From adalke at mindspring.com Mon Nov 3 00:22:09 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 03 Nov 2003 05:22:09 GMT Subject: ANN: pyfromc - Python from C++ and vice versa References: <3fa3488c.12101640@news.t-online.de> <3FA3B325.1491D228@engcorp.com> <3fa3c4e1.43930000@news.t-online.de> <2dGdncyBTpWEkDmiRVn-ig@comcast.com> Message-ID: <5Clpb.4352$qh2.1758@newsread4.news.pas.earthlink.net> JanC: > AFAIK in Belgium (and several other European countries) you can't legally > put your own work in the public domain; an author always keeps his or her > "author rights" (which includes copyright). Is there work for hire, so that the copyright goes to the employer? Can the employer sell that copyright to someone else? Are government works covered under copyright? In the US, they are not, and are always in the public domain. Can works enter the public domain after a period of time? Andrew dalke at dalkescientific.com From mikit at zoran.co.il Thu Nov 27 02:46:54 2003 From: mikit at zoran.co.il (Miki Tebeka) Date: 26 Nov 2003 23:46:54 -0800 Subject: a newbie References: Message-ID: <6250403b.0311262346.1ba21914@posting.google.com> Hello, > I am new to python.I have familiarized myself with Python through Doc. > and, simple code.My question is really about pygame.Which is somthing > I am very unfamiliar with.I could really use some honest advice about > getting started in python or pygame.I would like to learn Python as > my first programing language.IF somone could spare a litle time.I > would greatly appreciate as i know it is really precious.Anybody with > any suggestions on ways they might have started will be put to use. http://www.python.org/doc/Intros.html Start with "Introductions to Python programming for non-programmers" My advice is to start slowly, if you'll try to do too much you'll get frustrated. Programming is a art, it take time to know how to do it right and there are only a handfull of greate programmers out there. Lucky for you Python is greate for newbies and you dont need to be a grand master of the language to produce greate programs. Last advice: Start programming user interface (GUI) only after you have written some batch mode programs. GUI programming is an art of itself. HTH. Miki From robin at jessikat.fsnet.co.uk Mon Nov 10 19:36:39 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 11 Nov 2003 00:36:39 +0000 Subject: Subclassing String in C Message-ID: A client program wants to pass my code truetype font files which have already been loaded in memory. Our existing Python/c code reads ttf files into memory as strings. I can easily do the same providing the client knows the data length. I would like to avoid the memory overhead of n+1 bytes which that would involve by making a kind of readonly string that refers directly to the client memory. I can think of two possible approaches 1) implement a buffer compatible type from scratch 2) co-opt PyString_Type to subclass String and implement a special version of PyString_FromStringAndSize that doesn't copy and ensure that deallocation is handled properly. Any body already invented this kind of wheel? Are there obvious pitfalls (other than dangling reference issues etc)? -- Robin Becker From mwilson at the-wire.com Sun Nov 2 09:19:06 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 02 Nov 2003 09:19:06 -0500 Subject: None References: Message-ID: In article , "Daniel Sch?le" wrote: >Hi NG > > > >def executer(func, para): > func(para) > >def foo(): > print "function without parameter" > >def bar(a): > print "function with 1 parameter" > print a > >#executer(foo, None) #error > >executer(bar, 100) > >print type(foo) >print type(bar) >#seem to have the same type, though one takes parameter and the other doesnt > >does this mean that None *is* a value >some special value to show that variable cant be initialized with more >appreciate value >at this stage? That's what it means. The way to call foo is `foo()`. > >is there a way to allow parameterless functions as parameter in executer? def executer (func, para): foo (*para) will allow you to specify the parameter list explicitely. Then executer (foo, ()) ... executer (bar, (1,)) ... def baz (a, b): print "2 params:", a, b executer (baz, (1, 2)) Regards. Mel. From lol at lolmc.nospam.com Fri Nov 14 05:26:32 2003 From: lol at lolmc.nospam.com (Lol McBride) Date: Fri, 14 Nov 2003 10:26:32 +0000 Subject: trouble with unittest and namespaces - can anyone help? References: <3FB176E4.B3F7D534@engcorp.com> <3FB24E38.81035D47@engcorp.com> Message-ID: thanks for the tip Peter it worked a treat. I'm also busy looking through the docs as you mentioned. Thanks again. Lol From jeder at earthlink.net Tue Nov 25 03:22:16 2003 From: jeder at earthlink.net (Ryan Spencer) Date: Tue, 25 Nov 2003 08:22:16 GMT Subject: sleep() function, perhaps. References: Message-ID: On Tue, 25 Nov 2003 06:14:20 +0000, Christopher Koppler wrote: > On Tue, 25 Nov 2003 05:26:25 GMT, Ryan Spencer > wrote: > >> >>Hello Everyone, >> >> I want to have a row of periods, separated by small, say, .5 second >>intervals between each other. Thus, for example, making it have the >>appearance of a progress "bar". >> >>[code] >>import time >> >>sleep(.5) >>print "." >>sleep(.5) >>print "." >>[end code] >> >>But, it would (with those .5 second intervals) >>print out much like the following. >> >>. >>(pause) >>. >>(pause) >> >>I would rather those periods be on a single line, not printing on a new >>line each time. >> >>Any suggestions? > > Try print with added comma or sys.stdout.write, like so: > >>>> import time >>>> for i in range(10): > ... print '\b.', > ... time.sleep(1.5) > ... > .......... >>>> import sys >>>> for i in range(10): > ... sys.stdout.write('.') > ... time.sleep(0.5) > ... > .......... Heya', Thanks, Actually though, None of those suggestions give me the desired result I was looking for. I used both with the for loops, even the one with the while loop, and for the first suggested it prints all of them out on new lines (as opposed to all on the same line as I'd been hoping for) and the second posts on one full line, yet, the periods still don't have pauses between themselves. Perhaps something else is amiss? As well, the trailing commas gives the exact same result as doing the sys.stdout.write function. Is the code that you suggested giving you a result such as... .(pause).(pause).(pause). I raised everything up to a 1.5 second interval to exaggerate the results, and I'm afraid I still don't notice the pauses. Perchance I simply need to remove whatever is terminating the line? Does the time.sleep() function itself terminate a line? It would seem if I could bypass that, it would allow the pauses and keep the periods on one line. Thank you for your advice though, It's highly appreciated. ~Ryan From baljiangusa at yahoo.com Mon Nov 10 23:10:30 2003 From: baljiangusa at yahoo.com (Ling Jiang) Date: 10 Nov 2003 20:10:30 -0800 Subject: 2.3.2 complilatiion problem References: Message-ID: <6f2052c8.0311102010.2318d269@posting.google.com> Thanks for the advices. It worked, with 5.6 being altered to reflect release number of the OS, which is 5.9 in my case. Thanks Ling Jiang Nigel Rowe wrote in message news:... > navigating wrote: > > > The attached (gcc.err) came out of the compilation on solaris 9 on an > > intel platform using gcc. I've also attached the config.log. Please > > advise. > > > > Regards. > > > > Ling Jiang > > First bit of advice, do *NOT* post 11,000 line (320k) log files!!! > > 2nd. When I get to the 'gcc.err' part of your post (after working around the > tendency for my newreader to freeze when presented with 11000 line posts. > Got the hint?) I see the error is "previous declaration of 'va_list'" > > 2 Mins with google leads to > https://sourceforge.net/tracker/?func=detail&atid=105470&aid=690317&group_id=5470 > so you might try zenzen's suggestion. > > --8<-- > Hacking configure so it looks like the following > allows python to build: > case $ac_sys_system/$ac_sys_release in > # On OpenBSD, select(2) is not available if > _XOPEN_SOURCE is defined, > # even though select is a POSIX function. Reported by J. > Ribbens. > SunOS/5.6 | OpenBSD/2.* | OpenBSD/3.[012]) > define_xopen_source=no;; > esac > --8<-- > > Beyond this I cannot help as I have no access to any solaris box From emile at fenx.com Sat Nov 29 16:52:02 2003 From: emile at fenx.com (Emile van Sebille) Date: Sat, 29 Nov 2003 13:52:02 -0800 Subject: sorting dictionary keys? References: Message-ID: John Smith > Hi, what's the fastest way (least amount of typing) to sort dictionary > objects by the key? What's the fastest way of iterating over sorted keys > for a dictionary in terms of performance? Are the two equivalent? > > The way I have been doing it is: > > d = {} > #populate d > keys = d.keys() > keys.sort() > for k in keys: > print k, d[k] > > but I would like to do: > #error here > for k in d.keys().sort(): sort sorts in place and doesn't return anything. In 2.4 you'll have the sorted method. > print k, d[k] > > why doesn't the nested function call work? Thanks in advance. > > The shortest thing to type? You're there with s = d.keys() and s.sort(). -- Emile van Sebille emile at fenx..com From mhammond at skippinet.com.au Wed Nov 26 18:19:31 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 27 Nov 2003 10:19:31 +1100 Subject: Creating a Python installer in win32 In-Reply-To: References: <2XVwb.40137$Fv8.32356@twister01.bloor.is.net.cable.rogers.com> Message-ID: Patrick wrote: > On Wed, 26 Nov 2003 04:25:34 +0000, martin z wrote: > > >>Hey, all. I'll get to the point: project for class, got most of my needs >>figured out, just unsure about one detail: this is a large-scale design >>course, so it has to be a complete win32 app. That means a standalone >>installer. I can't just say "go fetch Python, then run this .py file". >>Anybody know how to set such a thing up? > > > Yes. > > http://homepages.tesco.net/~J.deBoynePollard/FGA/questions-with-yes-or-no-answers.html In the real world, if you were asked "do you have the time?", would you truly asnwer "Yes" and walk-away? Do-unto-others-as-you-would-do-unto-them-in-the-real-world ly, Mark. From max at cNvOiSsiPoAnMtech.com Wed Nov 19 15:44:24 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Wed, 19 Nov 2003 20:44:24 GMT Subject: PIL and jpg -> png conversion, do I really need java for this??? In-Reply-To: References: Message-ID: Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: > Guys, I gave up. > > I can't figure out why the PNG converted in PIL won't work in the MIDP applications written in Java. There is something different but I really don't know what. > All PNG generated from ImageMagick, GIMP or whatever, they work fine, from PIL, no. > The conversion in Java using JIMI works fine as well. > The option of executing scripts from Python using these external tools is not really what I like. What platform are you working on? if it's windows/linux you could probably python-wrap (I recommend boos.python) CxImage http://www.codeproject.com/bitmap/cximage.asp - it's about time someone did it anyway! max. From rainerd at eldwood.com Wed Nov 12 21:12:38 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Thu, 13 Nov 2003 02:12:38 GMT Subject: case-sensitivity References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> Message-ID: Ron Adam wrote: > Which would you choose from the following? Here are the options I see, in order of preference: 1. The compiler enforces a consistent capitalization scheme, preferably all_lower_case. Note that MixedCase is only consistent if PsychoTheRapist is a different identifier than Psychotherapist. Different syntactical elements (identifiers vs keywords) are allowed to use different schemes. 2. Traditional case sensitivity: Bob and bOb are different identifiers. 3. Case insensitity. What your editor does is an orthogonal issue and irrelevant to me; what my editor does is let me type what I want without correcting me. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From jjl at pobox.com Mon Nov 10 17:41:58 2003 From: jjl at pobox.com (John J. Lee) Date: 10 Nov 2003 22:41:58 +0000 Subject: response time References: <1jSrb.2419$9_.105379@news1.tin.it> Message-ID: <8765hrethl.fsf@pobox.com> forgot to add: time.clock() might be more useful on Windows, if you want high precision. John From jjl at pobox.com Tue Nov 18 07:40:46 2003 From: jjl at pobox.com (John J. Lee) Date: 18 Nov 2003 12:40:46 +0000 Subject: Unit Testing Examples References: Message-ID: <87he11vohd.fsf@pobox.com> tom_verbeure at hotmail.com (Tom Verbeure) writes: > so I'm now convinced that unit testing is really the way to go and I > want to add it to an existing project. The first thing that I find > out, is that, well, it's hard work. Harder than writing the real > functional code. Graphs aside, it's easier 1. when you write them before you write the code 2. when you get some practice (of course). [...] > I'm not sure, though, at what level I have to write unit tests. It's > easy to write a tests that validates the consistency of a single node > of a graph, but the real complexity is, of course, in the interaction > of multiple nodes. [...] Test at both levels. Also, even for a graph object containing nodes (if that's how it's written), it can make sense to test the graph object independently of the nodes. Sometimes you look at tests like that and think "how could that possibly fail?", but it's surprising how often they do if you do any refactoring (and even bug fixing, sometimes). This is related to "mock objects", though I think mock objects are worth avoiding if they don't turn out to be necessary. I certainly don't like to put this forward as a beacon of good practice, but I was quite unhappy with the tests in ClientForm (too long, too apparently repetitive and trivial), *until* I wanted to port it from an event-based HTML parser to a DOM. I was amazed at the number of tests that failed in subtle ways. If I didn't have the tests, I would never have finished it, I'm quite sure, and the tests I thought were not pulling their weight turned out to be valuable. Elegant graph algorithms and messy W3C standards (both HTML DOM and HTML are quite nasty) are different things, and the latter has more to benefit from unit tests, but I think it's worth experimenting with the more paranoid end of unit testing. One thing I don't do and I'm quite sure is valuable is code coverage measurement, so if I were starting afresh I'd be attracted to amk's framework (though there are several tools to do it with unittest -- they're just not integrated to make it trivial). As a BTW, one interesting thing about moving from an event parser to a DOM (and kept the old implementation: the event-based code is still in use) was that the unit-test nature of some of the tests was actually a hindrance to getting the tests running, and a barrier to maintainability. Necessary background: the module parses HTML to get a list of HTMLForm objects; HTMLForms contain Control objects (controls are things like text entry boxes, buttons, menus, checkboxes). Now, my tests of the various Controls constructed Controls directly rather than using the parser -- these were supposed to be unit tests, after all, so I didn't want to be testing the Controls *and* the parser at the same time. The problem, of course, was (still is, I haven't fixed it yet) that when I started using the DOM, the constructors for the Control objects changed completely, and I had to fork the test code in a nasty way just to get the tests to run. If I'd just been lazy and used the parser interface to build Control objects, I could have run the tests with almost no changes. Not entirely sure what the moral of this story is yet... maybe just. John From mwilson at the-wire.com Sun Nov 2 09:31:38 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 02 Nov 2003 09:31:38 -0500 Subject: It's still I, Miville References: Message-ID: In article , Todd Stephens wrote: >On Sat, 01 Nov 2003 22:08:58 -0500, Fran?ois Miville-Dech?ne wrote: > >> You say in the definition of mappings that at present Python has only > >> You say Python is an evolving language, prove it. > >> To take on another subject, an object-oriented language such as yours >> should > >> Your language appears in a calculator fashion, the user is reassured > >Your 'suggestions' walk a fine line between constructiveness and trolling >with the 'your language' and 'you say' references. The ethos of open source is: "If you don't see it, make it." Regards. Mel. From haris.bogdanovic at zg.htnet.hr Sat Nov 1 13:12:39 2003 From: haris.bogdanovic at zg.htnet.hr (Haris Bogdanovic) Date: Sat, 01 Nov 2003 19:12:39 +0100 Subject: simple echo server Message-ID: I'm trying to implement chess server program so I started by implementing simple echo server. When client is trying to connect to the server everything works fine but when server tries to echo what it receieved from client I get access denied error. Why is that happening ? (I put my server.py under ("m-net.arbornet.org") my user account. Is this the right place to put server program or is there a place on the Net where such applications are welcome ? ) Thanks Haris From joconnor at nets.com Sun Nov 23 21:25:26 2003 From: joconnor at nets.com (Jay O'Connor) Date: Sun, 23 Nov 2003 19:25:26 -0700 Subject: Empty list as default parameter In-Reply-To: <7xfzge1rzg.fsf@ruckus.brouhaha.com> References: <7xislb238p.fsf@ruckus.brouhaha.com> <7xsmkf1uwk.fsf@ruckus.brouhaha.com> <7xfzge1rzg.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >bokr at oz.net (Bengt Richter) writes: > > >> changing the dynamic nature of the language. >> >> > >I think some of that dynamicness should be toned down as Python matures. > One aspect of Python's dynamic nature that has always intrigued me is in the terms of how instance variables. Python allows you to dynamically add instance variables as you need, which is pretty cool, but seems to require a lookup of every instance variable reference, which can be pretty slow. Consider the following test case, using Python 2.3 on Win95 in IDLE: ===================== class A: def __init__(self, val=1): self.value= val def setval (self, v): self.value=v def getval (self): return self.value def test(self): for x in range (1,1000000): self.value = 1 y = self.value import time a = A() print "start" t1 = time.time() a.test() t2 = time.time() print t2 - t1 print "done" ===================== This routinely return values of over 6.3. Swithing the implementation of test() to use the accessor methods kicked the times up to over 20 seconds By contrast the equvalent Smalltalk* code (VisualWorks 7,1) on the same machine. gave me consistant results of a little over 600 milliseconds when using direct variable access and roughly 1.5 seconds when using accessors. I think a portion of the difference in that in Smalltalk, instance variables are specified in the class metadata (in terms of ordering) when the class is compiled and thus an instance variable reference is just a pointer offset from the start of the object data in memory and thus the compiler can optimize instance variable reference by just compiling in the offset into the the mehod code. This is a case where Python is more dynamic than Smalltalk in that Python allows easy addition of instance variables to objects, but it comes at a price in terms of performance. The Smalltalk solution to adding instance variables dynamically is just to carry around a dictionary (similar to Python) but most experienced Smalltalkers know that "instance variables are much faster than dictionary lookups so consider if this is really the right design and consider the performance/flexibility tradeoff" This is one case where I think Python's flexibility hurts it in the long run and perhaps as it goes forward, it will adapt to a more rigid style that will provide for better performance without too much tradeoff. After all, Python is still very young, Smalltalk has a twenty year head start on it. *Smalltalk code ====================== A>>#test | y | 10000000 timesRepeat: [ self value: 1. y := self value ] ----------- | a | a := A new. Time millisecondsToRun: [a test]. ====================== From guettli at thomas-guettler.de Wed Nov 5 02:46:47 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 05 Nov 2003 08:46:47 +0100 Subject: Pickling Objects inherited from dict (Bug?) Message-ID: Hi! After unpickling the objects are not the same any more. Is this a bug or feature? import pickle class MyDictContainer(dict): def __init__(self): dict.__init__(self) print "MyDictContainer.__init__" class MyDict(dict): def __init__(self, root, name): dict.__init__(self) self.root=root self.name=name container=MyDictContainer() for name in ["one", "two", "three"]: mydict=MyDict(container, name) container[name]=mydict print container file="data.pickle" fd=open(file, "w") pickle.dump(container, fd) fd.close() fd=open(file) unpickle=pickle.load(fd) fd.close() print unpickle Output: ===> python test-pickle.py MyDictContainer.__init__ {'three': {}, 'two': {}, 'one': {}} {'one': {}, 'three': (, , {'three': {}, 'two': (, , {'three': {}, 'two': {}, 'one': {}}), 'one': {}}), 'two': (, , {'three': {}, 'two': {}, 'one': {}})} After unpickling the object is not the same anymore. Any hints? If I inherit from UserDict instead, the is no error. thomas From Michael.Sparks at rd.bbc.co.uk Tue Nov 4 07:38:51 2003 From: Michael.Sparks at rd.bbc.co.uk (Michael Sparks) Date: Tue, 4 Nov 2003 13:38:51 +0100 Subject: Using debug print routine inside assert In-Reply-To: <8765i072jh.fsf@titan.staselog.com> References: <8765i072jh.fsf@titan.staselog.com> Message-ID: <200311041238.51131.Michael.Sparks@rd.bbc.co.uk> On Tuesday 04 Nov 2003 12:15 pm, Edvard Majakari wrote: ... > What do you think, what is the best solution for this kind of problem? I > for one wouldn't like to see myself writing assert(debug(...)) every now > and then :) I haven't got a solution to this, but I would be interested in a solution as well. I came to similar conclusions some months back and have been doing assert/debug for a while now, and the difference between -OO and debug is diverging very heavily. (couple of orders of magnitude kinds of differences) Michael. -- Michael Sparks, Senior R&D Engineer, Digital Media Group Michael.Sparks at rd.bbc.co.uk, +44 (0) 1737 839754 British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP From pinard at iro.umontreal.ca Fri Nov 28 12:24:02 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 28 Nov 2003 12:24:02 -0500 Subject: Python parser generators In-Reply-To: References: Message-ID: <20031128172402.GA4479@titan.progiciels-bpi.ca> [anton muhin] > Can someone give an overview of existing Python parser generators? > [...] I'm rather looking for convenience and expressiveness. Hello, Anton. I looked at a few, but did not look at them all, and finally settled for SPARK for production. (I do not fully understand why a few generators which were written after SPARK did not at least recycle its elegance.) SPARK is not blazing fast, but is not inordinately slow either, _given_ you write reasonable grammars. By "reasonable", I do not mean small, we indeed use some rather big ones here. But I mean grammars which are rather left-to-right-ly, and for which big inputs could be chumped into smaller syntactical units at lexical time. In that way, each of the repeated call to a SPARK parser in an application is not given the whole input -- we found out that this is worth, and usually easy to do. Our parsers are easy to maintain and very dependable. We are happy with it. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From radam2 at tampabay.rr.com Tue Nov 4 15:20:12 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Tue, 04 Nov 2003 20:20:12 GMT Subject: nearest neighbor in 2D References: Message-ID: On Tue, 04 Nov 2003 08:25:36 -0800, David Eppstein wrote: >In article , > Peter Otten <__peter__ at web.de> wrote: > >> This is of course all premature optimization as the most promising approach >> is to try hard to reduce the number of candidate points, as David Eppstein >> seems to have done. But then, he could use complex numbers, too. > >Well, yes, but then my code wouldn't work very well in dimensions higher >than two... I rearranged my first example to match the output of yours and used a random number seed to get identical results. Moving the square root to the return line of the find shortest distance function increased the speed of my routine about 20%. Then using the p*p form instead of p**2 added anouther 4%. With printing turned there is only a very small difference. Of course printing is the bottle neck. Turning off printing resulted in the following. All are best of 3 runs. 1000 points: Standard loop: 0:00:00.958192 Kdtree: 0:00:00.248096 Quite a difference. I'm not quite sure how kdtree's work. (yet) But they can be worth while when working with large data sets. The standard loop seems to be better for small lists of < 100 points. 100 points: Standard loop: 0:00:00.009966 kdtree 0:00:00.015247 But for really large lists. 10000 points: Standard loop: 0:01:39.246454 kdtree 0:00:03.424873 Hehe.... no comparison. The number of calculations the standard loop does: 100 new points, 4950 distance calculations. 1000 new points, 499500 distance calculations. 10000 new points, 49995000 distance calculations. And I don't know how to figure it for kdtree. But we can estimate it by using the ratio of the speeds. 1000 points: kdtree (3.42/99.25)*49995000 = 1722749.62 est. dist. calculations. There's probably a better way to do that. Python is fun to do this stuff with. Playing around like this with other languages is just too much trouble. _Ron From tjreedy at udel.edu Sun Nov 16 18:58:17 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 16 Nov 2003 18:58:17 -0500 Subject: Python's simplicity philosophy References: <3FAC19F0.284DCB03@alcyone.com> <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <7xoevcf1u2.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xoevcf1u2.fsf at ruckus.brouhaha.com... > "Andrew Dalke" writes: > > list.sort also became guaranteed to be stable (this include 'reverse'). > > I don't see the reason for that. It seems like a needless restriction > on implementers. Which is why Guido long resisted making such a guarantee, in spite of many requests. (The previous list.sort was not stable.) However, timsort is stable, tested for about a year, and so fast for lists both random and with various types of order, and so close to optimal in terms of number of comparisons, that Guido was willing to 'annoint' it as list.sort for the indefinite future. If there were a generally useful non-stable sort discovered proposed in the future, is could be added under a different name. Terry J. Reedy From pekka.niiranen at wlanmail.com Sun Nov 30 14:12:12 2003 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Sun, 30 Nov 2003 21:12:12 +0200 Subject: HELP: W2K Python + Cygwin shell script In-Reply-To: References: Message-ID: <3fca4139$0$1154$39db0f71@news.song.fi> Hi, Before I start the trial & error -cycle, has anybody tried to start Bash -shell script in Cygwin environment from Python running in W2K? True, Cygwin has Python package available, but I would like to use true W2K version of Python. This would be the first step of gradual conversion of all the shell scripts in Cygwin to true W2K Python scripts: I would initially have WxPython Menu in W2K from which I start Cygwin scripts. -pekka- From martin at v.loewis.de Mon Nov 24 17:38:50 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 24 Nov 2003 23:38:50 +0100 Subject: gettext crazy question References: <43e3984e.0311201935.64aac584@posting.google.com> <43e3984e.0311230527.74eed7a3@posting.google.com> Message-ID: ulysses_dm at yahoo.com.cn (ulysses) writes: > I use same statement open file. different is MO file. > when don't fill some line, gettext can open mo normally. Can you please post a bug report to SourceForge then? Please include the .mo file, and a small Python script showing the error. Regards, Martin From jdriller at orchid.org Tue Nov 18 12:48:15 2003 From: jdriller at orchid.org (Jonathan Driller) Date: 18 Nov 2003 09:48:15 -0800 Subject: loop does not count... References: Message-ID: Thanks. That worked beautifully - except that I kept getting errors if I moved the import statements out of the def... "invalid syntax" So, now it is (with the changed comments per Terry's suggestion to be added): def stats(): import sys import string #read the file of current urls that are to be checked - presumes it exists already x = open('urlList.txt') # note this reads as a file, not a list urlFile = x.read() # don't need to close but should x.close() #list what is in text file of urls print "Here is what we check now:\n", urlFile print "\n" #prompt to add additional urls - use raw so quotes not nec addItem = raw_input('Enter an additional URL in quotes:' ) # can't append() to a file, must list.append() or do this way urlList = urlFile + "\n" + addItem #write additional urls to list y = open('urlList.txt', 'w') y.write(urlList) y.close() # len(listName) gives # of list elements #turn url listings into list z = open('urlList.txt') urlList = z.readlines() #open log file log = open('sampleLog.txt') logFile = log.read() #initialize counter at 0 i = 0 # loop through to search for urls while i < len(urlList): # put element into var check = urlList[i].strip() #print out # found and what it was print check, " found" , string.count(logFile, check) ,"times \n" # increment for next item - can't do i ++ i = i + 1 z.close() From joobs at grizo.free-onlineNOJUNK.co.uk Thu Nov 13 00:17:33 2003 From: joobs at grizo.free-onlineNOJUNK.co.uk (John Burns) Date: 13 Nov 2003 06:17:33 +0100 Subject: Matrix - Metaphors, Analogies and the REAL References: Message-ID: <9447377298731260.NC-1.60.joobs@news.free-online.net> On Tue, 11 Nov 2003 12:30:47 GMT, Coyote Seven wrote: > RaYzor wrote: > > Its OK to like a movie, sure. Even being a super-fan is allright. I like > > Star Wars series a lot, I have 4 or 5 Star Wars games, I own all the movies. > > But I don't wander into AMIGA (or for that matter, ANY) newsgroups and start > > theorizing on how I can use the Dark Side of the Force ... in random, > > meaningless spurts of convulted text. This is because I know its just a > > movie. > > I find your lack of faith disturbing. > Nah, it is those with faith who are disturbing (or maybe disturbed :) ) since they are willing to forego any evidence or logic to the contrary in defence of and to keep their "faith". From tov at eecs.harvREMOVEard.edu Sat Nov 1 16:21:14 2003 From: tov at eecs.harvREMOVEard.edu (Jesse Tov) Date: 1 Nov 2003 21:21:14 GMT Subject: Explanation of macros; Haskell macros References: <87brs2tjut.fsf@memetrics.com> Message-ID: Peter Seibel : > them. Now I don't know Haskell or ML so I'm also suffering from finite > knowledge. Maybe one day I'll have time to learn one of them for > myself and see if they really do offer better solutions. The existence of Template Haskell indicates to me that there are things people want to do with macros that aren't reasonably done in Haskell. I don't even know if I've ever wanted to do these things, because people rarely miss language features that they don't know. Jesse -- "A hungry man is not a free man." --Adlai Stevenson From theller at python.net Mon Nov 3 16:36:16 2003 From: theller at python.net (Thomas Heller) Date: Mon, 03 Nov 2003 22:36:16 +0100 Subject: ANN: ActivePython 2.3.2 & ActivePython 2.2.3 In-Reply-To: <041d01c3a0db$557615b0$0500a8c0@eden> (Mark Hammond's message of "Sun, 2 Nov 2003 11:50:37 +1100") References: <041d01c3a0db$557615b0$0500a8c0@eden> Message-ID: <4qxluobz.fsf@python.net> "Mark Hammond" writes: > FYI, my short-ish term plans with win32all are to: > * Enhance Thomas's distutils build script, and make that the "official" way > to build and install sources (that holds the best hope for managing multiple > Python versions at once from one source tree) Yes, it's much easier to enter 'python setup.py build' for each Python version you need than to fire up MSDev, set the paths, build, and so on. > * Drop all registry stuff, using a few .pth files One .pth file is probably enough. > * Re-do the setup script using inno. Just curious: are you missing something in bdist_wininst (except for the ability to install system files)? Thomas From peter at engcorp.com Sun Nov 9 22:06:35 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Nov 2003 22:06:35 -0500 Subject: Rekall and associated software go 100% GPL References: Message-ID: <3FAF00BB.900AE531@engcorp.com> Tim Churches wrote: > > Peter Hansen wrote: > > > > Tim Churches wrote: > > > > > > On Mon, 2003-11-10 at 06:59, John Dean wrote: > > > > It gives me great pleasure to inform you that Rekall, the > > cross-platform > > > > alternative to MS Access, is now totally GPL. So please visit > > > > http://www.totalrekall.co.uk and download download a copy for > > yourself. > > > > > > This is most welcome news, but in the light of the recent, often > > > confusing (or confused) discussion on this list over Rekall and the > > > Kompany, could Shawn Gordon please comment on this announcement? > > > > When asking one party in a legal dispute to comment on public > > announcements made by the other party, what exactly do you really > > expect to learn? > > Merely to discover whether there is, in fact, a legal dispute over the intellectual > property associated with Rekall. I have had a private response from Shawn > Gordon indicating that there is (and have asked his permission to copy his reply > to this list). I have no interest in the details of the Rekall dispute, nor in who is right > or who is wrong, only in whether Rekall is under an ownership cloud. Ah, you probably missed the recent thread on this subject, where it was made very clear (though implicitly) by both parties that there is a dispute. The statements they made showed that each contradicted the other, and there seemed little question that this was an issue that only a court case was likely to resolve. -Peter From john at rygannon.com Mon Nov 3 14:27:39 2003 From: john at rygannon.com (John Dean) Date: Mon, 3 Nov 2003 19:27:39 GMT Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <3fa6ac07$0$12683$fa0fcedb@lovejoy.zen.co.uk> Nice sales and markets pitch but not exactly true if you compare that with this email snippet dated 18.8.03 John I told that we are flat broke 7.8.03 I meant to talk to you yesterday. There is like $50 in the account right now. last month was our worst sales month in over a year 22.8.03 I'll answer all the various emails at once. This has been a pretty terrible summer for sales thus far, June and July were some of our worst months in almost 2 years And there are lots more of the same. They make interesting reading, especially in the context of the what is said onn the TKC web site -- Best Regards John From tjreedy at udel.edu Wed Nov 12 17:49:21 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Nov 2003 17:49:21 -0500 Subject: Get more from Google (was: programming languages (etc) "web popularity" fun) References: <9Vvob.74272$e5.2721707@news1.tin.it> Message-ID: <05KdnaKtN89qJS-iRVn-jg@comcast.com> "Nick Vargish" wrote in message news:m3fzgtlj78.fsf at tanelorn.bandersnatch.org... > To drag this thread kicking and screaming back onto topic, does anyone > know what Google uses Python for, and to what extent? I *assume* that they use it for relatively quickly prototyping new/experimental features. The ability to test things quickly and keep ahead of the competition is part of their competitive advantage. Things put into production use are legitimately (in an economic sense, for quick response and CPU farm savings) rewriten in C?? and I presume they do. TJR From http Tue Nov 4 17:00:21 2003 From: http (Paul Rubin) Date: 04 Nov 2003 14:00:21 -0800 Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0310312008.ce341ea@posting.google.com> <87r80sdyb1.fsf@pobox.com> <7xn0bg6njb.fsf@ruckus.brouhaha.com> <7x7k2jpti9.fsf@ruckus.brouhaha.com> <3fa6a66a$0$12690$fa0fcedb@lovejoy.zen.co.uk> <3fa78ee1$0$12706$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <7xbrrrrdze.fsf@ruckus.brouhaha.com> "John Dean" writes: > > Are there other, licensed technologies combined with ReKall, such as > > database drivers, etc., which would cripple a GPL version of ReKall? > > I would say not. We include drivers for MySQL, PostgreSQL and xBase. We do > have drivers for DB2, Oracle, Informix, Sybase, and ODBC, but I suppose they > would have to be sold as commercial plugins, much as we don't want to I'd say screw it. Just ship with what you have and don't worry about the other stuff. It will get taken care of, like it did for the Perl DBI package. From Mike at DeleteThis.Geary.com Sat Nov 29 03:16:35 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 29 Nov 2003 00:16:35 -0800 Subject: if - else References: <871xrtr8yb.fsf@pobox.com> <5ctxb.120283$Ec1.5141313@bgtnsc05-news.ops.worldnet.att.net> <87smk9mmgj.fsf@pobox.com> <3fc7a6dd.70951673@news.blueyonder.co.uk> Message-ID: > > | if (10 == sum) {...} > > | > > | rather than > > | > > | if (sum == 10) {...} > > Yes, there's such a style, and it's considered by experienced C > > programmers to be as weird as if( (a Dunno about that, I've been using C since 1986 and every C > project I've worked on since 1991 (about half a dozen biggish > ones) has mandated the > > if (CONST == variable)... > > style of if statement check, and most of the recent books > recommend it. So an awful lot of experienced C > programmers use it day in day out - and I haven't heard > any loud complaints. > Generally anything that saves bugs in C is "A Good Thing", > its like running lint - you just build it into the make rules > so that you never forget... The problem with "if( CONST == variable )" is that it reads unnaturally, creating a mental speed bump when someone reads your code. Admittedly it's a fairly minor speed bump, and avoiding coding errors is a good thing. However, this contrivance is unnecessary with modern C compilers, which issue a warning if you code "if( variable = CONST )". With Microsoft Visual C++, I always set my project options so that warnings are errors. If I code "if( variable = CONST )", it won't compile. Thus, I'm able to use the more natural "if( variable == CONST )" notation without fear of error. It's certainly pleasant that Python sidesteps this issue completely! :-) -Mike From jsbenson at bensonsystems.com Thu Nov 20 15:29:16 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Thu, 20 Nov 2003 12:29:16 -0800 Subject: Library to generate 3D Graphs Message-ID: <01a801c3afa4$fb1b6600$a90a500a@jsbwxp3> In Doug Tidwell's XSLT book from O'Reilly, there is an eyepopping application of XML on pages 37-40 showing how VRML (Virtual Reality Modeling Language), an application of XML, can be used. It doesn't go into the viewing software needed to process the .wrl file that XSLT transforms the VRML source into, but the demonstration is quite impressive. From jjl at pobox.com Mon Nov 3 17:10:21 2003 From: jjl at pobox.com (John J. Lee) Date: 03 Nov 2003 22:10:21 +0000 Subject: Selling Python Software References: <8765i1d2jb.fsf@pobox.com> Message-ID: <87oevt9k8i.fsf@pobox.com> Alex Martelli writes: [...] > Part of the problem is, that the "warezdoodz culture" is stacked > against you. If you DO come up with a novel approach, that is a [...] Ah, stop right there (oops, too late!-). I think we're somewhat at cross-purposes. I was talking about protecting something more at the level of source code than running programs. I mostly agree with you on the issue of protecting "binaries", but: > Part of the problem is, that the "warezdoodz culture" is stacked > against you. If you DO come up with a novel approach, that is a [...] Though information is indeed always incomplete, it seems a good bet that war3zd00dz are not an issue for a consultant being hired by a company to write a 1000 line program. Do you disagree? Anyway, back to source vs. binaries. Obviously, code that's closer to the "source" end of the spectrum has additional value. I'd got the impression that something rather similar to the original source could be recovered from Python byte-code, due to its high-level nature (albeit obviously missing a lot of stuff -- including all those valuable names). Certainly that's impossible with optimising compilers (I should have stated this much more strongly in my last message, of course -- there's no "may" or "guessing" involved there, unlike the Python case, where I don't know the answer). > It's not about programming languages at all. In the end, "clever" > schemes that are presumed to let people run code on machines under > their control yet never be able to "read" the code must rely on > machinecode tricks of some sort, anyway, since obviously, from a [...] Until MS get their grubby hands on our CPUs, anyway :-( John From SEE_AT_THE_END at hotmail.com Mon Nov 10 21:57:25 2003 From: SEE_AT_THE_END at hotmail.com (Georgy Pruss) Date: Tue, 11 Nov 2003 02:57:25 GMT Subject: Am I the only one who would love these extentions? - Python 3.0 proposals (long) References: Message-ID: Thank you all for the comments. -- Georgy Pruss E^mail: 'ZDAwMTEyMHQwMzMwQGhvdG1haWwuY29t\n'.decode('base64') From and-google at doxdesk.com Wed Nov 26 19:42:35 2003 From: and-google at doxdesk.com (Andrew Clover) Date: 26 Nov 2003 16:42:35 -0800 Subject: python xml dom help please References: <2c60a528.0311240720.1db7f90d@posting.google.com> <87isl89shv.fsf@pobox.com> Message-ID: <2c60a528.0311261642.5478397d@posting.google.com> John J. Lee wrote: > Why not just for node in list(nodeList)? You're right! I never trusted list() to make a copy if it was already a native list (as it is sometimes in eg. minidom) but, bothering to check the docs, it is guaranteed to after all. Hurrah. spam.meplease at ntlworld.com (deglog) wrote: > def appendToDescendant(node): > walker.previousSibling() > while 1: > if walker.currentNode.hasChildNodes(): > next = walker.nextNode() > else: break > walker.currentNode.appendChild(node) Are you sure this is doing what you want? A TreeWalker's nextNode() method goes to an node's next matching sibling, not into its children. To go into the matching children you'd use TreeWalker.firstChild(). The function as written above appends the argument node to the first sibling to have no child nodes, starting from the TreeWalker's current node or its previous sibling if there is one. I'm not wholly sure I understand the problem you're trying to solve. If you just want to nest sibling elements as first children, you could do it without Traversal or recursion, for example: def nestChildrenIntoFirstElements(parent): elements= [c for c in parent.childNodes if c.nodeType==c.ELEMENT_NODE] if len(elements)>=2: insertionPoint= elements[0] for element in elements[1:]: insertionPoint.appendChild(element) insertionPoint= element (Untested but no reason it shouldn't work.) > Strangely, the line checking "Game" is needed, because this firstnode > is its own previous sibling - how can this be right? 4DOM is fooling you. It has inserted a declaration automatically for you. (It probably shouldn't do that.) So the previous sibling of the documentElement is the doctype; of course the doctype has the same nodeName as the documentElement, so the debugging output is misleading. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From lucat at despammed.com Sat Nov 1 16:32:08 2003 From: lucat at despammed.com (Luca T.) Date: Sat, 01 Nov 2003 22:32:08 +0100 Subject: Finding the "home" folder [Linux/Windows] Message-ID: Hello, i need a way to find the home folder of the current user no matter if i am in Linux or Windows for instance: * Linux: /home/username * Windows: C:\Documents and Settings\username [of course this might change] Is there any general way to do this? Thank you, Luca From tuanglen at hotmail.com Tue Nov 25 15:43:47 2003 From: tuanglen at hotmail.com (Tuang) Date: 25 Nov 2003 12:43:47 -0800 Subject: Parsing strings -> numbers References: Message-ID: Skip Montanaro wrote > > Be careful if you're scraping web pages which might not use the same charset > as you do. You may find something like: > > $123.456,78 > > as a quote price on a European website. I don't know how to tell what the > remote site used as its locale when formatting numeric data. Perhaps > knowing the charset of the page is sufficient to make an educated guess. Thanks, Skip. I'm not planning some sort of shady screen scraping operation or anything of that sort. This is more of a generic question about how to use Python as a convenient utility language. Sometimes I'll find a table of interesting data somewhere as I'm just surfing around the Web, and I'll want to grab the data and play with it a bit. At that scale of operation, I can just look at the page source and figure out the encoding, what the currency is, etc. I know how to turn a formatted string into a usable number in other languages that I use (though I might have to check the docs in some cases to remind myself of the details), and since the docs didn't really make it obvious what the "one clear and obvious way to do it" was in Python, I thought I'd ask. It appears as though Python doesn't (yet) have the same formal support for format parsing and internationalization that languages like C# and Java have, but that's okay for now. I just wanted to make sure I didn't start creating my own naive, homemade equivalents of functions that are already part of the standard API. From tchur at optushome.com.au Tue Nov 11 04:26:08 2003 From: tchur at optushome.com.au (Tim Churches) Date: 11 Nov 2003 20:26:08 +1100 Subject: What do you think of this Python logo? In-Reply-To: References: Message-ID: <1068542768.1421.64.camel@emilio> On Tue, 2003-11-11 at 09:16, Brandon J. Van Every wrote: > What do you think of this Python logo? > http://pythonology.org/logos > Good, bad, indifferent, love it, hate it? All attempts to link Python the language with Python the snake are ultimately ill-advised, due to the origin of the name Python - see http://www.entrenet.com/~groedmed/greekm/mythpyth.html Much better to stick to a Monty Python-inspired theme, incorporating a mascot like this http://solair.eunet.yu/~janko/birdman.gif but with the BDFL's smiling face substituted, of course. Or maybe the Python Software Foundation could ask Terry Gilliam to design a logo, pro bono. Just tell him that every Python user would then be honour-bound to see all his future films (that should increase their box-office take by at least 100%...I can't understand why Munchausen, or Brazil weren't blockbusters, and what a pity The Man Who Killed Don Quixote was stillborn - see http://www.stuff.co.nz/stuff/0,2106,2698920a1870,00.html). -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From jkrepsBEAR at FISHneb.rr.com Sat Nov 1 09:23:50 2003 From: jkrepsBEAR at FISHneb.rr.com (GrayGeek) Date: Sat, 01 Nov 2003 14:23:50 GMT Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> Message-ID: Todd Stephens wrote: > On Sat, 01 Nov 2003 05:57:46 -0500, Alex Martelli wrote: > >> I do sometimes get asked for advice about "an Access-like product that's >> cross-platform" and the like, but I couldn't in good faith suggest >> Rekall if I thought that could potentially send the purchaser into the >> midst of a legal controversy. Sigh. > > I don't see much controversy here. If the work was done for theKompany, > then it is a work made for hire, no? In that case, theKompany owns the > rights to the software. > That depends upon the contract, if any, which was signed. I ran my own consulting business for 18 years and part of my contract boiler plates handled situations about code ownership. The algorithms and knowledge I possessed before a contract were not transfered to the client. They owned the product I delivered to them, including the source, but they agreed they wouldn't use it to compete against me, as an early client tried to do. Any proprietary knowledge about their business I learned while writing their software remained theirs. Any knowledge I acquired which was independent of their area remained with me...etc.... If course, my working rules also followed the 20 IRS rules for independent contractors. If John Dean was an independent contractor, and the URL I cited in a previous posting, which is a comment by Shawn Gordon himself, seemed to imply such, ("a team of people I've never physically met." ... "to the extent you can be friends with people you've never met and have never talked to on the phone.") then I get the impression that Gordon was a marketeer, a person selling code 'on consignment' and that he had a 'friendly' relationship, not a contractual one, with several coders around the world. John Dean may have happened to be one who lives in the US. I'm sure we'll find out more as the days pass by. Probably someone will post pertinent sections of a contract, or examples of prior art, etc... Meanwhile, ReKall appears to be in some sort of limbo for those putative customers who don't want to be left stranded by legal wrangles. Gordon legal power may be effective here, but not at other locations around the globe where other contributors to theKompany code base live. ??? -- - GrayGeek From Kepes.Krisztian at peto.hu Wed Nov 26 03:12:20 2003 From: Kepes.Krisztian at peto.hu (Kepes Krisztian) Date: Wed, 26 Nov 2003 09:12:20 +0100 Subject: 4 question Message-ID: <911798856.20031126091220@peto.hu> Hi ! I want to create an web application, but I want to get information, how to create that, and what system I use... 1.) Can I create persistent db connection under ZOPE ? I don't want to drop the db connection, because the connect to InterBase is very slow... Can I do that, or I must create a my owned connection tcp server, and interface to use this thing (like php ibase_pconnect) ? 2.) Can I use non-cookie based session - just like in php (1 session/1 browser) - under Zope ? 3.) mod_python or zope ? What is goodest thing for create web applications ? 4.) Under mod_python can I use persistent db connection; and real (php liked) session ? Thanx for any answers ! KK From mis6 at pitt.edu Tue Nov 25 01:02:23 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 24 Nov 2003 22:02:23 -0800 Subject: What exactly are bound methods? References: <153fa67.0311231859.551b673@posting.google.com> Message-ID: <2259b0e2.0311242202.7686f7a5@posting.google.com> kylotan at hotmail.com (Kylotan) wrote in message news:<153fa67.0311231859.551b673 at posting.google.com>... > Although I see lots of references to them in various documentation, I > can't find a decent explanation of exactly what they are. I'm guessing > that it's a reference to a method that remembers which object it came > from, and that when it's called, it passes that object as the first > parameter (which would conventionally be 'self'). Is this correct? If you really want to learn the difference between functions, methods and bound methods, you must learn descriptors: http://users.rcn.com/python/download/Descriptor.htm Warning: the study of descriptors may cause your head to explode ... >>> def f(self): pass ... >>> class C(object): pass ... >>> c=C() >>> f.__get__(c,C) > >>> f.__get__(None,C) >>> From michele.simionato at poste.it Fri Nov 28 01:31:46 2003 From: michele.simionato at poste.it (Michele Simionato) Date: 27 Nov 2003 22:31:46 -0800 Subject: for what are for/while else clauses References: <258fd9b8.0311220938.3210484c@posting.google.com> <258fd9b8.0311271519.153f573d@posting.google.com> Message-ID: <95aa1afa.0311272231.1e4f77b7@posting.google.com> magnus at thinkware.se (Magnus Lyck?) wrote in message news:<258fd9b8.0311271519.153f573d at posting.google.com>... > First of all, I'm not sure it's a good idea to use > exceptions like a poor (rich?) man's GOTO like this. :) > > If you persist, I'm not so sure your code is clearer than: > > try: > for ORlist in includes: > try: > for filter in ORlist: > for field in curr_fields: > for item in record[field]: > if match(item, filter): > raise Found > raise NotFound > except Found: > continue > except NotFound: > continue > else: > result.append(record) > > With the else clause on the for loop, just after the if > statement, you are bound to confuse people. I would guess > that most people who casually looked at that code would > think that you had made an indentation mistake. Some would > probably "correct" it. I, for one, could get confused. BTW, I don't remember a single case in all my code where I have used so much indentation. I would write some helper function and avoid nesting as much as possible. Michelee From peter at engcorp.com Sat Nov 1 15:15:35 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 01 Nov 2003 15:15:35 -0500 Subject: Py2exe on windows References: Message-ID: <3FA41467.E1B322CB@engcorp.com> Ray wrote: > > How do you run py2exe on a windows box? Usually from the command line, something like "python setup.py py2exe" after creating an appropriate setup.py according to the instructions on the py2exe web site. > also is anybody using Boa Constructor? Yes. (Not me, however, as I do little traditional GUI work, preferring to focus my resources on web interfaces.) -Peter From theller at python.net Wed Nov 5 04:29:39 2003 From: theller at python.net (Thomas Heller) Date: Wed, 05 Nov 2003 10:29:39 +0100 Subject: class with invalid base class References: Message-ID: "Andrew Dalke" writes: > Out of curiosity, I tried passing using an invalid base > for a class. I can't explain why I got the error messages > I did. Can someone here enlighten me? > > # Here I'm just curious > >>>> def spam(a, b): > ... return a+b > ... >>>> class Spam(spam): > ... pass > ... > Traceback (most recent call last): > File "", line 1, in ? > TypeError: function() argument 1 must be code, not str >>>> > > # What's 'function'? Why is it called? It's the Don Beaudry hook ;-). If the base class has callable a __class__ attribute, this is called with three arguments: The name of the new class, a tuple of the bases, and a dictionary. Or something like this, the details may be wrong... Since now functions have a __class__ attribute, the hook is triggered by your code above: >>> def spam(a, b): ... return a + b ... >>> print spam.__class__ >>> spam.__class__("Spam", (spam,), {}) Traceback (most recent call last): File "", line 1, in ? TypeError: function() argument 1 must be code, not str >>> Thomas From dman at dman13.dyndns.org Thu Nov 6 13:44:25 2003 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Thu, 06 Nov 2003 18:44:25 GMT Subject: from python1.5.2 to pytghon2.2.2 References: <3ef16536.3234041@news.marelli.it> Message-ID: Alberto Mantovani wrote: > Hi, > I have a lot of scripts written in python1.5.2 that I have to bring in > python2.2.2 , someone could give me some informations about the sintax > differences between the two versions?. The syntax is the same, except for a new keyword (maybe two). The _semantics_ have changed somewhat and lots of new features (library stuff) is included. See AMK's "What's New" write-ups on python.org for the details. -D -- If you want to know what God thinks about money, just look at the people He gives it to. -- Old Irish Saying www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From StefanoZAP.THIS at gaburri.net Thu Nov 6 05:11:27 2003 From: StefanoZAP.THIS at gaburri.net (stefanogaburri) Date: Thu, 06 Nov 2003 11:11:27 +0100 Subject: [XPOST] [REQ] open source multimedia authoring tools? In python maybe? In-Reply-To: References: Message-ID: Miika Keskinen wrote: > First of all PyGame comes to my mind. Very right, I actually thought of pygame - not much for the GUI (it's pretty trivial anyway) but to facilitate multimedia playback via the SDL layer. I had just forgotten to mention it... thanks! ciao S From pinard at iro.umontreal.ca Mon Nov 24 22:28:37 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Mon, 24 Nov 2003 22:28:37 -0500 Subject: Adding new methods at runtime to a class In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DEEEC2C9@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DEEEC2C9@au3010avexu1.global.avaya.com> Message-ID: <20031125032837.GA19415@alcyon.progiciels-bpi.ca> [Delaney, Timothy C (Timothy)] > > From: Fernando Rodriguez > > How can I add new methods at runtime to a class? > Before we send you into what most would consider black magic in > Python, you should explain why you want to. In most cases, this is > *not* what you want to do - there are better, more elegant and much > more Pythonic ways of doing it. There is a case which happens sometimes for me, in which I find it useful assigning methods at runtime. It occurs in stateful objects, where the actions of conceptual method varies according to the state. It is clean, clear and fast to merely assign various processors to methods when the state changes, more than maintaining and testing a state variable all-around in a never changing set of methods. (What does not change is the external API.) To me at least, it does not look like black magic, I find it Pythonic enough, and even elegant, to the point I'm doing more and more. Oh, I do read your assertion about what people do "in most cases", but I'm not sure how you get such statistics. Please enlighten us! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From frr at easyjob.net Wed Nov 19 06:46:34 2003 From: frr at easyjob.net (Fernando Rodriguez) Date: Wed, 19 Nov 2003 12:46:34 +0100 Subject: good book on multithreaded programming with Python Message-ID: Hi, Any recommendation for a good book on multithreaded programming with Python? O:-) TIA From joconnor at cybermesa.com Wed Nov 26 13:11:57 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Wed, 26 Nov 2003 11:11:57 -0700 Subject: polymorphism in python In-Reply-To: References: <6bWwb.40604$Fv8.39489@twister01.bloor.is.net.cable.rogers.com> Message-ID: anton muhin wrote: > Jay O'Connor wrote: > >> martin z wrote: >> "Function overloading" is still one form of polymorphism. > > I'm not completly agree. Indeed, dispatching on arguments' types can > be regarded as polymorphism. However, OP needed to dispatch on > *number* of parameters that seems like classic overloading IMHO I didn't really address the OP phrasing because I'm not really convinced that overloading on numbers of parameters is really polymophism either, I was mostly just addressing the follow up; just pointing out that function overloading, in general, is one way of implementing polymorphism. From peter at engcorp.com Tue Nov 18 17:28:45 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Nov 2003 17:28:45 -0500 Subject: Looking for code References: Message-ID: <3FBA9D1D.933605EA@engcorp.com> Andy Koch wrote: > > Hello. I am new to Python and for the most part new to programming. The > best way to learn to write is to read, so I have been looking for a > website that has the code of programs written in Python. If anyone knows > of a good place to find something like this, I would be very grateful if > you could respond. Almost all Python code is distributed as .py files, which is the actual source, so you shouldn't have to look far to find it. Start with the standard distribution: look under your /python/lib folder (adjust path to your own situation) and check it out: more code than you're likely to want to read right now. :-) Also download just about *any* Python program, starting from links on www.python.org, or searching at SourceForge.net, and you'll find lots of source to peruse. Also make sure you've followed through the tutorial and other beginner materials, again linked from www.python.org. -Peter From frr at easyjob.net Fri Nov 21 09:16:36 2003 From: frr at easyjob.net (Fernando Rodriguez) Date: Fri, 21 Nov 2003 15:16:36 +0100 Subject: Trouble with nested scopes when trying to rebind a variable Message-ID: <187srv08b4hbsckjje6s79dmipug8lcqlh@4ax.com> Hi, I have a parameter defined in a module, called PREVIEW. Many functions use it's value to modify their behavior. A function called dispatch checks the user arguments in sys.argv and calls the appropriate function. It should also modify the value of PREVIEW depending on the user input. And here's where I get into trouble: if I write something like PREVIEW = None inside the body of a function, it doesn't modify the value of the existing PREVIEW variable, it creates a new variable in the function scope. How can I modify the external PREVIEW variable? In Lisp there are different operators to rebind an existing variable and to create a new variable. How do you do this in python? From radam2 at tampabay.rr.com Wed Nov 12 18:18:24 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Wed, 12 Nov 2003 23:18:24 GMT Subject: case-sensitivity References: <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FB2738E.2B8C13FE@engcorp.com> <3fb275b2.55356282@news.cybermesa.com> <7075rv0d1thucjc617gibn4te7uoumh71c@4ax.com> <3fb2a0ee.66426159@news.cybermesa.com> Message-ID: On Wed, 12 Nov 2003 21:08:11 GMT, joconnor at cybermesa.com (Jay O'Connor) wrote: > >>I hope nobody is thinking of that approach seriously. It may work >>well in places where the use is naturally limited in both scope and >>degree, but it becomes unmanageable when the size and content are >>allowed to grow with no limits on them. > > >If you mean color-coded code with meaning, I don't know. > >but if you mean using databases for source-code management, it works >very well and I much prefer it to text file based approaches. Both. But as for using databases for source-code management, I don't think it should be necessary. The source code itself should contain all the information required to construct an application. Thus, makefiles and/or database oriented sorce-code management tools shouldn't be needed. My reference to the windows registry was an example of how a seemingly good idea can become a problem. The registry contains so much information now it's difficult to manage and is a security risk. The reference earlier to using a database for keeping all sorts of meta information is a very similar situation in my opinion. I'm definitely not against using databases. It's the separation of related content in such a way that the source code is incomplete without the other, that I don't like. _Ron Adam From SEE_AT_THE_END at hotmail.com Sun Nov 9 22:01:12 2003 From: SEE_AT_THE_END at hotmail.com (Georgy Pruss) Date: Mon, 10 Nov 2003 03:01:12 GMT Subject: Bad docs for os.path.isabs() References: Message-ID: "Bengt Richter" wrote in message news:bom7ii$8n4$0 at 216.39.172.122... > On Sun, 9 Nov 2003 11:32:46 -0800, "Ben Allfree" wrote: > > >The docs for os.path.isabs() state: > > > > isabs( path) > > > >Return True if path is an absolute pathname (begins with a slash). > > > >This is false becase os.path.isabs("C:\\foo") == True > > > >It should read: > > > > isabs( path) > > > >Return True if path is an absolute pathname (begins with a slash or drive > >letter). Return True if path is an absolute pathname i.e. it begins with a slash or backslash, possibly prepended by a drive letter and a colon. ... or something like that. Sorry for my bad English. G-: -- Georgy Pruss E^mail: 'ZDAwMTEyMHQwMzMwQGhvdG1haWwuY29t\n'.decode('base64') > > While you're at it, better take this into account also ;-) > > >>> import os > >>> os.path.isabs("C:\\foo") > True > >>> os.path.isabs("C:foo") > False > >>> os.path.isabs("\\foo") > True > > For that last one, I think you could argue that it's false, since it does not > absolutely specify what the meaning is in a multi-drive system. > > The whole drive letter file path thing is soo lame it makes me incoherent ;-/ > > Regards, > Bengt Richter From curty at freeze.invalid Sun Nov 23 06:39:10 2003 From: curty at freeze.invalid (Curt) Date: 23 Nov 2003 12:39:10 +0100 Subject: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com> <3FBC2025.B2A33B6F@alcyone.com> <87d6bncbaj.fsf@einstein.electron.net> <3FBD3D6F.E4068821@alcyone.com> <878ymad3ga.fsf@einstein.electron.net> <3FBD6419.A5A863C8@alcyone.com> <874qwyaqqj.fsf@einstein.electron.net> <3FBE892D.22B4A544@alcyone.com> Message-ID: <87k75rs49t.fsf@einstein.electron.net> "Michael Geary" writes: > Curt... > It is unfortunate that both the program name and the one-line description of > uniq are misleading: > uniq - remove duplicate lines from a sorted file The Gnu/Linux man page is not the only document in the world that's misleading about "uniq". http://www.gnu.org/manual/textutils-2.0/html_chapter/textutils_7.html 7.2 uniq: Uniquify files uniq writes the unique lines in the given `input', or standard input if nothing is given or for an input name of `-'. Synopsis: uniq [option]... [input [output]] By default, uniq prints the unique lines in a sorted file, i.e., ****** discards all but one of identical successive lines. Optionally, it can instead show only lines that appear exactly once, or lines that appear more than once. The input must be sorted. If your input is not sorted, perhaps you ****** want to use sort -u. http://publib16.boulder.ibm.com/pseries/en_US/cmds/aixcmds5/uniq.htm Description The uniq command deletes repeated lines in a file. The uniq command reads either standard input or a file specified by the InFile parameter. The command first compares adjacent lines and then removes the second and succeeding duplications of a line. Duplicated lines must be adjacent. (Before issuing the uniq command, use the sort **** command to make all duplicate lines adjacent.) http://www.tldp.org/LDP/abs/html/textproc.html uniq This filter removes duplicate lines from a sorted file. It is often ****** seen in a pipe coupled with sort. **** cat list-1 list-2 list-3 | sort | uniq > final.list # Concatenates the list files, # sorts them, # removes duplicate lines, # and finally writes the result to an output file. ======================================================================= It seems to me that this utility was developed to "uniquify" files; that is, remove every and all duplicate lines in order that every line be "unique". I can only assume that this was the primary, fundamental use case in the mind of the author when he developed the program, and that's why he called it "uniq". If you find this misleading, maybe you should file a bug report. ;-) Anyway, I'm having lunch with him next Friday so I'll ask him what he had in mind and let you know if he remembers just exactly what that was. From aleax at aleax.it Thu Nov 13 11:50:00 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Nov 2003 16:50:00 GMT Subject: trouble understanding None References: Message-ID: Peter Otten wrote: ... > I mixed normal and raw strings because I recalled a problem with > backslashes at the end of a raw string. I've since found out that this > applies only to a single last backslash at the end of the string: Nope, any ODD number of backslashes at the end (1, 3, 5, 7, ...). Alex From Google_Post at slink-software.com Tue Nov 11 03:25:58 2003 From: Google_Post at slink-software.com (K_Lee) Date: 11 Nov 2003 00:25:58 -0800 Subject: Roadmap to python internal source code's Network socket interface. Message-ID: <394af34.0311110025.1ebbba4b@posting.google.com> While trying to understand some issues to python's implementation of Socket, I recorded an outline to Python's socket object interface to the native implementation in a webblog type documents in our website. Just like to share it with others in case you find it useful. Each of the following lines are links to source code where the functions, macros, variables and comments are hyperlinks to each others in other source files make browse, understand and document the source code easier. http://www.slink-software.com/W/SrcDoc_Top/Python-2.3/Python-2.3.sdoc/N_76 Python-2.3.sdoc Source Map URL Links Memory Interface. PyObject_Malloc - obmalloc.c:556 PyObject_Free - obmalloc.c:700 Network Interface init_socket - socketmodule.c:3461 Py_InitModule3 - socketmodule.c:3469 PySocket_MODULE_NAME - socketmodule.h:48 PyModule_AddObject - socketmodule.c:3497 sock_type - socketmodule.c:3496 sock_type - socketmodule.c:2258 sock_doc - socketmodule.c:70 sock_methods - socketmodule.c:2102 sock_connect - socketmodule.c:1492 internal_connect - socketmodule.c:1437 PySocketSockObject - socketmodule.h:92 internal_select - socketmodule.c:592 internal_setblocking - socketmodule.c:541 sock_close - socketmodule.c:1417 PySSLMethods - _ssl.c:473 PySSL_server - _ssl.c:478 PySSL_SSLwrite - _ssl.c:372 issuer - _ssl.c:479 PySSLObject - _ssl.c:62 From usenet_spam at janc.invalid Mon Nov 3 00:41:21 2003 From: usenet_spam at janc.invalid (JanC) Date: Mon, 03 Nov 2003 05:41:21 GMT Subject: ANN: pyfromc - Python from C++ and vice versa References: <3fa3488c.12101640@news.t-online.de> <3FA3B325.1491D228@engcorp.com> <3fa3c4e1.43930000@news.t-online.de> <2dGdncyBTpWEkDmiRVn-ig@comcast.com> <5Clpb.4352$qh2.1758@newsread4.news.pas.earthlink.net> Message-ID: "Andrew Dalke" schreef: > JanC: >> AFAIK in Belgium (and several other European countries) you can't >> legally put your own work in the public domain; an author always >> keeps his or her "author rights" (which includes copyright). > > Is there work for hire, so that the copyright goes to the employer? > Can the employer sell that copyright to someone else? Yes, in case of work-for-hire, the copyright is with the employer, and they can sell it (they aren't authors). And authors can always license the right to make copies to someone else, they just can't give away the ultimate right to do that. :-) > Are government works covered under copyright? In the US, they > are not, and are always in the public domain. I'm not sure about that. Public domain would that mean you can legally make copies of driver licenses? Don't think that's allowed... :-p > Can works enter the public domain after a period of time? Yes, but that's way too long for a computer program to be useful... (Something like 70 years I guess.) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From costanza at web.de Tue Nov 11 08:32:20 2003 From: costanza at web.de (Pascal Costanza) Date: Tue, 11 Nov 2003 14:32:20 +0100 Subject: Python from Wise Guy's Viewpoint In-Reply-To: <3fb0c2cd$1@news.unimelb.edu.au> References: <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <3F9D5D21.2060408@ps.uni-sb.de> <3fb097fe$1@news.unimelb.edu.au> <3fb0c2cd$1@news.unimelb.edu.au> Message-ID: Fergus Henderson wrote: > Pascal Costanza writes: >>DEFUN is just one example. What about DEFTYPE, DEFCLASS, DEFPACKAGE, and >>so forth... > > Well, DEFTYPE in lisp really just defines a function, doesn't it? > So that's not much different than DEFUN. Likewise, DEFCLASS just > defines a collection of functions, doesn't it? OK, maybe these > also record some extra information in some global symbol tables. > That is easily emulated if you really want. > > I don't know exactly what DEFPACKAGE does, but if the others are any > guide, it's probably not too hard either. I am not sure if I understand you correctly, but are you actually suggesting that it is better to reimplement Common Lisp on your own than to just use one of the various Common Lisp implementations? All I am trying to get across is that, in case you need the flexibility a dynamic language provides by default, and only occasionally need to restrict that flexibility, it's better to use a dynamic language from the outset. The price to pay is that you cannot make use of a 100% strict static type system anymore, but on the other hand you can pick one of the stable Common Lisp implementations with language features that have proven to work well during the past few decades. Sure, if you don't need the flexibility of a dynamic language then you can think about using a static language that might buy you some advantages wrt to static checkability. But I highly doubt that this is a rational choice because I don't know any empirical studies that show that the problems that static languages intend to solve are in fact problems that occur in practice. Let's inspect the list of those problems again: a) performance Good Lisp/Scheme implementations don't have problems in this regard. b) documentation Documentation can be handled well with comments and well-chosen names. c) absence of a certain class of bugs It's not clear whether this class of bugs really occurs in practice. There are also indications that these relatively trivial bugs are also covered by test suites as soon as they consist of a reasonable number of test cases. d) unbreakable abstraction boundaries Such boundaries seem to be as tedious to implement in dynamic languages, as is the case for dynamic features in static languages. My conclusions would be as follows: a) and b) are relatively uninteresting. c) needs convincing studies from the proponents of static type systems. As long as they don't provide them, it's just guesswork that these bugs are really important. d) is the hard part. Proponents of static languages say that it's important to be able to express such boundaries because it increases their expressive power. (That's one thing I have learned from this discussion: It is arguable that this can also be an important kind of expressive power.) Proponents of dynamic languages say that it's more important to be able to work around restrictions, no matter whether they are intentional or not; it's better not to be able to paint yourself into a corner. With regard to d, both "groups" don't have enough objective empirical evidence beyond their own subjective experiences. Static programmers don't have enough objective empirical evidence that their languages objectively increase the quality of their software, and dynamic programmers don't have enough objective empirical evidence that painting oneself into corners is a problem that occurs regularly. So both views essentially boil down to be no more than subjective belief systems. And IMHO that's not so far from the "truth": I am convinced that these issues depend mostly on personal programming style and preferences and not so much on technological issues. Software quality is a social construct, and social problems can hardly be solved with technical means. If you have a bunch of good programmers and let them choose their preferred tools, it's more likely that they produce good software than when you have a bunch of average programmers and tell them what tools they must use. (It's very important in this regard that we are not talking about braindead languages. There are both extremely stupid as well as excellent exemplars of static and dynamic languages.) Pascal -- Pascal Costanza University of Bonn mailto:costanza at web.de Institute of Computer Science III http://www.pascalcostanza.de R?merstr. 164, D-53117 Bonn (Germany) From mis6 at pitt.edu Thu Nov 13 23:53:39 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 13 Nov 2003 20:53:39 -0800 Subject: True inconsistency in Python References: <3FB364A3.1060701@users.ch> Message-ID: <2259b0e2.0311132053.4ef8b4aa@posting.google.com> Gerrit Holl wrote in message news:... > > (btw, I _do_ use bool ocasionally: I implemented an anytrue() function > using sum([bool(i) for i in L]), is this wrong?) > > Gerrit. > > -- > 128. If a man take a woman to wife, but have no intercourse with her, > this woman is no wife to him. > -- 1780 BC, Hammurabi, Code of Law It does not shortcut, i.e. it creates the full list. For the rest, it is a matter of personal opinion if this idea is considered cool or an abuse of sum. I personally, will propend for the latter, but since we don't have yet an anytrue function in the library, for the moment it can be tolered). Just my 0.02 E. Michele From radam2 at tampabay.rr.com Wed Nov 12 20:32:51 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Thu, 13 Nov 2003 01:32:51 GMT Subject: case-sensitivity References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> Message-ID: On Wed, 12 Nov 2003 23:49:57 GMT, "Rainer Deyke" wrote: >Ron Adam wrote: >> The only reason to use case >> sensitivity is as a way to differentiate names. > >No. The only reason to use case sensitivity is to let the programmer >recognize names immediately without mentally translating them into a common >case. A language which allows 'sWord' as an alias for 'Sword' is >unnecessarily difficult to read. > >Differentiating names is an undesired side effect of case sensitivity. > > >-- >Rainer Deyke - rainerd at eldwood.com - http://eldwood.com > Once side of this is from the programmers point of view and the other is from the machine interpreter point of view. >From the interpreters view, case sensitivity is used to differentiate names in name space. From the programmers view, it helps us to recognize names. I don't believe they are mutually exclusive. You can still have caps and identifiable variables without requiring case sensitivity. A smart editor can implement case insensitivity without changing Python. This isn't true case insensitive but it has the same effect from a programmers point of view. It would need to correct case at some point to do it. So call it case correcting instead of case insensitive. Which would you choose from the following? As I type in a program: 1: I get an error for using the wrong case at compile time. Then have to find the problem and correct it. Then try to recompile. 2: I'm very careful to make sure and look up all the proper names which takes quite a bit of additional time. The program compiles and runs normally if I didn't have any typos. If I did, then the result is the same as #1. 3. The editor doesn't do anything special and the compiler ignores case differences and it compiles and runs normally. I only have to remember the correct spellings. I can use any editor I choose or have available with the same result. 4: The editor or IDE matches what I enter to the names and then substitutes the proper case of the name at some definitive point. This ensures that the case is correct and the program compiles and runs normally. If I choose a different editor then see #1 or #2. 5. The editor or IDE matches corrects the case as in #4, and the compiler which is case insensitive compiles and runs normally. I can choose any editor. If it doesn't support case correcting then see #3. My preferences would be in order: #5, #3, #4, #1, #2 Numbers 1 and 2 are really the same, but #1 is what I'm most likely to do. Numbers 5 and 3 are basically the same, but #5 uses case correcting while editing. Number 4 is possible to do now, but I don't know of any editors that currently do it. It would be a nice option to include in one I think. _Ron Adam From bokr at oz.net Thu Nov 20 13:25:29 2003 From: bokr at oz.net (Bengt Richter) Date: 20 Nov 2003 18:25:29 GMT Subject: rotor alternative? References: <7x8ymd4hwf.fsf@ruckus.brouhaha.com> Message-ID: On 18 Nov 2003 11:05:04 -0800, Paul Rubin wrote: >Robin Becker writes: >> It seems that the rotor module is being deprecated in 2.3, but there >> doesn't seem to be an obvious alternative. I'm using it just for >> obfuscation. It seems we have ssl available in 2.3 for sockets, but >> there seems no obvious way to use that from python code. >> >> Is an alternative to rotor planned? > >Yes, Python should get some real encryption functions sooner or later. >Meanwhile here's something you can use: > > http://www.nightsong.com/phr/crypto/p3.py Just noticed your using time.time. I believe clock has more bits than time, at least on windows: >>> from time import time,clock >>> min([abs(time()-time()) for i in xrange(1000)]) 0.0 >>> min([abs(time()-time()) for i in xrange(1000)]) 0.0 >>> min([abs(clock()-clock()) for i in xrange(1000)]) 5.8666657726975935e-006 >>> min([abs(clock()-clock()) for i in xrange(1000)]) 5.866665771847579e-006 >>> min([abs(clock()-clock()) for i in xrange(1000)]) 5.866665771847579e-006 I don't know if it's worth anything, but the change would be easy ;-) Regards, Bengt Richter From hungjunglu at yahoo.com Fri Nov 14 15:38:02 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 14 Nov 2003 12:38:02 -0800 Subject: conceiling function calls.. References: Message-ID: <8ef9bea6.0311141238.7b91cf34@posting.google.com> Alex Martelli wrote in message news:... > > You want to HIDE (shudder) the fact that a function is being called, > ensuring, instead, that just coding: > print f.someattr > will call f secretly, behind the scenes. > > If one was truly intent on perpetrating this horror, then: > > class DontLetKidsSeeThisPlease(object): > def __init__(self, f): self.__f = f > def __getattr__(self, name): return getattr(self.__f(), name) > f = DontLetKidsSeeThisPlease(f) I think the original poster was not very clear in his writing. But he did give an analogy. Let me try to guess what he wants. For a property implemented with getter and setter accessor methods, you can do a lot of things when the user accesses the property. A few examples are: (a) dynamically retrieve/store the value from/to a database, (b) do some logging or access security control, (c) return different values depending on environmental circumstances, etc. The original poster seems to want the same level of control for access to a global object inside a module. That's all. That is, he probably would like to: (a) dynamically assemble the object on the flight, perhaps from a database, perhaps some meta-programming, notice that a simple Python namespace entry CANNOT do this trick, because it always points to the same object. Sure, one way out in Python is to make a wrapper, but that's exactly what the original poster's "f" is about, (b) do some logging or security control everytime the object is accessed, (c) return different objects depending on environmental circumstances, etc. regards, Hung Jung From mhammond at skippinet.com.au Sat Nov 15 21:12:34 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 16 Nov 2003 13:12:34 +1100 Subject: Strange Python COM behaviour In-Reply-To: References: Message-ID: a_bogdan_marinescu wrote: > Hello all, > > I'm trying to do some COM automation from Python (using Mark > Hammond's Win32 extensions, of course) and I'm getting some very > strange errors. Specifically, I try to use a COM object that supports > events, and I'm instantiating it like this: > > eventobj = win32com.client.DispatchWithEvents( crtthread, > DebuggerThreadEvents ) > > When I try to do this, I get the following error: > > ... > File "d:\work\scripts\automation\autobuild.py", line 106, in > execute_one_file > eventobj = win32com.client.DispatchWithEvents( crtthread, > DebuggerThreadEvents ) > File "C:\Python23\lib\site-packages\win32com\client\__init__.py", > line 264, in DispatchWithEvents > result_class = new.classobj("COMEventClass", (disp_class, > events_class, user_event_class), {"__setattr__" : _event_setattr_}) > TypeError: str() takes at most 1 argument (3 given) > > It seems that events_class's type is str ( as returned by > getevents() function in __init__.py file from win32com/Client > directory) instead of 'classobj' as it is supposed to be. event_class > is actually a simple string showing a CLSID. I'm new to COM and I > can't understand why this is happening. Please help me if you can. > Regards, It looks to me as if this error could occur if the event interface you are trying to implement is not based on IDispatch. It looks like a bug in win32com - what is the object you are trying to use? Mark. From radam2 at tampabay.rr.com Tue Nov 18 02:15:01 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Tue, 18 Nov 2003 07:15:01 GMT Subject: True inconsistency in Python References: <3FB8847F.6CB1BECA@alcyone.com> Message-ID: <83bjrvcm92o6l2gte1nbehrpvofm0r5i88@4ax.com> On Mon, 17 Nov 2003 23:13:24 -0500, "Terry Reedy" wrote: > >"Ron Adam" wrote in message >news:ivqhrv403or6mm68arqg5793gnaaehjq8e at 4ax.com... >> x = True >> if x: >> .... > >since the above snippert is equivalent to > >if True: >... > >which is equivalent to > >... > >you must have meant something more imvolved. But I am having trouble >filling in the missing pieces. > Yes, the paragraph (that you snipped) above this code snippit, explained that you need to be able to depend on 'True' being consistent with how the underlying operating system evaluates boolean expressions. If that trust is broken, then comparisons using True may not work. Including "if True:". This is so basic and simple, that you take it for granted. And so do many others. I believe the words 'True' and 'False' need to be treated the same as the digits 1, 2, 3, ... The values of the digits do not change. We depend on them not changing. True should always evaluate to True also. So we can depend on it as well. This is my opinion, you don't have to agree with it. >> So I get consistent results for the language and platform I'm using >> now and in the future. If down the road someone decided to make >True >> = 3, and False = -5, and they change the language so that any >boolean >> comparisons return 3 and -5 respectively, my use of True and False >> will still work. > >This strikes me as comparable to worrying about being killed by an >asteroid. Is there some actual historical event that makes it more >plausible to you? Again, it was an example of a concept. I was trying to point out even if the underlying values that the operating system uses to represent true and false are changed, having True as a constant equal to a boolean true evaluation, will still work. I chose numbers that are very unlikely to try demonstrate in an obvious way that the concept is valid. Sorry, if I lost you. Does making 'True' and 'False' constants and/or literals have any draw backs for you? I can only think of benefits and don't see any reason for not doing it in this particular case. While I admit that any knowledgable programmer can write good programs without these being constants or literals, I also realize that python is becoming popular as a teaching tool for entry level programming. So yes, I believe errors using and miss using True and False will happen. > >... >> It looks to me that 'True' in python is a combination of the boolean >> binary logic of 1 or 0, and as an "exists" test of 0 or not 0. > >I do not understand this. If you have a reference to 0, then 0 >exists. If you do not, then the 'existence' or not of an int with >value 0 is irrelevant. > if x: is a test to see if the value 0 does not exist in x. Or as someone has stated to me earlier... it is a test that something does exist. That something being whatever the value x represents. x is the number of coins I have. ' if x:' is a true statement if I have some coins. We are testing for the existence of my coins. >> If python had an exists operator, you could do. > >I think you are confusing names and objects. You can only apply an >operator to objects and only to objects that exist. > No, I'm not confused, and yes I am diverging here. >> if x exists: >> 'do something' > >Do you mean >if bound_to_something('x'): >? > Yes, you understand. >Normally, in the absence of error, one only uses names that one has >defined (bound to somethingj). So you must be worried about the >following scenario: > >if a: x=1 > >if exists(x): > >In non-module script only: >import __main__ as mm >x = 1 >hasattr(mm, 'x') # True >hasattr(mm, 'y') # False > >Anywhere: use try ... except NameError > >Or, don't do that (have conditionally defined name). Instead, > >x=None >if a: x = something_not_None() > >if x != None: > >In other words, name != None is often idiom for exists('name')! > >> This could serve two options also... does the object exist? > >Again, Python only operates on objects that do exist. > Yes, I noticed. The reason I bring this up is in situations where you want to initialize a variable if it has not been defined yet, but do not want to re initialize it if it's already been defined. Being able to check if an object already exists could be useful. I'll look into the hasattr() function more, thanks for pointing it out. I did stray a bit on this and I admitted so in my post. _Ronald Adam From adalke at mindspring.com Mon Nov 24 22:12:35 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 25 Nov 2003 03:12:35 GMT Subject: Making a maze.... References: <1PSsb.44675$jy.34613@clgrps13> <3fc266e7$0$1505$e4fe514c@news.xs4all.nl> <6Utwb.29786$I53.1016789@twister.southeast.rr.com> <87zneluu4e.fsf@pobox.com> Message-ID: John J. Lee: > One algorithm that's not so easy to implement in Python: > > http://www.abc.net.au/science/news/stories/s189608.htm It's a rather uninformative article. It says that a slime mold found the optimal path to a food source, and claimed that that's a form of intellegence. It doesn't mention precautions made to ensure that the action isn't a simple tropic response to go towards where more receptors on the slime mold surface say "here there be food!". In other words, by the definition used in the article, a plant is intellegent because it finds the direct path to light and water is intelligent because it finds the most direct route downhill. And all those could be done in Python -- it's the reverse of the breadth-first search. The food source emits tiny particles which diffuse outwards. An exponential function describes the density of particles, although constrained by the walls. In general, the higher the density the closer the food source, so if there's a decision point, go the route with the higher signal. Andrew dalke at dalkescientific.com From joconnor at cybermesa.com Sat Nov 29 18:20:00 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Sat, 29 Nov 2003 16:20:00 -0700 Subject: The namespace for builtin functions? In-Reply-To: <3FC926ED.7070906@irl.cri.nz> References: <3FC926ED.7070906@irl.cri.nz> Message-ID: Blair Hall wrote: > Can anyone please tell me how to correctly use a built in function > when there is a function of the same name in local scope? Save yourself a lot of trouble, just give it a different name. From peter at engcorp.com Mon Nov 3 12:24:17 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Nov 2003 12:24:17 -0500 Subject: programming languages (etc) "web popularity" fun References: <3d06fae9.0310310915.4447d4ca@posting.google.com> <9Zzob.75517$e5.2773519@news1.tin.it> <2531b4fb3a153253e29f8a74f733aef1@news.teranews.com> <3FA68205.636ED781@engcorp.com> Message-ID: <3FA68F41.A4E1D799@engcorp.com> Peter Otten wrote: > > Peter Hansen wrote: > > > Dang Griffith wrote: > >> > >> On Sat, 01 Nov 2003 00:53:17 -0000, claird at lairds.com (Cameron Laird) > >> wrote: > >> > >> >Note, too, that the Python one hasn't been on the street > >> >as long as some of the others. It's reasonable to specu- > >> >late that the ratios haven't equilibrated yet. > >> > >> Not sure I understand your comment. > >> Python predates Java. > >> --dang > > > > I'm sure Cameron is quite aware of that, and yet your comment > > does nothing to invalidate his statement. Surely you can accept > > that "Python hasn't been on the street as long as *some* of > > the others" (emphasis added), can't you? > > > > -Peter > > The point is, "the Python one" does refer to "Python in a Nutshell". > Are there any Nutshell books that came out after March 2003? But while Python predates Java, the Nutshell book for it is extremely recent, while the Java one is very old. I'm confused now, and I don't know which of us is arguing in favor of which position... . Too little sleep I think. :-( -Peter From try_vanevery_at_mycompanyname at yahoo.com Fri Nov 14 21:18:04 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Fri, 14 Nov 2003 18:18:04 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <2259b0e2.0311140033.4e3ca8ea@posting.google.com> <2259b0e2.0311140906.87b7839@posting.google.com> Message-ID: Michele Simionato wrote: > "Brandon J. Van Every" > wrote in message > news:... >> >> True... but in most cases we're making an Existential choice about >> our >> willingness to control. We are not in fact helpless. Such is the >> case with Python. >> >> If you want to actually do something about marketing Python "like >> the big boys do," I encourage you to join the marketing-python forum. >> http://pythonology.org/mailman/listinfo/marketing-python > > Unfortunately, I am not a kinda of marketing person ... Well, this is less a matter of having some official qualification (I certainly don't) than having a head for it, and for getting things done. I think in my case, the pressure of running my own business and being responsible for all of my own missteps has made me better able to see when some avenues of discussion are a complete waste of time. > Anyway, I must congratulate you for the Python logo: I'll take that as collective congratulation for the py-design-forum, and a specific accolade for Tim Parkin, the designer. I could not possibly take the congratulation specifically! My main role has been to light a match under other people's toes and force people to make decisions instead of hemming and hawing endlessly. I tried my hand at "graphic designer wannabe" and offered a couple of shaky concepts of my own. By doing so, I forced others with more skill to put up or shut up. Once real graphic designers started putting up, we got some results. Now, if only we can get PSF to see the wisdom of progress... we haven't secured their buy-in for this logo yet. > it is ways better > than any other Python logo I have seen (so far) and it looks really > professional. The font is so and so, but the stylized snake is > perfect, and very original. I think we have consensus that the font needs improvement, even from the designer. He didn't want to spend lotsa time angsting about the font if we didn't even have PSF's buy-in about the logo itself yet. A wise move on his part: PSF has a lot of trouble cutting the chase and shipping things in the art dept. The web redesign process, for instance, has been interminable. >>> We can only wait and see (as in that old chinese said ...) >> >> Chinese philosophies, at least as received by Westerners looking for >> alternatives to their high stress culture, often have the flaw of >> being too Yin. The Tao is balance, not passivity. > > Yes, but the idea I had in mind was something like "relax, we are not > in war against Java or C# or anything else, let us wait for a bit > before complaining about Python dead". I have seen the DEC Alpha CPU torn out from under me. As far as I'm concerned, any hardware / language / API / OS has enemies, and those that do not market themselves properly are endangered. Considering that Python was available before Java, it is not the success story that it could or should be. The ugly truth of high is it's 1/3 technology and 2/3 marketing. If you believe otherwise, then you haven't had Intel or Microsoft hand you your ass yet. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA Brandon's Law (after Godwin's Law): "As a Usenet discussion grows longer, the probability of a person being called a troll approaches one RAPIDLY." From unread_spamaddddress at spam0339.trash.pinguin.uni.cc Sat Nov 15 09:50:21 2003 From: unread_spamaddddress at spam0339.trash.pinguin.uni.cc (Al Bogner) Date: Sat, 15 Nov 2003 15:50:21 +0100 Subject: Tutorial for DB-Frontend with GUI References: <2560581.qn5EVrxEmu@usenet.pinguin.uni.cc> Message-ID: <2220860.bMRq6yj4MN@usenet.pinguin.uni.cc> email9898989 at yahoo.com wrote: >> So, does anyone know a tutorial/howto/link or whatever how to >> build a database client with a GUI? Is there a sample >> database-fronted built with python in the web, where one can see >> what is possible? > > Pythoncard includes a dbBrowser sample. But really you can use > any GUI toolkit with the mysql python module: > http://sourceforge.net/projects/mysql-python > http://www.devshed.com/Server_Side/Python/PythonMySQL/print_html > http://www.codespark.net/v2/articles.asp?CategoryID=45 > > See also SQLObject which might be a nicer way to do the MySQL > coding: http://sqlobject.org/ Thank you for your valuable links! What are the cons of Spectix? Specitx was the only tookit, which worked immediately with SuSE 8.2. The installation of boa-constructor-0.2.3 didn't work, also there were problems with the installation of eric 3.2. Al From fjh at cs.mu.oz.au Tue Nov 11 03:04:20 2003 From: fjh at cs.mu.oz.au (Fergus Henderson) Date: Tue, 11 Nov 2003 08:04:20 GMT Subject: Python from Wise Guy's Viewpoint References: <3F994597.7090807@ps.uni-sb.de> <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <3F9D5D21.2060408@ps.uni-sb.de> Message-ID: <3fb097fe$1@news.unimelb.edu.au> Pascal Costanza writes: >OK, let's try to distill this to some simple questions. > >Assume you have a compiler ML->CL that translates an arbitrary ML >program with a main function into Common Lisp. The main function is a >distinguished function that starts the program (similar to main in C). >The result is a Common Lisp program that behaves exactly like its ML >counterpart, including the fact that it doesn't throw any type errors at >runtime. > >Assume furthermore that ML->CL retains the explicit type annotations in >the result of the translation in the form of comments, so that another >compiler CL->ML can fully reconstruct the original ML program without >manual help. > >Now we can modify the result of ML->CL for any ML program as follows. We >add a new function that is defined as follows: > >(defun new-main () > (loop (print (eval (read))))) > >(We assume that NEW-MAIN is a name that isn't defined in the rest of the >original program. Otherwise, it's easy to automatically generate a >different unique name.) > >Note that we haven't written an interpreter/compiler by ourselves here, >we just use what the language offers by default. > >Furthermore, we add the following to the program: We write a function >RUN (again a unique name) that spawns two threads. The first thread >starts the original main function, the second thread opens a console >window and starts NEW-MAIN. > >Now, RUN is a function that executes the original ML program (as >translated by ML->CL, with the same semantics, including the fact that >it doesn't throw any runtime type errors in its form as generated by >ML->CL), but furthermore executes a read-eval-print-loop that allows >modification of the internals of that original program in arbitrary >ways. For example, the console allows you to use DEFUN to redefine an >arbitrary function of the original program that runs in the first >thread, so that the original definition is not visible anymore and all >calls to the original definiton within the first thread use the new >definition after the redefinition is completed. [1] > >Now here come the questions. > >Is it possible to modify CL->ML in a way that any program originally >written in ML, translated with ML->CL, and then modified as sketched >above (including NEW-MAIN and RUN) can be translated back to ML? Yes, it is possible. For example, have CL->ML ignore the type annotation comments, and translate CL values into a single ML discriminated union type that can represent all CL values. Or (better, but not quite the same semantics) translate those CL values with ML type annotations back to corresponding ML types, and insert conversions to convert between the generic CL type and other specific types where appropriate. Suppose the original ML program defines the following functions foo : int -> int bar : string -> string ... We can add dynamic typing like this: datatype Generic = Int of int | String of string | Atom of string | Cons Generic Generic | Apply Generic Generic | ... fun foo_wrapper (Int x) = (Int (foo x)) fun bar_wrapper (String x) (String (foo x)) and then dynamic binding like this val foo_binding = ref foo_wrapper val bar_binding = ref bar_wrapper For dynamic binding, function calls will have to be translated to does an indirection. So a call let y = foo x will become let y = !foo_binding x or, if x and y are used in a way that requires that they have type int, then let (Int y) = !foo_binding (Int x) We can then simulate eval using an explicit symbol table. fun lookup "foo" = !foo_binding | lookup "bar" = !bar_binding | lookup "define" = !define_binding ... fun define "foo" f = foo_binding := f | define "bar" f = bar_binding := f | define "define" f = define_binding := f ... fun define_wrapper (Cons (Atom name) body) = let () = define name body in Atom "()" val define_binding = ref define_wrapper fun eval (Apply func arg) = case (eval func) of Atom funcname => (lookup funcname) (eval arg) | eval x = x Note that our symbol table includes an entry for the function "define", so that eval can be used to modify the dynamic bindings. The rest (e.g. read) is straight-forward. >To ask the question in more detail: > >a) Is it possible to write CL->ML in a way that the result is both still >statically type checkable Yes, but only in a weak sense. Since we are allowing dynamic binding, and we want to be able to dynamically bind symbols to a different type, we're definitely going to have the possibility of dynamic type errors. The way this is resolved is that things which would have been type errors in the original ML program may become data errors (invalid constructor in an algebraic type Generic) in the final ML program. >and not considerably larger than the original program that was given to >ML->CL. There's a little bit of overhead for the wrapper functions of type "Generic -> Generic", and for the variables of type "ref (Generic -> Generic)" which store the dynamic bindings. It's about two lines of code per function in the original program. I don't think this is excessive. >Especially, is it possible to do this >without implementing a new interpreter/compiler on top of ML and then >letting the program run in that language, but keep the program >executable in ML itself? The program includes a definition for "eval", and "eval" is an interpreter, So in that sense, we have added a new interpreter. But the bulk of the program is written in ML, without making use of eval. >c) If you respond with yes to either a or b, what does your sketch of an >informal proof in your head look like that convincingly shows that this >can actually work? See above. -- Fergus Henderson | "I have always known that the pursuit The University of Melbourne | of excellence is a lethal habit" WWW: | -- the last words of T. S. Garp. From walterm at parque.homelinux.net Thu Nov 13 19:00:51 2003 From: walterm at parque.homelinux.net (Walter Moreira) Date: Thu, 13 Nov 2003 21:00:51 -0300 Subject: Making a maze.... In-Reply-To: <1PSsb.44675$jy.34613@clgrps13> References: <1PSsb.44675$jy.34613@clgrps13> Message-ID: <20031114000051.GA11138@casa> On Thu, Nov 13, 2003 at 09:35:57PM +0000, Bernard Fields wrote: > Greets, all. > > > As the title suggests, I'm trying to make a maze. Specifically, it's a > top-down, 2-d maze, preferably randomly generated, though I'm willing to > forego that particular aspect as this point. > > I've done many, many web-searches, but nothing that I've found so far has > provided any clues.... The following url was useful for me: http://www.ai.mit.edu/people/shivers/mazes.html Algorithms are written in Scheme but they are translated almost verbatim to Python. Walter -- -------------- Walter Moreira <> Centro de Matematica <> Universidad de la Republica email: walterm at cmat.edu.uy <> Home Page: http://www.cmat.edu.uy/~walterm PGP: 0x1DB0E000 45DC 8212 9680 4507 5E5A 7490 0134 8144 1DB0 E000 PGP key: www.keyserver.net From aleax at aleax.it Sat Nov 1 05:57:46 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 01 Nov 2003 10:57:46 GMT Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> Message-ID: Shawn Gordon wrote: ... > John cannot legally sell the Rekall software, nor does he own it. *OUCH* -- with you claiming this against them, and they claiming the same against you, we're exactly in the situation where any potential customer will run away from Rekall and back into MS Access _fast_... who needs to risk lawsuits?! Unlikely as it may be, given the current appearance of enmity, I sure hope you and them can come to some kind of agreement on this "detail" and make a joint announcement about it, otherwise, this may just be the Knell of Death for Rekall in the corporate market, and nobody ain't gonna make any money from it, no matter who's right and who's wrong about the present controversy. I do sometimes get asked for advice about "an Access-like product that's cross-platform" and the like, but I couldn't in good faith suggest Rekall if I thought that could potentially send the purchaser into the midst of a legal controversy. Sigh. Alex From FBatista at uniFON.com.ar Tue Nov 4 12:50:55 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 4 Nov 2003 14:50:55 -0300 Subject: prePEP: Decimal data type Message-ID: Ron Adam wrote: #- >The Decimal data type should support the Python standard #- functions and #- >operations and must comply the decimal arithmetic ANSI #- standard X3.274-1996. #- #- Is this the correct ANSI number? I ended up at the following #- websight. #- #- http://www.rexxla.org/Standards/standards.html I took the ANSI number from the previous Decimal.py code. Anyway, I didn't read the ANSI standard, just the General Decimal Arithmetic Specification, the Mike Cowlishaw's work at http://www2.hursley.ibm.com/decimal/. . 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 FBatista at uniFON.com.ar Tue Nov 4 12:16:05 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 4 Nov 2003 14:16:05 -0300 Subject: prePEP: Decimal data type Message-ID: Emile van Sebille wrote: #- > 3. To exist a Context. The context represents the user-selectable #- > parameters #- > and rules which govern the results of arithmetic #- operations. In the #- > context the user defines: #- > #- > - what will happen with the exceptional conditions. #- > - what precision will be used #- > - what rounding method will be used #- > #- > 4. The Context must be omnipresent, meaning that changes #- to it affects all #- > the current and future Decimal instances. #- #- Does this imply then that there is unlimited precision being #- maintained #- under the covers? No, why? Under the cover you got: - sign - coefficient (just several decimal digits, fixed in quantity) - exponent . Facundo From fredrik at pythonware.com Fri Nov 21 08:23:43 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 21 Nov 2003 14:23:43 +0100 Subject: Passing list with flexible length to C extension References: <20031121125404.GA3369@mf.uni-lj.si> Message-ID: Bostjan Jerko wrote: > Is there a way to pass list with flexible length to C extension? > I want to pass flexible length list of floats to method and just can't get info > if it is possible and how to do it. use a PyObject* variable to hold the list object (use "O" for the type code), and use the sequence API to loop over the list contents: http://www.python.org/doc/current/api/sequence.html unless your sequences are really large, the PySequence_Fast API is the most efficient way to extract the items (it applies tuple() to the source, unless it's already a tuple or a list, and uses direct access to the object structure to pick out individual items): ... PyObject* obj; PyObject* seq; int i, len; if (!PyArg_ParseTuple(args, "O", &obj)) return NULL; seq = PySequence_Fast(obj, type_error_msg); len = PySequence_Size(obj); for (i = 0; i < len; i++) { item = PySequence_Fast_GET_ITEM(seq, i); ... /* DON'T DECREF item here */ } Py_DECREF(seq); ... you'll find plenty of examples in the source code for the standard library grep for PySequence and look for GetItem, GET_ITEM, and Fast_GET_ITEM calls...) you can also use the PyList API, but that only works for lists, and is only marginally faster than the PySequence_Fast API. http://www.python.org/doc/current/api/listObjects.html (to squeeze out the last cycles from PySequence_Fast, expand the loop body yourself: seq = PySequence_Fast(obj, type_error_msg); len = PySequence_Size(obj); if (PyList_Check(seq)) for (i = 0; i < len; i++) { item = PyList_GET_ITEM(seq, i); ... } else for (i = 0; i < len; i++) { item = PyTuple_GET_ITEM(seq, i); ... } Py_DECREF(seq); this design is as fast as a list-only implementation, but still supports tuples (fast) and other sequence objects, including arbitrary iterable objects (slower)). From mikit at zoran.co.il Thu Nov 27 02:55:25 2003 From: mikit at zoran.co.il (Miki Tebeka) Date: 26 Nov 2003 23:55:25 -0800 Subject: py2exe issues References: Message-ID: <6250403b.0311262355.70044798@posting.google.com> Hello Mark, > Now I'm trying py2exe. I use the bdist wininst > method (?) and it seems to create all the files. I usually use "python setup.py py2exe" and it works fine. > However, nothing > happens when I double-click the .exe file. I saw similar behavior from > Installer, so I'm inclined to think there's something wrong with the > script. It runs fine from my Python directory. I am currently > searching the code for any weird hard-coded pathnames or something like > that, but I don't think that should matter. Make sure py2exe create a console program and run it from a "cmd" window. If there any exception you'll be able to see them. A wild guess whould be that your script is using some module that wasn't detected by distutils and you get an ImportError, if this is the case use the --force-import option of py2exe. HTH. Miki From stephen at dino.dnsalias.com Thu Nov 6 21:22:21 2003 From: stephen at dino.dnsalias.com (Stephen J. Bevan) Date: Fri, 07 Nov 2003 02:22:21 GMT Subject: Explanation of macros; Haskell macros References: <87brs2tjut.fsf@memetrics.com> Message-ID: "Coby Beck" writes: [big snip] > But back to macros, and really any language feature, they are all just tools > and it is always a judgment call as to what the best tool for a job is and > judgements are always subjective. It is very hard to convince anyone that a > tool they are completely unfamiliar with is the best one for some problem > they never thought they had. Indeed. That's why I suggested if one wants to convince someone of the utility of macros one has to find out what problems they are trying to solve and show how macros can help them solve those problems (obviously takes time and effort). Attempts to show the utility of macros by showing how one solves one's own problems using them tend to miss the mark unless one is lucky and others are trying to solve the same problems. From simonb at webone.com.au Mon Nov 10 02:00:17 2003 From: simonb at webone.com.au (Simon Burton) Date: Mon, 10 Nov 2003 18:00:17 +1100 Subject: Assembler Parser/Lexer in Python References: <3fabc59e.42407448@news.dsl.pipex.com> Message-ID: On Thu, 06 Nov 2003 22:06:45 +0000, Simon Foster wrote: > > Anyone have any experience or pointers to how to go about creating > a parser lexer for assemble in Python. I was thinking of using PLY > but wonder whether it's too heavyweight for what I want. Anyone have > any thoughts? Write the parser yourself? is assembly really that complex? Simon. From marc.lentz at ctrceal.caisse-epargne.fr Wed Nov 19 04:47:12 2003 From: marc.lentz at ctrceal.caisse-epargne.fr (marco) Date: Wed, 19 Nov 2003 10:47:12 +0100 Subject: "python exe" and "py plugins" References: Message-ID: great ! it works with dynamic import ( __import__() )! it's a lot better than an execfile ... "Marc Boeren" a ?crit dans le message de news: mailman.826.1069158322.702.python-list at python.org... > > > and it works WITHOUT THE PYTHON RUNTIME INSTALLED ... > > sure that this script can't import lib which are not in the exe ;-) > > If I remember correctly py2exe provides the python23.dll, so there's your > runtime... meaning that you can probably import whatever library you wish in > your plugin. > You can probably also dynamically import your plugin instead of using > execfile. > > Cheerio, Marc. > From peter at engcorp.com Fri Nov 21 12:20:00 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Nov 2003 12:20:00 -0500 Subject: small, fast and cross-platform flat-file database for python References: <425cc8d1.0311210915.33eb10e0@posting.google.com> Message-ID: <3FBE4940.BD960E76@engcorp.com> mir nazim wrote: > > i want to know if there is any flat-file relational database system ^^^^^^^^^ ^^^^^^^^^^ I'm no database expert, but aren't these two terms contradictory in some important way? -Peter From pmaupin at speakeasy.net Wed Nov 12 21:26:37 2003 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 12 Nov 2003 18:26:37 -0800 Subject: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> Message-ID: <653b7547.0311121826.65b6b2d4@posting.google.com> Douglas Alan wrote: > Describing reduce() in 10 seconds is utterly trivial to anyone with an > IQ above 100, whether or not they have ever used sum() Well, yeah, but they may not need or want to learn or remember it. And then there are the corner cases, e.g. sum([]) vs. reduce(operator.add,[]) (which throws an exception). > If someone can't understand this quickly, then they shouldn't be > programming! Again, it's not "can't", it's whether they need to or not. > I'm sorry, but you are incorrect. When I took CS-101, we learned > assembly language, then were assigned to write a text editor in > assembly language, then we learned LISP and were assigned to write > some programs in LISP, and then we learned C, and then we were > assigned to implement LISP in C. > > If you can write a !$#@!!%# LISP interpreter in C, you no doubt can > figure out something as mind-achingly simple as reduce()! Ahh, the lisp background. I _knew_ that would come out sometime :) Seriously, though, even in this scenario -- you don't really need reduce() to create a LISP interpreter (as I'm sure you found when you wrote one in C). > > Ignorance is not stupidity. > > Assuming that your audience cannot learn the simplest of concepts is > assuming that they are stupid, not that they are ignorant. As I and others have pointed out, it's not a matter of assuming they can't learn, it's a matter of assuming they have better things to do. Many people can write all the useful programs they will ever need without reduce, and sum() makes the percentage of Python users who can do this even higher. (Having said that, I never personally argued that reduce() should be removed from the language, but I do agree that it does not have to be part of "core" Python, and could easily be relegated to a module.) > > >> I sure hope that Python doesn't try to emulate C. It's a terrible, > >> horrible programming language that held back the world of software > >> development by at least a decade. > > > I used to hate C. But then, when it borrowed enough good concepts > > from Pascal and other languages, and the compilers got smart enough > > to warn you (if you cared to see the warnings) about things like > > "if (x = y)" I stopped using Modula-2. C held software back 10 > > years in the same manner as Microsoft did, e.g. by helping to > > standardize things to where I can buy a $199 system from WalMart > > which would cost over $20,000 if everybody kept writing code like > > the pointy-headed ivory tower academics thought it ought to be written. > > You score no points for C by saying that it is like Microsoft. That's > a strong damnation in my book. And you really don't know how the > world would have turned out if a different programming language had > been adopted rather than C for all those years. Perhaps computers > would be more expensive today, perhaps not. On the other hand, we > might not have quite so many buffer overflow security exploits. > Perhaps we'd have hardware support for realtime GC, which might be > very nice. On the other hand, perhaps people would have stuck with > assembly language for developing OS's. That wouldn't have been so > pretty, but I'm not sure that that would have made computers more > expensive. Perhaps a variant of Pascal or PL/1 would have taken the > niche that C obtained. Either of those would have been better, though > no great shakes either. I agree that I cannot know how the world would have turned out without C and Microsoft; but likewise, you cannot know for sure that computer science would be ten years farther along by now :) (And I personally feel my alternate universe is more realistic than yours, but then everybody should feel that way about their own private alternate universe.) > >> The reason for Python's wide acceptance isn't because it is > >> particularly well-designed compared to other programming languages > >> that had similar goals of simplicity and minimality (it also isn't > >> poorly designed compared to any of them -- it is on par with the > >> better ones) -- the reason for its success is that it was in the right > >> place at the right time, it had a lightweight implementation, was > >> well-suited to scripting, and it came with batteries included. > > > I'd vote this as the statement in this group most likely to start > > a religious flamewar since the lisp threads died down. > > The only way it could start a religious flamewar is if there are > people who wish to present themselves as fanboys. I have said nothing > extreme -- just what is obvious: There are many nice computer > programming languages -- Python is but one of them. If someone > wishes to disagree with this, then they would have to argue that there > are no other nice programming languages. Now that would be a flame! Well, I guess I may have read more into your original statement than you put there. You wrote "similar goals of simplicity and minimality", and to me, the language is pretty much a gestalt whole, in the sense that when I read "similar goals" I was thinking about all the features that, to me, make Python Python. These goals actually include the lightweight implementation, the portability, the suitability to scripting, etc. In one way or another, I feel that these contribute to its simplicity and minimality, and on rereading your words, I think you were probably mainly referring to the syntax and semantics. (Even there, however, as I think Alex has pointed out, design decisions were made which might make the semantics less than optimal, yet contribute heavily to the small size and portability of the language.) > I'm not sure what you are getting at. There were many nice > programming languages before Python, but not many of them, other than > Perl, were portable and well-suited to scripting. I was just challenging you to defend a position which it appears in hindsight you didn't really take :) > > > 3) Do you _really_ think that all the batteries were included when > > Python first came out? > > It certainly was not a particularly popular language until it came > with pretty hefty batteries. There are many other languages that > would have been equally popular before Python started coming with > batteries. Here is one area where I think the genius of the design shows through. Even _before_ the batteries were included, in a crowded field of other languages, Python was good enough to acquire enough mindshare to start the snowball rolling, by attracting the kind of people who can actually build batteries. > > Do you even think that Python has more batteries _right_ _now_ than > > Perl (via CPAN), or that some competing language couldn't or hasn't > > already been designed which can coopt other languages' batteries? > > Um, the last time I checked Perl was still a lot more popular than > Python, so once again I'm not sure what you are getting at. Regarding > whether or not some future language might also come with batteries and > therefore steal away Python's niche merely due to having more > batteries: Anything is possible, but this will be an uphill battle for > another language because once a language takes a niche, it is very > difficult for the language to be displaced. On the other hand, a new > language can take over a sub-niche by providing more batteries in a > particular area. PHP would be an example of this. We are in agreement that Perl has more batteries than Python, and also more "marketshare." To me, this is yet another testament to Python's good design -- it is in fact currently on a marketshare ramp, mostly because it attracts the kind of people who can do an excellent job of writing the batteries. > > I can accept the premise that, for Python to enjoy the acceptance it > > does today, Guido had to be lucky in addition to being an excellent > > language designer. But if I were to accept the premise that > > Python's popularity is due to sheer luck alone my only logical > > course of action would to be to buy Guido a plane ticket to Vegas > > and front him $10,000 worth of chips, because he has been extremely > > lucky for many years now. > > I never claimed *anything* like the assertion that Python's popularity > is due to luck alone! In the post I was responding to, you wrote "The reason for Python's wide acceptance isn't because it is particularly well-designed compared to other programming languages," and you also used the phrase "in the right place at the right time." To me, these statements taken together implied that you thought the process leading to Python's ascending popularity was mostly stochastic. Your later posting (and a more careful reading of your original post) help me to put your words in the proper context, and seem to indicate that our opinions on the subject are not as divergent as I first thought they were. Regards, Pat From rainerd at eldwood.com Tue Nov 18 03:02:36 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Tue, 18 Nov 2003 08:02:36 GMT Subject: Origin of the term "first-class object" References: <8ef9bea6.0311171335.356a7af6@posting.google.com> Message-ID: Ben Finney wrote: > On Tue, 18 Nov 2003 03:01:35 GMT, Rainer Deyke wrote: >> One would be passing a name as an argument >> to a function. > > To accomplish what? What would you be doing with the name that you > can't do just as easily by passing the object (by reference, as always > happens in Python)? Binding the name to a different object. >> Given the immutability of certain Python objects, it is >> often necessary to write statements in the form of >> "x = f(x)". > > I don't understand the logic here. What is it that necessitates > "x = f(x)", For example, any "mutating" operation on x, where x is an immutable object. Trivial and useless example: def increment(x): return x + 1 i = increment(i) > and why is that undesirable? Suppose the 'x' in 'x = f(x)' is not a simple variable, but an element in a list l[x * 2 + f(y)] = f(l[x * 2 + f(y)]) This statement contains an obvious redundancy that will make code maintenance difficult. Python allows me to factor out some of the redundancy: index = x * 2 + f(y) l[index] = f(l[index]) However, Python gives me no way to factor out the remaining redundancy. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From emile at fenx.com Mon Nov 3 16:49:15 2003 From: emile at fenx.com (Emile van Sebille) Date: Mon, 3 Nov 2003 13:49:15 -0800 Subject: EIBTI Message-ID: What does this mean? Emile van Sebille emile at fenx.com From gh at ghaering.de Mon Nov 24 05:28:29 2003 From: gh at ghaering.de (=?ISO-8859-2?Q?Gerhard_H=E4ring?=) Date: Mon, 24 Nov 2003 11:28:29 +0100 Subject: Dyna grid In-Reply-To: <17910121023.20031124112023@peto.hu> References: <17910121023.20031124112023@peto.hu> Message-ID: <3FC1DD4D.7020806@ghaering.de> Kepes Krisztian wrote: > Szia ! [...] Szervusz! ;-) Normally we speak English on python-list, because a much larger audience speaks English here than Hungarian. Perhaps you can resend your message in English? -- Gerhard From ivan_r_moore at yahoo.com Wed Nov 5 05:12:00 2003 From: ivan_r_moore at yahoo.com (ivan_r_moore) Date: Wed, 05 Nov 2003 10:12:00 -0000 Subject: COM event callbacks Message-ID: Hello, Does anyone know how to do the Python equivalent of the Ruby WIN32OLE_EVENT example in: http://www.rubycentral.com/book/lib_windows.html in which WIN32OLE_EVENT is used in conjunction with the WIN32OLE class to add callbacks for Windows 32 events. BTW - using Ruby isn't the answer I'm looking for! thanks, Ivan From peter at engcorp.com Wed Nov 12 10:21:51 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 Nov 2003 10:21:51 -0500 Subject: readline() after popen hangs References: Message-ID: <3FB2500F.E8EC0CD@engcorp.com> Thomas Steffen wrote: > > here my code: > ... > (sin, souterr) = os.popen4(command) > while 1: > line = souterr.readline() > print line > if not line: > break > ... > > Now I have the problem: the last two lines are written after five > (5!!!) minutes. Why so a long time? Note that doing "print line" before the check for "not line" doesn't make sense, as you would then be printing an empty line when in fact you had reached the end of the data. You don't show the command involved, so we're just guessing. My guess is that you are not providing the other program that you are invoking with the input data that it needs, via sin, and that after the five minute timeout the program is quitting and you are getting the final output only as it exits. Why are you grabbing "sin" if you aren't going to use it? -Peter From matt at pollenation.net Thu Nov 27 06:17:23 2003 From: matt at pollenation.net (Matt Goodall) Date: Thu, 27 Nov 2003 11:17:23 +0000 Subject: Newbie problem In-Reply-To: <20031127120418.4bb0e7f2.secchi@sssup.it> References: <20031127120418.4bb0e7f2.secchi@sssup.it> Message-ID: <3FC5DD43.208@pollenation.net> Angelo Secchi wrote: >Hallo, > >I have the following problem. I'm trying to clean a database whose lines >look like: > >"2/G DM" "HOE" 0 "R5D2" 1 0 0 0 > >in particular I need to remove the ". > >Here my code > >def wash(a) : > a=string.replace(a,'"','') > return a > >data=file("prova.txt",'r') >data_clean=file("prova_clean.txt",'w') > >temp_string = data.readline() >while len(temp_string) != 0: > temp_field=string.split(temp_string,'\t') > print temp_field > temp_field=map(wash,temp_field) > print temp_field > data_clean.write(temp_field) > temp_string = data.readline() > >data.close() >data_clean.close() > >Of course I receive an error in line "data_clean.write(temp_field)" >saying "TypeError: argument 1 must be string or read-only character >buffer, not list". I'm a newbie and reading tutorials around I was not >able to find the best solution to my problem. Could anybody help me? > > You presumably need to output the result with tab delimiters as in the source file so you need to do: >>> data_clean.write('\t'.join(temp_field)) I should point out that your code could be greatly simplified. You could write it something like this (untested): >>> data=file("prova.txt",'r') >>> data_clean=file("prova_clean.txt",'w') >>> for line in data: >>> line = '\t'.join([s.replace('"','') for s in line.split('\t')]) >>> data_clean.write(line) You may prefer to continnue using map() rather than a list comprehension, that's up to you. My final point (I promise!) is that this looks remarkably like a tab delimited CSV file. Are you aware of the standard CSV module in Python 2.3? If you're using an older version of Python then there is also Object Craft's CSV parser. Hope this helps. Cheers, Matt -- Matt Goodall, Pollenation Internet Ltd w: http://www.pollenation.net e: matt at pollenation.net t: +44 (0)113 2252500 From ramen at lackingtalent.com Tue Nov 11 01:59:19 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 11 Nov 2003 06:59:19 -0000 Subject: True, False, None (was re. Pruss's manifesto) References: <20031110065915.07735.00000461@mb-m07.aol.com> Message-ID: In article , David Eppstein wrote: > In article , > "John Roth" wrote: > >> Making them keywords isn't exactly correct. There's a movement >> to make just about everything in the built-in scope immutable and >> not rebindable at any lower scope for performance reasons. The >> usual example is the len() built-in function. All this function does is >> call the __len__() method on the object; the extra function call >> is a complete waste of time, and could be eliminated if the >> compiler could depend on len() never being modified or >> rebound at any level. > > This would also have the advantage of more quickly catching certain > common programming errors.... This would break backward compatibility, especially with some of the more popular variable names like "file" and "list" (most of us know not to do that these days, but they're such tasty words, I'm sure there's enough code out there to make the restriction painful). I seem to remember Guido being opposed to command-line arguments that change the language, but it seems like this could be a good opportunity for an argument that locks down built-ins. -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From mir4uu at yahoo.com Fri Nov 21 12:15:00 2003 From: mir4uu at yahoo.com (mir nazim) Date: 21 Nov 2003 09:15:00 -0800 Subject: small, fast and cross-platform flat-file database for python Message-ID: <425cc8d1.0311210915.33eb10e0@posting.google.com> hi. i want to know if there is any flat-file relational database system available for python. i require it in a project. it should have following capabilities: 1. should be small and compact on system requirments. 2. should be roubust and fast. 3. must be able to handle a bit large tables( upto 5000 rows) 4. should be available for both linux and ms windows 9x/xp/2000 platforms. 5. it will be nice if it supports sql-92. hopping to find some real good help soon bye. blesess-n-luck From bobx at linuxmail.org Sat Nov 8 08:01:44 2003 From: bobx at linuxmail.org (Bob X) Date: Sat, 08 Nov 2003 13:01:44 GMT Subject: Sleepycat DBXML included? Message-ID: I read on the Sleepycat site that dbXML was included in the 2.3 release. I downloaded the latest from the Python site but get a traceback when trying to import it. Was it removed? Can I get it somewhere else? From marco at analog.se Thu Nov 13 04:38:57 2003 From: marco at analog.se (Marco) Date: 13 Nov 2003 01:38:57 -0800 Subject: ANN: ruleCore - The event pattern detector engine References: <438a319a.0311091143.256db982@posting.google.com> <1Q5sb.23278$M02.14529@twister.rdc-kc.rr.com> <438a319a.0311112313.22df2a95@posting.google.com> Message-ID: <438a319a.0311130138.19261078@posting.google.com> GrayGeek wrote in message news:... > Marco wrote: > > > Yes, I can imagine that there are lots of events in an industrial > > process control setup. I suppose all these events could be fed into > > ruleCore and there it could detect all kinds of interesting patterns of > > events that should be reacted to. > > > > I didn't understand much of the ladder, but it seems to be some kind of > > tool for event correlation just as ruleCore is. > > Most industrial process controllers come with a software/hardware modeling > tool that uses the IEC 1131-3 language. Once you get the model working > (using Ladder, for instance) you can then burn the software that the Ladder > generates into the control EPROM. ok, this seems to be a bit more low-level than ruleCore is intended for. But people tend to use software in the most strange ways.... ;) It is a interesting idea to use ruleCore for monitoring industrial process things, really cool. I suppose there exists some kind of standard to extract events from your typical industrial process thingy and somehow collect them all and send them into a ruleCore instance? From newsgroups at jhrothjr.com Mon Nov 10 18:21:48 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 10 Nov 2003 18:21:48 -0500 Subject: What do you think of this Python logo? References: Message-ID: "Brandon J. Van Every" wrote in message news:bop24j$1gg5h3$1 at ID-207230.news.uni-berlin.de... > What do you think of this Python logo? > http://pythonology.org/logos > Good, bad, indifferent, love it, hate it? > > -- > Cheers, www.indiegamedesign.com > Brandon Van Every Seattle, WA > > Brandon's Law (after Godwin's Law): > "As a Usenet discussion grows longer, the probability of > a person being called a troll approaches one RAPIDLY." Looks a little bit like the Worm Oroboros (sp?) when it took a break from chewing on its tail. John Roth > > From thomas.rademacher at nikocity.de Wed Nov 12 10:14:23 2003 From: thomas.rademacher at nikocity.de (Thomas Steffen) Date: 12 Nov 2003 07:14:23 -0800 Subject: readline() after popen hangs Message-ID: Hallo, here my code: ... (sin, souterr) = os.popen4(command) while 1: line = souterr.readline() print line if not line: break ... Now I have the problem: the last two lines are written after five (5!!!) minutes. Why so a long time? Who has a solution for this problem? Thank you for your hints, Thomas From SEE_AT_THE_END at hotmail.com Sun Nov 9 21:58:27 2003 From: SEE_AT_THE_END at hotmail.com (Georgy Pruss) Date: Mon, 10 Nov 2003 02:58:27 GMT Subject: Bad docs for os.path.isabs() References: <3FAEB530.D67D27BC@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3FAEB530.D67D27BC at engcorp.com... > Ben Allfree wrote: > > > > The docs for os.path.isabs() state: > > > > isabs( path) > > > > Return True if path is an absolute pathname (begins with a slash). > > > > This is false becase os.path.isabs("C:\\foo") == True > > > > It should read: > > > > isabs( path) > > > > Return True if path is an absolute pathname (begins with a slash or drive > > letter). > > As Bengt says, that revision is still insufficient/incorrect. > > Probably the only way it can really be said is something like > "returns True if os.path.abspath() would leave the path unchanged". >>> os.path.isabs("C:\\foo\\..\\bar") True >>> os.path.abspath("C:\\foo\\..\\bar") 'C:\\bar' And both are right G-: > (Or some variation on that... i.e. leave the actual specification > to the nuts-and-bolts of the platform-dependent code, rather than > trying to rewrite it in English and risk duplication/errors.) > > -Peter From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Mon Nov 17 14:44:17 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Mon, 17 Nov 2003 22:44:17 +0300 Subject: Variable interpolation question In-Reply-To: References: Message-ID: Bengt Richter wrote: > On Mon, 17 Nov 2003 20:47:51 +0300, anton muhin wrote: > > >>Andrew Fabbro wrote: >> >> >>>This is probably a beginner's question, but I'm stuck...please be kind >>>to an ex-perler ;) >>> >>>How do I do something like this: >>> >>>for attr in dir(some_obj): >>> if ( some_obj.attr == 0 ): >>> print "Missing data: %s field %s" % ( some_obj.name, >>>some_obj.attr) >>> >>>Of course, this gives >>>"AttributeError: foo instance has no attribute 'attr'" >>> >>>I really don't want to use exec/eval, as that slows things down >>>dramatically. >>> >>>Help? >>> >>>Thanks. >>> >>>-Drew >> >>You are probably looking for hasattr/getattr functions: >> >>for attr in dir(some_obj): >> if hasattr(some_obj, attr) and getattr(some_obj, attr) == 0: >> print 'blah...' >> >>of course, it could be shorter: >> >>.... >> if getattr(some_obj, attr, 0) == 0: >> print 'blah' >> > > Or why use an "== 0" test when just hasattr tests for presence/absence without using up > a possible value of the attribute for flag purposes? > [skipped] > Regards, > Bengt Richter Of course you're right, I just forgot it and thought that OP wants to verify attribute's presence as well---mea culpa. regards, anton. From SBrunning at trisystems.co.uk Thu Nov 13 10:16:17 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Thu, 13 Nov 2003 15:16:17 -0000 Subject: case-sensitivity Message-ID: <31575A892FF6D1118F5800600846864D01200CD1@intrepid> > From: Douglas Alan [SMTP:nessus at mit.edu] > > I agree with Alex. Case sensitivity is evil! When color monitors > started becoming common, I began to worry that programming languages > would come to allow you to have blue variable names, and red and green > variables names, and they would all be different. Or maybe even > variable names in mixed color! Then in mixed color and font. I > better be quiet now, lest I give anyone ideas. Too late! http://www.brunningonline.net/simon/blog/archives/000666.html BTW, some of the other ideas expressed in JSR-666 might be applicable to Python. I'm thinking particularly of "import *". ;-) Cheers, Simon Brunning. ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From peter at engcorp.com Tue Nov 18 10:50:50 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Nov 2003 10:50:50 -0500 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: <7N6dnUz1P9CKZTOiRVn-hQ@comcast.com> Message-ID: <3FBA3FDA.C5385A9C@engcorp.com> Terry Reedy wrote: > > I am somewhat flabbergasted that more people do not see the oddity of > "I will not read your first message (yet) but I will read a second > message from you in which you attempt to give me a reason that I find > 'acceptible', according to my unknown-to-you whims, that I do read > your first message." I completely agree with you on this subject Terry. The whole approach is extremely misguided and discourteous, especially in the light of this being about information that should have been welcomed by Edward. I'm using TMDA right now, which is remotely similar but doesn't require the "reason", just a real mailbox and a living person or an autoresponder... even so, this whole thing is starting to make me rethink even that approach. -Peter From jerry at sumpton.com Wed Nov 5 14:32:12 2003 From: jerry at sumpton.com (Jerry Sumpton) Date: 5 Nov 2003 11:32:12 -0800 Subject: Outlook add-in required to sort messages Message-ID: <7d88291f.0311051132.4a9b4f0f@posting.google.com> Hi, I am looking to have an Outlook add-in created that will interrogate a spam related server and sort messages into folders based on the response. It looks like most of the functionality is already used in SpamBayes. Can you offer suggestions on how to locate a suitable developer? Another list, perhaps? Thanks, Jerry. From mark at hahnca.com Wed Nov 26 14:12:17 2003 From: mark at hahnca.com (Mark Hahn) Date: Wed, 26 Nov 2003 11:12:17 -0800 Subject: The Python Application Framework (PAF) is released References: Message-ID: I am about to start my second wxPython-based app, which is is a news/email reader. I was planning on using bsddb with shelve for my data storage. Can you give me a "sales pitch" for why I should consider PAF? "TDC" wrote in message news:bQ3xb.44675$tU.1545310 at phobos.telenet-ops.be... > Hi all, > > The Python Application framework made it's first release. This framework > will make your life as a application developper a lot easier. PAF consists > of a set of easy-to-use components, such as CORBA-support, error-handling > and a GUI framework based on wxPython. You can check it out for yourself at > our open source site www.dctools.org . > > From alanmk at hotmail.com Mon Nov 24 07:21:20 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 24 Nov 2003 12:21:20 +0000 Subject: Programming cellular phones using Python/Jython ? References: <23891c90.0311240356.1513e84a@posting.google.com> Message-ID: <3FC1F7C0.89E470BD@hotmail.com> [Thomas Weholt] >>> Is it at all possible to use python to make apps on cellular/mobile >>> phones, using something like Jython etc. ? [Mark Hahn] >> I just got a samsung sph-i700 phone with pocket pc 2002 and it runs python >> 2.2+ apps with win32 gui just fine. I got the binaries for it from: >> http://www.murkworks.com/Research/Python/PocketPCPython/Overview [Paul Boddie] > I suppose the question was really more concerned with making use of > the Java support that a lot of new mobile 'phones seem to have these > days. I can't imagine that a significant number of 'phones out in the > European market (and certainly in the Norwegian market) are running > some kind of Windows derivative, but many manufacturers are promoting > their Java application (eg. games) support. I haven't done any work with jython on mobile phones, but here are some considerations which I think apply. 1. Java support on mobile phones is usually J2ME - Java2 Micro Edition. 2. J2ME is a cut down version of Java which does not support all of the java facilities that jython requires, notably some of the reflection APIs. Here are some urls that discuss this topic. http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=840592e1.0308170739.1de04d6d%40posting.google.com http://www.geocrawler.com/mail/msg.php3?msg_id=9169196&list=7018 http://www.geocrawler.com/mail/msg.php3?msg_id=6466738&list=7017 http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=GvKvDK.FHr%40bath.ac.uk http://aspn.activestate.com/ASPN/Mail/Message/Jython-users/1638105 HTH, P.S. Paul, thanks for drawing attention to xml.dom.javadom in another thread: I never knew it was there! -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From hfastjava at yahoo.com Sat Nov 8 19:26:13 2003 From: hfastjava at yahoo.com (Hunter Peress) Date: Sat, 8 Nov 2003 16:26:13 -0800 (PST) Subject: truly working multipart uploads. Message-ID: <20031109002613.47680.qmail@web41314.mail.yahoo.com> I have been unable to write a script that can do (and receieve) a multipart form upload. Also, it seems that there really are differences between python's implementation and else's. Can someone please prove me wrong with a script that works with itself AND with example 18-2 from php: http://www.php.net/manual/en/features.file-upload.php __________________________________ Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard http://antispam.yahoo.com/whatsnewfree From aahz at pythoncraft.com Tue Nov 18 09:59:07 2003 From: aahz at pythoncraft.com (Aahz) Date: 18 Nov 2003 09:59:07 -0500 Subject: Origin of the term "first-class object" References: <8ef9bea6.0311171335.356a7af6@posting.google.com> Message-ID: In article , Rainer Deyke wrote: > >Suppose the 'x' in 'x = f(x)' is not a simple variable, but an element in a >list > >l[x * 2 + f(y)] = f(l[x * 2 + f(y)]) > >This statement contains an obvious redundancy that will make code >maintenance difficult. Python allows me to factor out some of the >redundancy: > >index = x * 2 + f(y) >l[index] = f(l[index]) > >However, Python gives me no way to factor out the remaining redundancy. Sure it does: change the immutable to a mutable. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From rohit.nadhani at tallysolutions.com Mon Nov 17 05:32:14 2003 From: rohit.nadhani at tallysolutions.com (RN) Date: Mon, 17 Nov 2003 16:02:14 +0530 Subject: Newbie - Variable Scope Message-ID: I have a 2 Python scripts that contain the following lines: test.py ------- from testmod import * a1 = 10 modfunc() testmod.py ----------- def modfunc(): print a1 When I run test.py, it returns the following error: File "testmod.py", line 2, in modfunc print a1 NameError: global name 'a1' is not defined My intent is to make a1 a global variable - so that I can access its value in all functions of imported modules. What should I do? Thanks in advance, Rohit From fredrik at pythonware.com Wed Nov 19 08:15:56 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 19 Nov 2003 14:15:56 +0100 Subject: ANN: PyLogo 0.1 References: <3FBB4345.3020107@domain.invalid> <3FBB66C6.AFAFF104@engcorp.com> Message-ID: Peter Hansen wrote: > > Just tried it, and this is what I get > > ++++++++++++++++++ > > Traceback (most recent call last): > > File "/usr/bin/pylogo", line 6, in ? > > if os.path.basename(os.path.dirname(__file__)) == 'scripts': > > NameError: name '__file__' is not defined > > ++++++++++++++++++ > > Probably a sign that it requires Python 2.3 or something... or, in older versions, that you're running something as a script when it's designed to be imported as a module. From Mike at DeleteThis.Geary.com Sat Nov 8 18:43:08 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 8 Nov 2003 15:43:08 -0800 Subject: Nested for loop problem References: <3fad715f$0$58715$e4fe514c@news.xs4all.nl> Message-ID: > #!/usr/bin/python > > for n in range(2, 10): > for x in range(2, n): > if n % x == 0: > print n, 'equals', x, '*', n/x > break > else: > # loop fell through without finding a factor > print n, 'is a prime number' > I have another question which I hope you can answer. If I do > > 2 % 2 in the python interpreter, the answer is 0, and yet 2 is > a prime number. 2 modulo 2 is zero. Any number modulo itself is zero. If the question is why the code above reports 2 as a prime number, that's because it never gets to the "if n %x == 0" when n is 2. "for x in range(2,2)" does not execute the loop at all but goes directly to the else. I think you would find it helpful to step through this code line by line in any Python debugger such as PythonWin or IDLE--that way you can see exactly what it does as it executes. -Mike From __peter__ at web.de Mon Nov 3 08:04:48 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 Nov 2003 14:04:48 +0100 Subject: Testing validity of for...in... References: Message-ID: Richard Philips wrote: > def maxlength(mylist): > assert isinstance(mylist, list), "A list with strings" > max = -1 for item in mylist: > if len(item)>max: > max = len(item) > return max Your implementation makes two implicit tests: 1. Is mylist iterable 2. Do the items in mylist have a length There is no point in duplicating these tests. On the other hand, if you really want to accept only strings as items, you should put assert isinstance(item, basestring), "Sequence item must be a string" into the for loop. I'm not advocating that because it unnecessarily limits the generality of the algorithm. Other unrelated observations: max is a built-in function, don't use it as a variable name. -1 is not a length, if you don't want to accept empty lists/sequences, raise an exception when you encounter one, otherwise return 0. OK, the last one is only a personal preference... Peter From keflimarcusx at aol.comNOSPAM Wed Nov 5 05:07:06 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 05 Nov 2003 10:07:06 GMT Subject: Why no try-except-finally ? References: Message-ID: <20031105050706.29195.00000178@mb-m22.aol.com> >Hang on, there is something wrong with what you say here. If you really had >the code you wrote above, and you put DeInit() in the except block and >again after it then any time an exception was thrown you would call DeInit >twice. Is this *really* what you wanted? Err, no, it'd also exit with an error code in the except block (something I hadn't written in at that moment because I had already realized it wasn't going to work that way). My bad. For now I rewrote it like this, just a modified version of what you suggested: err_code = 0 try: game.Play() # was PlayGame() before except: err_msg = "FATAL ERROR: " + sys.exc_info()[0] logger.critical(err_msg) err_code = 1 DeInit() return err_code From cezary at nodomain.invalid Mon Nov 3 11:55:02 2003 From: cezary at nodomain.invalid (CezaryB) Date: Mon, 03 Nov 2003 17:55:02 +0100 Subject: Python from Wise Guy's Viewpoint In-Reply-To: References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> Message-ID: On 10/20/2003 5:49 AM, Kenny Tilton wrote: > > > Dennis Lee Bieber wrote: > >> Just check the archives for comp.lang.ada and Ariane-5. >> >> Short version: The software performed correctly, to >> specification (including the failure mode) -- ON THE ARIANE 4 FOR >> WHICH IT WAS DESIGNED. > > > Nonsense. From: http://www.sp.ph.ic.ac.uk/Cluster/report.html > > "The internal SRI software exception was caused during execution of a > data conversion from 64-bit floating point to 16-bit signed integer [...] > > >> LISP wouldn't have helped -- since the A-4 code was supposed >> to failure with values that large... And would have done the same >> thing if plugged in the A-5. (Or are you proposing that the A-4 code >> is supposed to ignore a performance requirement?) > > "supposed to" fail? chya. This was nothing more than an unhandled > exception crashing the sytem and its identical backup. Other conversions > were protected so they could handle things intelligently, this bad boy > went unguarded. Note also that the code functionality was pre-ignition > only, so there is no way they were thinking that a cool way to abort the > flight would be to leave a program exception unhandled. > > What happened (aside from an unnecessary chunk of code running > increasing risk to no good end) is that the extra power of the A5 caused > oscillations greater than those seen in the A4. Those greater > oscillations took the 64-bit float beyond what would fit in the 16-bit > int. kablam. Operand Error. This is not a system saying "whoa, out of > range, abort". "To determine the vulnerability of unprotected code, an analysis was performed on every operation which could give rise to an exception, including an Operand Error. [...] It is important to note that the decision to protect certain variables but not others was taken jointly by project partners at several contractual levels." "There is no evidence that any trajectory data were used to analyse the behaviour of the unprotected variables, and it is even more important to note that it was jointly agreed not to include the Ariane 5 trajectory data in the SRI requirements and specification." "It was the decision to cease the processor operation which finally proved fatal. Restart is not feasible since attitude is too difficult to re-calculate after a processor shutdown; therefore the Inertial Reference System becomes useless. The reason behind this drastic action lies in the culture within the Ariane programme of only addressing random hardware failures. From this point of view exception - or error - handling mechanisms are designed for a random hardware failure which can quite rationally be handled by a backup system." > As for Lisp not helping: "It has been stated to the Board that not all the conversions were protected because a maximum workload target of 80% had been set for the SRI computer" CB From djones at shcorp.com Fri Nov 7 19:36:52 2003 From: djones at shcorp.com (Dan Jones) Date: 07 Nov 2003 19:36:52 -0500 Subject: binary string question In-Reply-To: <3FAC2941.C8D1EF61@engcorp.com> References: <3FAC2941.C8D1EF61@engcorp.com> Message-ID: <1068251812.26084.34.camel@shdj> On Fri, 2003-11-07 at 18:22, Peter Hansen wrote: > Dan Jones wrote: > > > > I'm trying to figure out how to get bit operators to work on a binary > > string. This is what I'm trying to do: > > > > list(frame) #where frame is a binary string > > y = frame[x] << 8 > > You don't describe what you want this to do. How about an example, showing > input and desired output? > > > It gives me a TypeError. Whats the best way to get around that? I think > > the struct module may be what I'm looking for, if so could someone give > > me an example? Also, is there a better way to be able to access > > individual bytes than converting the string to a list? > > Yes, use an array (see the module by that name). > > On the other hand, depending on what you really want, the answer might > be as simple as taking your string and skipping the first element. > After all, shifting each byte in a long sequence to the left by 8 bits > is pretty much synonymous with that approach: > > out = in[1:] + '\x00' > > But I suspect that's not really what you meant. Please explain. > > -Peter Sorry, I should have included more information. I'm trying to write a webcam app to grab and display images off a Philips (pwc) camera in Linux. What I have so far is based on the mini-tv.py demo in the pyv4l module. It will work with RGB output such as from a tv tuner card but the Philips cameras use a different color palette. I found a C function that converts the YUV420P color palette to RGB, and I'm trying to convert it to python. The binary string in question is the image data for one frame of video. To display it, I'm using PIL's Image.fromstring() and tkinter. I don't know much C at all and am fairly new to python as well, but I'll post what I have so far. Here's the C version: static void ccvt_420p(int width, int height, const unsigned char *src, unsigned char *dst, int push) { int line, col, linewidth; int y, u, v, yy, vr, ug, vg, ub; int r, g, b; const unsigned char *py, *pu, *pv; linewidth = width >> 1; py = src; pu = py + (width * height); pv = pu + (width * height) / 4; y = *py++; yy = y << 8; u = *pu - 128; ug = 88 * u; ub = 454 * u; v = *pv - 128; vg = 183 * v; vr = 359 * v; for (line = 0; line < height; line++) { for (col = 0; col < width; col++) { r = (yy + vr) >> 8; g = (yy - ug - vg) >> 8; b = (yy + ub ) >> 8; if (r < 0) r = 0; if (r > 255) r = 255; if (g < 0) g = 0; if (g > 255) g = 255; if (b < 0) b = 0; if (b > 255) b = 255; switch(push) { case PUSH_RGB24: *dst++ = r; *dst++ = g; *dst++ = b; break; case PUSH_BGR24: *dst++ = b; *dst++ = g; *dst++ = r; break; case PUSH_RGB32: *dst++ = r; *dst++ = g; *dst++ = b; *dst++ = 0; break; case PUSH_BGR32: *dst++ = b; *dst++ = g; *dst++ = r; *dst++ = 0; break; } y = *py++; yy = y << 8; if (col & 1) { pu++; pv++; u = *pu - 128; ug = 88 * u; ub = 454 * u; v = *pv - 128; vg = 183 * v; vr = 359 * v; } } /* ..for col */ if ((line & 1) == 0) { // even line: rewind pu -= linewidth; pv -= linewidth; } } /* ..for line */ } void ccvt_420p_rgb24(int width, int height, const void *src, void *dst) { ccvt_420p(width, height, (const unsigned char *)src, (unsigned char *)dst, PUSH_RGB24); } ######################### And here's what I have so far: def yuv420p_to_rgb24(WIDTH, HEIGHT, source): line, col, linewidth = 0,0,0 y,u,v,yy,vr,ug,vg,ub = 0,0,0,0,0,0,0,0 r,g,b = 0,0,0 linewidth = WIDTH >> 1 sourceframe = list(source) py = 0 pu = py + (WIDTH * HEIGHT) pv = pu + (WIDTH * HEIGHT) / 4 destination = [] destindex = 0 y = sourceframe[py] py += 1 int(y) yy = y << 8 # This is where it blows up u = sourceframe[pu] - 128 ug = 88 * u ub = 454 * u v = sourceframe[pv] - 128 vg = 183 * v vr = 359 * v line = 0 while (line < HEIGHT): col = 0 while (col < WIDTH): r = (yy + vr) >> 8 g = (yy - ug - vg) >> 8 b = (yy + ub ) >> 8 if (r < 0): r = 0 if (r > 255): r = 255 if (g < 0): g = 0 if (g > 255): g = 255 if (b < 0): b = 0 if (b > 255): b = 255 destination[destindex] = r destindex += 1 destination[destindex] = g destindex += 1 destination[destindex] = b destindex += 1 y = sourceframe[py] py += 1 yy = y << 8 if (col & 1): pu += 1 pv += 1 u = sourceframe[pu] - 128 ug = 88 * u ub = 454 * u v = sourceframe[pv] - 128 vg = 183 * v vr = 359 * v col += 1 #end while col if ((line % 1) == 0): # even line: rewind pu -= linewidth pv -= linewidth line += 1 #end while line return destination From cbm64 at inwind.it Mon Nov 24 15:46:14 2003 From: cbm64 at inwind.it (Luca Montecchiani) Date: Mon, 24 Nov 2003 20:46:14 GMT Subject: string similarity in python In-Reply-To: References: Message-ID: <3FC26E14.9080401@inwind.it> Peter Otten wrote: : > Remembering an algorithm called Levenshtein, google came up with something > that looks promising. > > http://trific.ath.cx/resources/python/levenshtein/ : Other resources : o http://www-users.cs.umn.edu/~ialbert/python/apse/ o http://datamining.anu.edu.au/projects/linkage.html ( stringcmp.py encode.py modules ) o http://spazioinwind.libero.it/montecchiani/pyfdupes-0.7.tgz o http://www.bio.cam.ac.uk/~mw263/pyagrep.html ciao, luca From davidb at mcs.st-and.ac.uk Wed Nov 12 19:57:47 2003 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 12 Nov 2003 16:57:47 -0800 Subject: Structured Text or ReStructured Text Viewer References: Message-ID: <4de76ee2.0311121657.d0ca493@posting.google.com> Dinu Gherman wrote in message news:... > Hoang: > > > yes, I ran across that in my search and was very unhappy that it > > was only for the Mac. I wonder if the tool was written in Python. > > Sure it is! As it comes with full source code you can take it and > port it to something else, if you want. Here is another teasing > candidate: http://python.net/~gherman/RegexPlor.html ;-) It's not > unlikely, though, that these might work soon on GNUstep, too... For those using KDE, particularly with PyKDE, there's another option (long URL alert): http://dot.kde.org/1068148183/1068169673/1068181339/1068244361/1068260975/ I keep generating snapshots of the component mentioned in the referenced discussion. However, it was only recently that I got round to wrapping David Goodger's HTML writer for ReST to produce a ludicrously small plugin module for my Wiki KPart. http://www.boddie.org.uk/david/Projects/Python/KDE/ Some issues remain with its integration into Konqueror but, hopefully, these will be ironed out over time. David From dave at pythonapocrypha.com Fri Nov 14 15:40:36 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 14 Nov 2003 13:40:36 -0700 Subject: python STL? References: <0latb.95267$ri.14418352@twister.nyc.rr.com> Message-ID: <138201c3aaef$8f1835a0$891e140a@YODA> > being recently introduced to the joys of programming in a powerful > dynamic language (go snake!) I periodically rethink which parts of C++ I > still miss. One thing I really enjoy is the generics of C++ - i think > they are the single strong benefit of a strongly typed system. I was > wondering about the possibility of implementing STL-like algorithms in > Python and the one thing that I cannot think of doing without a kludge > is the object comparsion that so much of STL relies on, which in turn > relies on types and function(<) overloading. Is there a way to implement > something similar in python (short of multimethods?). How does the > python dictionary object allow arbitrary key types? Is in internally > using the references' addresses to impose the tree ordering? > thanks, > max. Hi Max, Could you give a more specific example of what you miss? -Dave From pje at telecommunity.com Fri Nov 28 16:17:36 2003 From: pje at telecommunity.com (Phillip J. Eby) Date: Fri, 28 Nov 2003 16:17:36 -0500 Subject: PyProtocols 0.9.1 Released Message-ID: <5.1.0.14.0.20031128160119.028e9dc0@mail.telecommunity.com> What is PyProtocols? -------------------- PyProtocols is an extended implementation of PEP 246, adding a new "declaration API" that lets you easily define your own interfaces and adapters, and declare what adapters should be used to adapt what types, objects, or interfaces. Using PyProtocols, you can easily make flexible frameworks that you or other developers can extend without needing to modify the base framework. PyProtocols interfaces can interoperate with those of Twisted and Zope, or can be used entirely standalone. PyProtocols may be used, modified, and distributed under the same terms and conditions as Python or Zope. What's new in version 0.9.1? ---------------------------- * Implemented Samuele Pedroni's "subproto" idea (see http://mail.python.org/pipermail/python-dev/2003-June/036242.html) as the new 'protocolForType()' API. * Added other APIs to automatically generate protocols, such as 'protocolForURI()', 'sequenceOf()', and 'Variation()'. * Compatible with Zope X3 Milestone 4, Python 2.3.2, and Twisted 1.1.0. (Also runs on Python 2.2.2+, if you don't need Zope 3 compatibility.) * New 'Adapter' and 'StickyAdapter' convenience base classes * Fixes for compatibility with 'ExtensionClass', and for a memory leak in the optional C "speedups" module PyProtocols Resources --------------------- * Detailed Changes since the 0.9 release: http://peak.telecommunity.com/protocol_api/CHANGES.txt.html * Release notes, installation instructions, and browsable API docs: http://peak.telecommunity.com/protocol_api/ * Source and Binary Releases: http://peak.telecommunity.com/dist/ * Reference Manual (HTML): http://peak.telecommunity.com/protocol_ref/module-protocols.html * Reference Manual (PDF): http://peak.telecommunity.com/protocol_ref.pdf * Browsable CVS Repository: http://cvs.eby-sarna.com/PyProtocols/ From bokr at oz.net Sun Nov 9 22:32:30 2003 From: bokr at oz.net (Bengt Richter) Date: 10 Nov 2003 03:32:30 GMT Subject: prePEP: Decimal data type References: <3faee2f8$1_1@news.bluewin.ch> Message-ID: On Mon, 10 Nov 2003 01:56:54 +0100, "Samuel Kilchenmann" wrote: >"Bengt Richter" schrieb im Newsbeitrag >news:bojrg5$vim$0 at 216.39.172.122... >> >> Following is an exact decimal/rational module hack that >> implements rounding when the .round() method is called. >> This is not too elegant, but it might make >> an interesting toy to cross-check results with. > >Thanks a lot for this interesting toy! You're welcome ;-) > >some results seem a little bit strange to me, eg.: > >Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on >win32 >Type "help", "copyright", "credits" or "license" for more information. >>>> from exactdec import ED >>>> ED('0.95',1) >ED('9..0') >>>> ED('0.995',2) >ED('99..0') >>>> ED('0.9995',3) >ED('99.9.0') >>>> ED('0.99995',4) >ED('99.99.0') >>>> ED('0.999995',5) >ED('99.999.0') >>>> ED('0.9999995',6) >ED('1.0') >>>> Gak. Yes, I had seen that weirdness before, and thought I fixed it, but not all of it ;-/ > >its probably due to the line: > ret.num //= (ret.den*10**psh) >in your rounding code and the fact that: >>>> 1 // 0.1 >9.0 >>>> 10 // 0.01 >999.0 >>>> 100 // 0.001 >99999.0 >>>> 1000 // 0.0001 >9999999.0 >>>> 10000 // 0.00001 >999999999.0 >>>> 100000 // 0.000001 >100000000000.0 > Thanks, you are are right. That line (and the companion exponent adjustment) should not be executed unless psh>0. If psh<=0 then there are no less significant digits to get rid of with the //. I hope this is a fix, no time for extensive test (I have to disappear for a few days): --- exactdec.r1.py Sat Nov 08 14:12:29 2003 +++ exactdec.r1a.py Sun Nov 09 19:18:21 2003 @@ -2,6 +2,7 @@ # 20031107 14:54:21 alpha -- bokr # 20031108 09:42:18 added contruction from float with all info or specified rounding -- bokr # 20031108 13:58:10 added more docs and interactive calculator thing -- bokr +# 20031109 19:14:10 fix to round method -- thanks to Samuel Kilchenmann for bug report -- bokr # # WARNING: Not signigicantly tested. Not optimized. No warranty. Use at your own risk. And, # if you run this program interactively, it passes your raw_input to eval unvalidated! @@ -219,9 +220,10 @@ ret.num = abs(ret.num) ret = ret + type(self)((5,1,-ndec-1)) psh = -(ret.p10+ndec) - ret.num //= (ret.den*10**psh) + if psh>0: + ret.num //= (ret.den*10**psh) + ret.p10 += psh ret.den = 1 - ret.p10 += psh if sign: ret.num = -ret.num ret.normalize() return ret Regards, Bengt Richter From ville.spammehardvainio at spamtut.fi Sun Nov 23 04:06:06 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 23 Nov 2003 11:06:06 +0200 Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> <7xwu9svyny.fsf@ruckus.brouhaha.com> <7xvfpcowjt.fsf@ruckus.brouhaha.com> <653b7547.0311222346.b4d9e98@posting.google.com> Message-ID: pmaupin at speakeasy.net (Patrick Maupin) writes: > restrictive). So it would appear that the FSF has no real legal > ability under the GPL to keep someone from writing and distributing > a package which uses readline, as long as that person does not > simultaneously distribute readline itself. In the light of this, does releasing a library under GPL (as opposed to LGPL) make any sense at all? -- Ville Vainio http://www.students.tut.fi/~vainio24 From bgudorf at neurokode.com Tue Nov 18 13:23:26 2003 From: bgudorf at neurokode.com (Bryan J Gudorf) Date: Tue, 18 Nov 2003 13:23:26 -0500 Subject: recommendations for python web programming tools In-Reply-To: Message-ID: Matthew, For the database connections, you could check out PDO (Python Database Objects). It uses DB-API 2.0 based modules to interface with the database with simple syntax. It also helps in that if you ever need to change the backend database to something other than MySQL. Of course to set up the Database Connections to MySQL, you will need to the module for MySQL: http://sourceforge.net/projects/mysql-python Bryan J Gudorf ~NeuroKode Labs, LLC -----Original Message----- From: Matthew Wilson [mailto:mwilson at sarcastic-horse.com] Sent: Tuesday, November 18, 2003 10:54 AM To: python-list at python.org Subject: recommendations for python web programming tools I am about to start designing a web application for my office intranet. It is pretty simple: we need a way to track conversations with contacts and a way to update contact information. I could do it all in PHP or perl-mason, but I really like python's syntax and I have the time to learn something new. I've never used any of the web stuff for python. I need something that is easy and quick to learn. I need support for connection to MySQL, simple user authentication based on passwords, and either a templating system, or the ability to embed python code in html, like PHP. I already have Apache installed and running on a Red Hat linux box. I don't need the most high-performance system. We have 8 users at the most that will be logging in simultaneously. All recommendations are welcome. From gmuller at worldonline.nl Tue Nov 4 14:56:30 2003 From: gmuller at worldonline.nl (GerritM) Date: Tue, 4 Nov 2003 20:56:30 +0100 Subject: ActivePython or Python2.2.3+win32? References: <9i0bqvs4ir5963iiiv5bpukejvirga6gm1@4ax.com><87ekwq74y0.fsf@pobox.com> Message-ID: <3fa8045e$0$79334$5fc3050@dreader2.news.tiscali.nl> "Trent Mick" schreef in bericht news:mailman.424.1067966695.702.python-list at python.org... > [James Kew wrote] > > ActivePython 2.3.2 seems to have quietly dropped any mention of the PPM > > package system. Is it no longer supported? > > This change was mention on the ActivePython-specific mailing list: > http://listserv.activestate.com/mailman/listinfo/ActivePython > http://aspn.activestate.com/ASPN/Mail/Message/ActivePython/1872769 > <...snip...> > Trent Mick Thank you, this is a message with valuable information, worthwile to be published in comp.python.announce I have sympathy for your reasoning, hopefully the feedback of the Python community at large can help even more. kind regards, Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From stephan.diehlNOSPAM at gmx.net Mon Nov 24 13:35:51 2003 From: stephan.diehlNOSPAM at gmx.net (Stephan Diehl) Date: Mon, 24 Nov 2003 19:35:51 +0100 Subject: Bug or Feature? References: <2259b0e2.0311240603.549943b3@posting.google.com> <9cf48f3e1bcf524ab4ad581a061d1852@news.teranews.com> Message-ID: Dang Griffith wrote: > On Mon, 24 Nov 2003 18:13:34 +0100, Stephan Diehl > wrote: > > ... >>This is probably more a theoretical question, but if I decide to have an >>operation within one specific domain, I want the result in that domain >>too. Otherwise, there would be no point at all to define such a numeric >>class at all. >> >>Stephan > > I understand what you're saying, but there's no universal rule that > says that the result of operations between members of a set are also > members of the set. Obvious examples include division on the set of > integers, and division over the set of real numbers, i.e.division by > zero is not a real number. > --dang If we have a look at the mathematical definition of numbers, the interesting thing is not the set of these numbers, but the set combined with some usefull operators (like addition and multiplication). It is (mathematicaly speaking) not possible to have a result under these operations that are outside the definition. In that sense, there IS this universal rule, you were talking about. (and division by zero is just not allowed by definition). Stephan From SBrunning at trisystems.co.uk Mon Nov 17 10:57:21 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Mon, 17 Nov 2003 15:57:21 -0000 Subject: line number var like perl's $.? Message-ID: <31575A892FF6D1118F5800600846864D01200CEA@intrepid> > From: Matthew Wilson [SMTP:mwilson at sarcastic-horse.com] > Is there an equivalent construct in python? Or are people doing > something like this: > > linenum = 0 > for line in open('blah.txt'): > linenum += 1 > print linenum, ". ", line > for linenum, line in enumerate(file('blah.txt')): print linenum, line You'll need Python 2.3 for this, mind. Cheers, Simon Brunning, http://www.brunningonline.net/simon/blog/ --LongSig ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From fumanchu at amor.org Thu Nov 20 16:29:49 2003 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 20 Nov 2003 13:29:49 -0800 Subject: How do you pass a standard operator such as '<' as a parameter? Message-ID: Don't forget the 'operators' module: http://www.python.org/doc/current/lib/module-operator.html FuManChu > -----Original Message----- > From: Peter Milliken [mailto:peterm at resmed.com.au] > Sent: Thursday, November 20, 2003 1:22 PM > To: python-list at python.org > Subject: Re: How do you pass a standard operator such as '<' > as a parameter? > > > Wrote too soon - the obvious answer is not to use a > "comparison" function at > all when instantiating the class but rather to just code the > "<" in the > class "add" procedure and then make sure the data type that > is being used > contains a __lt__ operator :-) i.e. the class definition > should just be: > > class OrderedList (list): > def add (self, element): > """Add the element into the list in the correct > ordered sequence > for > the data type. > """ > # Locate the position in the list and perform the > insertion > for i in list(self): > if element < i: > list.insert(self, list.index(self, i), element) > break > else: > # element is greater than any current value in > the list, so > stick > # it at the end. > list.append(self, element) > > This will work for integers as well as user defined data > types that have a > __lt__ function defined. > > > > "Peter Milliken" wrote in message > news:z7avb.541$WD1.13194 at nnrp1.ozemail.com.au... > > I am creating a subclass of list that will allow 'ordered' > lists via the > > addition of a new method ('add' for want of a better name > :-)). Since I > want > > to make it as generic as possible, I want to pass the > comparator function > as > > an argument at initialisation. It would be used line this: > > > > y = OrderedList([], LessThanFunction) > > > > y.add(9) > > y.add(8) > > y.add(11) > > > > y > > > > [8,9,11] > > > > > > > > So the class definition would look like this: > > > > class OrderedList (list): > > def __init__ (self, comparator): > > list.__init__(self) > > self.ComparisonFunction = comparator > > > > def add (self, element): > > """Add the element into the list in the correct ordered > sequence > > for > > the data type. > > """ > > # Locate the position in the list and perform > the insertion > > for i in list(self): > > if self.ComparisonFunction(element, i): > > list.insert(self, list.index(self, i), element) > > break > > else: > > # element is greater than any current value > in the list, so > > stick > > # it at the end. > > list.append(self, element) > > > > > > For non-standard data types, you would obviously define a > '<' function and > > then pass it as a parameter at initialisation, but how can > you pass one of > > the standard operators? i.e. '<'. > > > > For instance, to create an ordered list of integers, I would like to > > instantiate new objects using something like this: > > > > y = OrderedList([], <) > > > > However, this results in a syntax error. Is there anyway to > pass the '<' > > operator itself? I fully realise that you could create a "lessthan" > > function, either explicitly or as a lamdba, but my > curiousity bump is > > itching and I would like to know how to pass one of the standard > operators. > > > > Thanks > > Peter > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From __peter__ at web.de Sun Nov 30 05:45:14 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 30 Nov 2003 11:45:14 +0100 Subject: Fast attribute/list item extraction Message-ID: There is currently a discussion on python-dev about an extract() function which offers fast access to list items and object attributes. It could serve, e. g., as the key argument of the future list.sort() method: extract("attr") # extract an attribute extract(1) # extract a list item Below is a slight variation of this idea, together with a pure-python implementation. As a "real" C version is currently beyond me, I chose not to post it on python-dev. Following variants are possible: # extract an attribute extract.attr extract(name="attr") # necessary when attribute name only known at runtime # extract a list item or slice extract[1] extract[:] extract(index=1) # for symmetry only # extract a dictionary value extract["key"] extract(key="key") # for symmetry only # the gory details class GetItem(object): def __init__(self, index): self.index = index def __call__(self, item): return item[self.index] class GetAttr(object): def __init__(self, name): self.name = name def __call__(self, obj): return getattr(obj, self.name) class Extract(object): def __getitem__(self, key): return GetItem(key) def __getattribute__(self, name): return GetAttr(name) def __call__(self, name=None, key=None, index=None): assert sum([name is None, key is None, index is None]) == 2, ( "Please provide only one of these arguments: name, key, index") if name is not None: return GetAttr(name) if key is not None: return GetItem(key) return GetItem(index) extract = Extract() # usage demonstration class Demo: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "(x=%s, y=%s)" % (self.x, self.y) __repr__ = __str__ indexSample = [(1, 10), (2, 20), (3, 30)] keySample = [{"x": x, "y": y} for x, y in indexSample] attrSample = [Demo(*xy) for xy in indexSample] print "Index", indexSample print "Key", keySample print "Attribute", attrSample def printSeq(seq, extractor): for item in seq: print extractor(item), print printSeq(indexSample, extract[0]) printSeq(indexSample, extract(index=1)) printSeq(indexSample, extract[:]) printSeq(attrSample, extract.x) printSeq(attrSample, extract(name="y")) printSeq(keySample, extract["x"]) printSeq(keySample, extract(key="y")) Comments welcome :-) Peter From tchur at optushome.com.au Sun Nov 9 14:26:13 2003 From: tchur at optushome.com.au (Tim Churches) Date: 10 Nov 2003 06:26:13 +1100 Subject: Status of JPE (Java-Python Extension)? In-Reply-To: <87fzgxfpv3.fsf@pobox.com> References: <87fzgxfpv3.fsf@pobox.com> Message-ID: <1068405973.1203.11.camel@emilio> On Mon, 2003-11-10 at 03:50, John J. Lee wrote: > Tim Churches writes: > [...] > > d) Are there any alternatives for making calls on Java objects from > > CPython, or vice-versa? Or is Corba or similar the best approach? > > Pyro. Never used it, though. PyRO is great (have used it), but strictly Python to Python. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From http Wed Nov 19 14:16:35 2003 From: http (Paul Rubin) Date: 19 Nov 2003 11:16:35 -0800 Subject: deprecation gotchas Re: rotor alternative? References: <9a6d7d9d.0311191026.44da2b19@posting.google.com> Message-ID: <7xn0asw4mk.fsf@ruckus.brouhaha.com> aaron at reportlab.com (Aaron Watters) writes: > repr(string) went hex and broke a lot of stuff for interacting > with systems that matched the old octal representation > (pdf format for example). It's very hard to ferret out all > the places where someone assumed that chr(0)=="\000". repr really shouldn't be used that way though. From aleax at aleax.it Fri Nov 14 10:53:12 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Nov 2003 15:53:12 GMT Subject: Too much builtins (was Re: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <653b7547.0311121826.65b6b2d4@posting.google.com> Message-ID: Ville Vainio wrote: ... > I also think that reduce, sum, map and filter (and lots of others, > __builtins__ has *too much stuff*) should be removed from builtins, > but that will probably take some time (1997 years?). LC's and genexpes > will take care of most of that stuff. And people can always do: There are no way in which LC's and genexp can "take care of" CONSUMING iterables and iterators -- they PRODUCE them (and itertools also do some production, and, mostly, composable transformation). map and filter, sure; sum, reduce, min, max, can never be replaced by any LC nor any genexp. I think we need a separate module for _consumers_ of iterables/iterators, and I have repeatedly posted about it. But, sure, I'd gladly agree that there's no real call for any of these to be a built-in. > from funtional import * > # map, filter, reduce, curry, ... (I want lots of these :) I'd rather put map/filter/reduce in a 'legacy' module -- warts and all, e.g. map's horrible habit of None-padding shorter sequences, EEK -- and have a designed-from-scratch functional module without the warts. What about starting one as a sourceforge project, as I mentioned elsewhere? > There are also tons of functions that should be in sys, math or > whatever: > > reload, repr, divmod, max, min, hash, id, compile, hex... Probably, yes. What functions, as opposed to types, do you think should absolutely be in the builtins rather than in a separate module, and (unless it's obvious) why? Of course __import__ had better stay or we won't be able to get anything imported, for example:-). The attribute-related functions hasattr, getattr, setattr, and delattr, seem very fundamental (but I'd want the same status for the item-functions currently over in operator), as well as (at least some of them -- delattr isn't -- but I do think that trying to discriminate too finely would make things too hard to learn) very frequently used in code. What else? iter, len, pow [for the crucial 3-arguments case], range (or some preferable variant that returns an iterator), and zip seem pretty fundamental; chr and ord might be suitable as str methods (in the case of chr, a staticmethod, no doubt). Many functions that are quite handy for interactive use, such as locals, globals, dir, vars, ..., are not all that frequently used in programs -- so they might live in a module that the interactive mode gets automatically, rather than being built-ins. Having beginners learn 'import' before they do raw_input (or output, which should also be a function, not a statement) may not agree with somebody's didactics, so, we should consider how to deal with those. All of this would be perfect for the mailing list on Python 3.0 if the latter existed. Posting it to c.l.py makes it unlikely Guido will ever consider the discussion's resuts, anyway. The problem is that, with 3.0 at least 2 years away, there seems to be little incentive to actually go and make such a list, so that its archives may come in handy in the future. > What's your pet deprecation candidate? I have always thought > `backticks` as repr has got to be the most useless feature around. Pretty bad, yes. 'apply' at least, while useless, doesn't make Python's syntax any more complicated, while `...` does. Alex From raven at phoenyx.net Wed Nov 19 18:06:05 2003 From: raven at phoenyx.net (Carl D Cravens) Date: Wed, 19 Nov 2003 17:06:05 -0600 Subject: syntax philosophy In-Reply-To: References: Message-ID: I just started learning Python over the weekend, and I have to say that it was very frustrating at first. This thread came at just the right time, and it's been very enlightening. Understanding Python's approach has helped me accept and appreciate why it does things the way it does. I was originally a C advocate, lured to Perl by the rapid development... I'm a Unix sysadmin and Perl was perfect for me. But as I look at doing larger projects, I find Perl's modules, scoping and OO to be esoteric. Python looks like just the ticket. Thanks to everyone who contributed. -- Carl D Cravens (raven at phoenyx.net) I'm not lost, I'm "locationally challenged". From op73418 at mail.telepac.pt Mon Nov 3 07:35:41 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Mon, 03 Nov 2003 12:35:41 +0000 Subject: Testing validity of for...in... References: Message-ID: On Mon, 03 Nov 2003 12:53:18 +0100, Richard Philips wrote: >Hi, > > From the "The Pragmatic Programmer / Dave Thomas, Andy Hunt", >I acquired the habit to insert assertions in function declarations: > >def maxlength(mylist): > assert isinstance(mylist, list), "A list with strings" > max = -1 > for item in list: > if len(item)>max: > max = len(item) > return max > > >But if you look at the code, maxlength is meaningful if mylist supports >the "for ... in ...". > The following should work: try: it = iter(mylist) except TypeError: raise TypeError("Object not iterable.", mylist) Except I'm wondering what you would be gaining, besides the marginally better error description, by putting this check in. TypeError will be raised anyway by the time you get to the for loop, so, IMHO, it's just better to document your function: def maxlength(mylist): """... Warning(s): - Raises TypeError if argument is not iterable. """ max = -1 for item in list: if len(item)>max: max = len(item) return max With my best regards, G. Rodrigues From andrew-pythonlist at puzzling.org Mon Nov 24 19:24:41 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 25 Nov 2003 11:24:41 +1100 Subject: 'from __future__ import ...' overview In-Reply-To: References: Message-ID: <20031125002441.GB4466@frobozz> On Tue, Nov 25, 2003 at 01:09:09AM +0100, Logan wrote: > Is there a list with all 'from __future__ import ...' statements > (which lists all the statements, in which version of Python the > feature was introduced and in which version of Python it will become > the default behavior)? Yes -- __future__.py in the python standard library. -Andrew. From bushbo at attbi.com Fri Nov 14 16:53:35 2003 From: bushbo at attbi.com (Brian O. Bush) Date: 14 Nov 2003 13:53:35 -0800 Subject: Gadfly DB in python standard library? Message-ID: <3fe406f0.0311141353.3aec780f@posting.google.com> A while ago, I recall hearing that Gadfly might be included into the python standard library. What happened? As I recall, the issue was the license. Brian From miika.keskinen at utu.fi Wed Nov 5 09:20:43 2003 From: miika.keskinen at utu.fi (Miika Keskinen) Date: Wed, 05 Nov 2003 16:20:43 +0200 Subject: Template-engine Message-ID: Hi all I was in need for a simple template engine (like PEAR::IT.php) and didn't find any suitable. Yes, there is many templating engines available but most are far too complex or does implement some additional features in their syntax. So I created following and I'm asking comments - and yes I know there is couple not so pythonistic sides in code. Most of all accessing inner dict B straight. This is however first working version (started it hour ago) and I'm asking if any of you have something in mind that could help me making that better. This engine is non only for html ( in fact I don't use it for html but email-templates and some configuration-templates ). the beast can be found from http://users.utu.fi/mikrke/index.html (includes example how to use it) -- Miika From jzgoda at gazeta.usun.pl Wed Nov 19 16:06:30 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 19 Nov 2003 21:06:30 +0000 (UTC) Subject: PyQt, Qt, Windows and Linux References: Message-ID: email9898989 at yahoo.com pisze: >> Qt for Linux is GPL'd, so nothing prevents you from selling your >> software for Linux - you do have to provide source code though >> and can't charge for Qt/PyQt/etc. > > Sorry I wasn't crystal clear. If you plan to develop commercial > software on any platform, you have to pay for Qt. I was trying to > make their pricing schemes more easy for people to understand. Don't spread FUD. You don't have to pay for Qt if you distribute it under GNU Public License. Even commercially. You can earn money for your software and you have nothing to pay to Trolltech if this is GPL-ed software. They can say anything, but it's GPL, they just can not impose such restriction. I think somebody at FSF should take closer look at statements that can be found on Trolltech website -- they are misleading at least. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From mikit at zoran.co.il Sun Nov 23 05:13:51 2003 From: mikit at zoran.co.il (Miki Tebeka) Date: 23 Nov 2003 02:13:51 -0800 Subject: Help with script with performance problems References: Message-ID: <6250403b.0311230213.124d969@posting.google.com> Hello Dennis, A general note: Use the "hotshot" module to find where you spend most of your time. > splitline = string.split(line) My guess is that if you'll use the "re" module things will be much faster. import re ws_split = re.compile("\s+").split ... splitline = split(line) ... HTH. Miki From mis6 at pitt.edu Thu Nov 13 13:57:40 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 13 Nov 2003 10:57:40 -0800 Subject: case-sensitivity (was Re: True, False, None) References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <2259b0e2.0311122135.62359cc0@posting.google.com> <3gNsb.20789$hV.759234@news2.tin.it> Message-ID: <2259b0e2.0311131057.2479dc9e@posting.google.com> Alex Martelli wrote in message news:<3gNsb.20789$hV.759234 at news2.tin.it>... > Michele Simionato wrote: > > > Alex Martelli wrote in message > > news:... > >> So, when I used to have a factory function (as 'int' was), and change > >> it into a type (or class, same thing), I should rename it and break all > ... > > But these are very rare cases, so probably I could live with an > > enforced capitalization too. > > You think it's rare, during refactoring, to change between types and > factory functions?! I suspect you may not have been maintaining and > enhancing code (in languages allowing interchange of the two things) > for long enough. Consider that *ALL* types in Python's builtins started > life as factory functions -- that's 100%... "very rare"?!-) It is very rare in my own code, but I haven't maintained code written by others, so I will accept your experience on this. > >> remember that module FCNTL has an all-uppercase name, htmllib all-lower, > >> cStringIO weirdly mixed, mimetypes lower, MimeWriter mixed, etc, etc -- > >> totally wasted mnemonic effort. > > > > This is more a problem of inconsistent conventions. It is true that > > it will disappear with case insensitivity enforced, but somewhat I > > [[ probably mean "case sensivity enforced" ? ]] No, this time I really meant case *insensitivity*: if case insensitivity was enforced, the issue with FCNTL,cStringIO, MimeWriter, etc. etc. would disappear and a normal memory would be enough to grasp everything. > How am I "exaggerating" in claiming that the SAME module, zipfile, > spells "zipfile" differently in the module name itself, in class > zipfile.ZipFile, and in class zipfile.BadZipfile? Maybe you have a > photographic memory so that having seen each of these ONCE you are > never going to forget which ones uppercase exactly which letters, but > even back when my memory was outstanding (when I was younger) it was > always more "auditory" than "visual": I could easily recite by heart > long quotes from books I had read once, but never could recall the > details of punctuation (or capitalization, when non-systematic, as > it often was e.g. in 17th/18th century english) without painstaking > and painful explicit memorization effort. No, I don't have a photographics memory and sometimes (few times, actually) I don't remember the right capitalization, but few seconds with the on-line help (trying zipfile or ZipFile or BadZipfile, for instance) are usually enough to solve the issue. So, as I said, capitalization does not give big headaches to me. Also, I am absolutely unconvinced that capitalization gives big headaches to you (except as a point of principle, of course). I am not saying case sensitivity is perfect, I am saying its disadvantages (in real life) are not so serious as you claim. People has written tons of C, but I am sure capitalization bugs are scarcely relevant as compared, for instance, to pointer arithmetic bugs ;) > Should a language cater mostly to the "crowd" (?) of people with > photographic memories, or shouldn't it rather help the productivity > of people whose memories aren't _quite_ that good and/or visual...? I don't have an auditive memory, nor a visual memory, but still I manage to survive with case sensitivity, so I guess everybody can do the same ... > > You are still exaggerating. 99% of times uppercase constants denote > > numbers or strings. I don't remember having ever seen an all uppercase > > function, even if I am sure you do ;) > > Maybe my defect is knowing the Python standard library too well? It's > got SEVERAL all-uppercase functions, Michele! Check out modules > difflib (functions IS_LINE_JUNK and IS_CHARACTER_JUNK), gzip > (functions U32 and LOWU32), stat (all the S_IMODE etc functions), > token (functions ISTERMINAL and ISNONTERMINAL)...! Ubi major, minor cessat ;) I confess I never used these functions: not only their capitalization is new to me, but even their names! Still, I am sure that knowing the names I will be able to remember the capitalization: 100% of times for all caps identifiers, 80% of times for camel case identifiers. I do think this is an average performance. > Maybe the sum total IS 1% or so of the functions in the library, but > that's _STILL_ a silly, arbitrary memorization chore which I shouldn't > have had to undergo in the first place -- and I'm not even sure I > have in fact remembered all of them... Even if you enforce case insensitivity, the library will still have inconsistencies due to different code conventions: think to the use of underscores to separate names, for instance. The standard library index gives plenty of cases, i.e. "add_something" versus "addsomething" etc. > > > For instance, I can define a matrix type, overload "*" and write the > > multiplication of a matrix "A" times a vector "a" as > > > > b=A*a > > > > Much more readable to me, that something like > > Please note that here you are suddenly and undocumentedly _switching > conventions on the fly_ regarding capitalization. One moment ago, > leading cap had to mean "type" and all caps had to mean "numeric > constant" (which in turn made a single-caracter capital identifier > ambiguous already...) -- now suddenly neither of these conventions > exists any more, since that uppercase A means 'matrix' instead of > 'vector' (and a _number_, i.e. even lower dimensionality, would be > indicated *HOW*? Don't you EVER multiply your matrices by scalars?! > Or is it so crucial to distinguish matrices from vectors but totally > irrelevant to distinguish either from scalars?!). That's rethoric and you know that. As I already said, readability is more important than foolish consistency; also in the context a matrix computations, how big is the possibility to misunderstand the meaning of variables such as A=Matrix(2,2); b=vector(2); s=scalar() ?? > My opinion is that, while _habit_ in mathematical formulas may surely > make one hanker for such case-sensitivity, the preference just does not > stand up to critical analysis, as above. You're trying to overload WAY > too many different and conflicting "conventions" onto a meager "one bit > [at most] per character" (about 0.87 bits I believe, in fact) of > "supplementary information" yielded by case-sensitivity. I strongly like operator overloading because of my mathematical background. Mathematicians overloads the meaning of operators all the time and never get confused, since the context is always made well clear. Nevertheless, many programmers are against operator overloading, because it can be abused. In my opinion the advantage is worth the risk (the same for case sensitivity) but I do accept that other may disagree. Insisting too much, we risk to enter in a religious discussion, so it is better to stop here. > > Most paladins of case sensitivity would probably be horrified to see > that the main point in its "favour" now appears to be that it > encourages you to use shorter (e.g. 1-letter) identifiers (and thus > more cryptic ones) because it gives you more of them to choose from...!!! In mathematical formulas, at least, shorter identifiers are clearer, not more cryptic; also, it is nice to import modules with syntaxes such as ``import math as m``, using a single letter, which does not clash with some other ``M`` (for instance the mass of an object in a Physics program, or a pluggable metaclass in an object oriented program, or anything else). > > I've tried (e.g. in Dylan) the concept of having punctuation freely > embeddable in identifiers and didn't particularly like it (I guess it > works better with a NON-infix-syntax language -- I don't recall it > feeling like a problem in either Forth or Scheme -- but in Dylan the > inability of writing a sum as > a+b > because that's an identifier, so you have to write > a + b > instead, _was_ rather uncomfortable to me [maybe I just didn't get > long-enough practice and experience with it]). I am against too much punctuation, that's one of the reason why I do like case insensitivity, so you don't need extra identifiers: did you miss my point or I am misreading you? > I disagree -- once you have to spell out e.g. pi, capital-sigma, etc, > in Ascii letters anyway, having to make sure you do so in letters that > are unambiguous in terms of capitalization differences is no big loss. > Personally, in terms of formulas, I've never found Fortran any less > readable than C, for example. I don't like Fortran verbosity, but others could agree with you. That's just a matter of personal preference. > And no, I definitely don't want Unicode characters in identifiers -- > that would ensure a LOT of new and diverse errors as people use the > wrong "decoration" (accent, circumflex, etc, etc) on letters. Plain > ascii's just great...!-) > Who wants Unicode characters ?? I am not so foolish yet !! > Alex Michele From gerrit at nl.linux.org Tue Nov 18 13:15:23 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 18 Nov 2003 19:15:23 +0100 Subject: good ways to convert string into time In-Reply-To: <731fc603.0311180958.32135957@posting.google.com> References: <731fc603.0311180958.32135957@posting.google.com> Message-ID: <20031118181523.GA8339@nl.linux.org> > i have a string as follows > > 18Nov2003:18:23:43:405 > Is there an easy way to convert that to absolute time? What i really > want to do is to parse these times from a log file and do time > comparisons, averages, stop minus start (elapsed). > > Probably create my own conversion table i guess? You can use time.strptime: strptime(string, format) -> struct_time Parse a string to a time tuple according to a format specification. See the library reference manual for formatting codes (same as strftime()). Gerrit. -- Mozilla _is_ the web: it grows faster than you can download it. 1011001 1101111 1110101 1110010 1110011 0101100 1000111 1100101 1110010 1110010 1101001 1110100 From jbublitzno at spamnwinternet.com Sat Nov 8 12:16:32 2003 From: jbublitzno at spamnwinternet.com (Jim Bublitz) Date: Sat, 08 Nov 2003 17:16:32 GMT Subject: ANN: PyKDE now does KDE plugins References: <87sml01hgc.fsf@pobox.com> <87llqrgiva.fsf@pobox.com> Message-ID: <9y9rb.3612$xr.997430341@twister2.starband.net> John J. Lee wrote: > Not if a (C++) interface is *added*, not replaced. The KDE > plugin loader could check for init_blah first, and if that's > not there, check for plain old init. There sre several different loading schemes. I've always taken the approach that PyKDE and related stuff shouldn't require any modifications to KDE (although I did file one feature request before we figured out how to load panel applets reliably). Considering any scripting language can use the same approach and there are other bindings in various stages of development, it would probably be a good idea to bring this up with KDE eventually. I'd prefer to have more running code before doing that. > Well, it might be if there were any sip documentation :-) I had > some > success using sip before, but it was hard work. I noticed that > Phil promised docs for PyQt/sip 4, though! Yeah - I promised Phil I'd write a sip tutorial too. Notice there aren't any links :( Actually I have a tutorial about half done, but sip 4.0 is in pre-release with lots of improvements (less handwritten code), so I'm waiting for that to be completed. There are some links to docs at tiverbankcomputing.co.uk too. I also have a tool in development that generates sip files automatically from h files (it's how PyKDE is generated) - it's probably about 6 months (or more) away from release. The code generation works well, but the doc generation and build machinery generation need a lot of work yet. That will need updating for sip 4 also. Jim From prunesquallor at comcast.net Sat Nov 1 10:07:53 2003 From: prunesquallor at comcast.net (prunesquallor at comcast.net) Date: Sat, 01 Nov 2003 15:07:53 GMT Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> <3f9d556c$1@news.unimelb.edu.au> <3f9f8f49$1@news.unimelb.edu.au> <3f9fe9b1$1@news.unimelb.edu.au> <3fa26092$1@news.unimelb.edu.au> <3fa3b8a4$1@news.unimelb.edu.au> Message-ID: Fergus Henderson writes: > prunesquallor at comcast.net writes: > >>Fergus Henderson writes: >> >>> But the difference between dynamically typed languages and >>> statically typed languages is that in dynamically typed languages, *every* >>> data access (other than just copying data around) involves a dynamic dispatch. >>> Sure, implementations can optimize a lot of them away. But generally you're >>> still left lots that your implementation can't optimize away, but which >>> would not be present in a statically typed language, such as the O(N) >>> dynamic type checks in the example above. >> >>That's what the type-checking hardware is for. > > Did you forget a smiley? No, I never use smileys. > In case not: type-checking hardware has been tried already, and failed. News to me. I've used type checking hardware and it works like a charm. > (Anyway, type-checking hardware would only solve part of the problem, I think. > Dynamic type checking imposes two costs: one is the time cost of performing > the checks, and the other is the locality cost due to the code size increase. > Type-checking hardware avoids the code size increases, but I don't think it > helps with the time cost of performing the checks.) Actually it works quite well with performing the checks. In general, type checking is much quicker than computation, and in general it can be performed in parallel with computation (you simply discard the bogus result if it fails). You don't need very much hardware, either. From ark at acm.org Mon Nov 17 21:17:37 2003 From: ark at acm.org (Andrew Koenig) Date: Tue, 18 Nov 2003 02:17:37 GMT Subject: syntax philosophy References: Message-ID: <5jfub.77732$Ec1.4046405@bgtnsc05-news.ops.worldnet.att.net> > Then within the loop you use the following construct: > > histogram[word] = histogram.get(word, 0) + 1 Why not this? if word in histogram: histogram[word] += 1 else: histogram[word] = 1 Isn't that crystal clear? Or, for that matter: if word not in histogram: histogram[word] = 0 histogram[word] += 1 From mhammond at skippinet.com.au Thu Nov 20 05:03:47 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 20 Nov 2003 21:03:47 +1100 Subject: win32com with netscape In-Reply-To: References: Message-ID: jeff wrote: > does anyone know how to dispatch netscape with > win32com.client or using make.py? > I search every place I can include microsoft and > netscape and find nothing about it. > I tried to search ID from vc++, and couldn't find it > neither. > I am trying to open netscape browser with > win32com.client and navigate it. > can anyone help? I'm fairly sure you can't. Mark. From adalke at mindspring.com Tue Nov 4 04:14:57 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 04 Nov 2003 09:14:57 GMT Subject: Testing validity of for...in... References: Message-ID: Peter Otten: > Your implementation makes two implicit tests: > > 1. Is mylist iterable > 2. Do the items in mylist have a length It also fails if len(item) returns a different values when called multiple times for a given item. Andrew dalke at dalkescientific.com From __peter__ at web.de Tue Nov 4 16:27:43 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Nov 2003 22:27:43 +0100 Subject: XORing long strings opimization? References: <3ISpb.24447$BD3.4566933@juliett.dax.net> Message-ID: Noen wrote: > def XOR(s1,s2): > """ XOR string s1 with s2 """ > output = "" > # Argument check > if (type(s1) or type(s2)) != type(""): > raise TypeError, "Arguments are not strings" > if len(s1) != len(s2): > raise ValueError, "Size differs in strings" > # Xoring > for i in range(len(s1)): > output += chr(ord(s1[i]) ^ ord(s2[i])) > return output I keep nagging: >>> xor3.XOR("", 1) Traceback (most recent call last): File "", line 1, in ? File "xor3.py", line 7, in XOR if len(s1) != len(s2): TypeError: len() of unsized object Must be in a nasty mood this evening :-) Seriously, I think that "first make it right, then make it fast" is a reasonable design principle. You can check the type if type(s1) != type("") or type(s2) != type(""): ... or if not isinstance(s1, str) or not isinstance(s2, str): ... or even if not type(s1) == type(s2) == type(""): ... but personally I would omit the check altogether. The second check could be relaxed to len(s1) <= len(s2), assuming that s1 is the data to be encrypted and s2 the random character sequence that makes your encryption NSA-proof. For (much) weaker encryption schemes, you could omit it completely and cycle over the characters of s2 (not recommended). As to speed, I would suppose the following to be somewhat faster: def xor(s1, s2): return "".join([chr(ord(c1) ^ ord(c2)) for c1, c2 in itertools.izip(s1, s2)]) It favours "".join(character list) over consecutive s += tail operations, which need to build "many" strings as intermediate results. I think, further speedups could be achieved building a lookup table for all character combinations. Peter From marco at analog.se Wed Nov 12 02:13:56 2003 From: marco at analog.se (Marco) Date: 11 Nov 2003 23:13:56 -0800 Subject: ANN: ruleCore - The event pattern detector engine References: <438a319a.0311091143.256db982@posting.google.com> <1Q5sb.23278$M02.14529@twister.rdc-kc.rr.com> Message-ID: <438a319a.0311112313.22df2a95@posting.google.com> Yes, I can imagine that there are lots of events in an industrial process control setup. I suppose all these events could be fed into ruleCore and there it could detect all kinds of interesting patterns of events that should be reacted to. I didn't understand much of the ladder, but it seems to be some kind of tool for event correlation just as ruleCore is. From aleax at aleax.it Mon Nov 17 07:42:50 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 17 Nov 2003 12:42:50 GMT Subject: Too much builtins (was Re: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <653b7547.0311121826.65b6b2d4@posting.google.com> Message-ID: Ville Vainio wrote: ... > [stuff that should remain builtins] > >> iter, len, pow [for the crucial 3-arguments case], range (or some >> preferable variant that returns an iterator), and zip seem pretty > > +enumerate Yep, it sure should be there. >> are quite handy for interactive use, such as locals, globals, >> dir, vars, ..., are not all that frequently used in programs -- >> so they might live in a module that the interactive mode gets >> automatically, rather than being built-ins. > > locals and globals seem to have a natural place in builtins IMHO. Why? They only allow a limited form of introspection. Why are they more essentially "built-in" than other stuff in inspect? >> All of this would be perfect for the mailing list on Python 3.0 >> if the latter existed. Posting it to c.l.py makes it unlikely >> Guido will ever consider the discussion's resuts, anyway. The > > How about the wiki at python.org? Sure, one could write things up there, but I don't think it's a medium as suitable to debate as a newsgroup or mailing list. Alex From hungjunglu at yahoo.com Sun Nov 23 19:34:39 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 23 Nov 2003 16:34:39 -0800 Subject: code blocks in Python References: <8ef9bea6.0311221215.804bdb3@posting.google.com> <8ef9bea6.0311221913.427cb53e@posting.google.com> Message-ID: <8ef9bea6.0311231634.1ca497ac@posting.google.com> hungjunglu at yahoo.com (Hung Jung Lu) wrote in message > > codeblock A: > x = 1 > y = 2 > > codeblock B: > z = x + y > print z > > exec A > exec B > > This will be equivalent to writing the program: > > x = 1 > y = 2 > z = x + y > print z It just occurred to me a better syntax: def A: x = 1 y = 2 def B: z = x + y print z No new keyword needed, beside, it uses the same keyword as function definition, so the purpose of the code block is clear: it's something that you will invoke. A proper name for this type of meta-programming is "Linear Meta-programming". Just like in algebra you have linear algebra and non-linear algebra, in meta-programming you have all sorts of non-linear ways of taking code pieces and turn them into other code pieces, these include e.g.: (a) compiling: turning a character string into a binary code string, (b) encryption, (c) macro/token substitution, (d) tweaking with the internals like meta-classes, etc. Linear meta-programming is much more modest and well-organized. It's like sequencing DNA bands. Each statement is like a DNA nucleotide, each codeblock is like a DNA band. You just want to sequence the codeblocks properly, and at times replace one block with some other block, or insert additional blocks. I still have yet to hear any difficulties/complaints. I refuse to believe that Python developers have NEVER considered this extension to the language. So, what's the problem? Hung Jung From reply.in.the.newsgroup at my.address.is.invalid Mon Nov 3 06:44:03 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 03 Nov 2003 12:44:03 +0100 Subject: Unicode -> Python -> DBAPI -> PyPgSQL -> PostgreSQL References: <375cqv82qeo8agtlodmbkc8fgo6aa7v2q6@4ax.com> Message-ID: Gerhard H?ring: >Rene Pijlman: >> I can't seem to find any way to specify the character encoding with the DB >> API implementation of PyPgSQL. There is no mention of encoding and Unicode >> in the DB API v2.0 spec and the PyPgSQL README. [...] > >See section 2.2.5 in the pyPgSQL README: Well, its not in this README I found in the Debian package python2.2-pgsql with pyPgSQL 2.0: #ident "@(#) $Id: README,v 1.20 2001/11/05 01:18:12 ghaering Exp $" pyPgSQL - v2.0: Python DB-API 2.0 Compliant Interface Module for PostgreSQL. But this tells me I probably need to upgrade to pyPgSQL 2.3 or 2.4: "Q: I?ve heard of Unicode support for pyPgSQL. What?s the current status? A: It?s integrated in pyPgSQL 2.3." http://pypgsql.sourceforge.net/pypgsql-faq.pdf Thanks a lot Gerhard, you've put me on the right track. -- Ren? Pijlman From jjl at pobox.com Sun Nov 2 17:55:15 2003 From: jjl at pobox.com (John J. Lee) Date: 02 Nov 2003 22:55:15 +0000 Subject: form processing question References: <423f3$3fa58837$42a655ea$20950@msgid.meganewsservers.com> Message-ID: <87ism2754c.fsf@pobox.com> "WmGill" writes: > I am experimenting with Python, and want to convert some of my PHP scripts > to python cgi scripts. In PHP I use PHP_SELF for the action target. This [...question snipped...] Which web framework / library are you using? Or are you just using the standard library cgi module (most Python web programmers use something more than that)? John From mis6 at pitt.edu Thu Nov 6 13:47:15 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 6 Nov 2003 10:47:15 -0800 Subject: PEP 289: universal and existential operators References: <5d83790c.0310231158.65595858@posting.google.com> <9f76ee00.0311051257.45461381@posting.google.com> Message-ID: <2259b0e2.0311061047.4c53948e@posting.google.com> austin at smartobject.biz (Jess Austin) wrote in message news:... > It seems like the consensus is "all" and "any". Not necessarely. I prefer "alltrue" and "anytrue", for instance. Michele From terjeros at phys.ntnu.no Fri Nov 7 16:21:57 2003 From: terjeros at phys.ntnu.no (Terje Rosten) Date: Fri, 07 Nov 2003 22:21:57 +0100 Subject: experience with redhat9 + python2.3 rpms? References: Message-ID: * Matthew Wilson | | Has anyone installed these 2.3 rpms while keeping the old 2.2 rpms and | has anyone had any problems with these? The python2.3 rpm from python.org installs in /usr/lib/python2.3 and as /usr/bin/python2.3 and /usr/bin/pydoc2.3. It does not affect the default python rpm at all. - Terje From andy47 at halfcooked.com Mon Nov 3 05:59:27 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Mon, 03 Nov 2003 10:59:27 +0000 Subject: Getting error condition from MySQLdb In-Reply-To: <3fa5f6e6$0$1722$5a62ac22@freenews.iinet.net.au> References: <3fa5f6e6$0$1722$5a62ac22@freenews.iinet.net.au> Message-ID: Derek Fountain wrote: > I was trying to use MySQLdb to connect to a database. All is OK, except I > can't figure out how to get the details of an error. Suppose I try to > connect to a non existant server, or with the wrong password - how do I get > a meaningful error message which I can present to my user? > In Python whenever an error occurs an exception is raised. I'd suggest a quick read of the section of the tutorial that explains this; http://www.python.org/doc/current/tut/node10.html Then fire up a Python command prompt and try some things out. For instance, on my Windows machine if I try; >>> import MySQLdb >>> mydb=MySQLdb.connect(db='wibble') I get a nice traceback; Traceback (most recent call last): File "", line 1, in ? File "C:\PROGRA~2\PYTHON23\Lib\site-packages\MySQLdb\__init__.py", line 63, in Connect return apply(Connection, args, kwargs) File "C:\PROGRA~2\PYTHON23\Lib\site-packages\MySQLdb\connections.py", line 115, in __init__ self._make_connection(args, kwargs2) File "C:\PROGRA~2\PYTHON23\Lib\site-packages\MySQLdb\connections.py", line 41, in _make_connection apply(super(ConnectionBase, self).__init__, args, kwargs) OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)") If I actually start up MySQL, I get; Traceback (most recent call last): File "", line 1, in ? File "C:\PROGRA~2\PYTHON23\Lib\site-packages\MySQLdb\__init__.py", line 63, in Connect return apply(Connection, args, kwargs) File "C:\PROGRA~2\PYTHON23\Lib\site-packages\MySQLdb\connections.py", line 115, in __init__ self._make_connection(args, kwargs2) File "C:\PROGRA~2\PYTHON23\Lib\site-packages\MySQLdb\connections.py", line 41, in _make_connection apply(super(ConnectionBase, self).__init__, args, kwargs) OperationalError: (1049, "Unknown database 'wibble'") Note that MySQLdb, like the majority of distributed modules, defines its own exceptions. MySQLdb, to the best of my knowledge, implements the standard DB-API exceptions. They are detailed here; http://www.python.org/topics/database/DatabaseAPI-2.0.html Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From martin at v.loewis.de Mon Nov 24 17:47:58 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 24 Nov 2003 23:47:58 +0100 Subject: wxPython i18n question References: Message-ID: Logan writes: > Is it possible to tell the wxPython widgets (e.g. file dialogs) > to use another language (instead of English)? That should certainly be possible. In standard wxPython builds, you are restricted to characters of the "host" encoding (I'm not sure what that encoding is). There are separate "Unicode" builds of wxPython, where you can use Unicode strings throughout. Regards, Martin From vze4rx4y at verizon.net Sun Nov 9 01:55:45 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 09 Nov 2003 06:55:45 GMT Subject: More user feedback on Sets.py References: <1hSqb.1167$bQ3.696@nwrdny03.gnilink.net> Message-ID: [Raymond Hettinger] > > If the need has arisen, is the current design sufficient? [David Eppstein] > I've certainly been doing some implementations of graph algorithms in > which the graph vertices represent sets of objects (but I've been > representing them as bitvectors since I am still running 2.2 and don't > have Sets.py yet). I have added some backwards compatability code so that Sets.py will run Python 2.2. Please give it a test drive: http://cvs.sourceforge.net/viewcvs.py/*checkout*/python/python/dist/src/Lib/sets.py?content-type=text%2Fplain&rev=1.44.8.4 > It would be awkward if I couldn't have sets of > vertices...but I don't see any reason for the sets in these applications > to ever be mutable, so automatic conversion to immutability doesn't seem > to be critical. That was useful feedback. > For something concrete (that I thought about doing recently but haven't > actually done): conversion of NFA to DFA and then state minimization of > the resulting DFA. The converted DFA's states are sets of states of the > NFA, and the state minimization involves sets of DFA states. That would be a perfect way to test drive the sets module. Raymond From google.com.112139 at satilla.com Fri Nov 21 10:58:24 2003 From: google.com.112139 at satilla.com (Eric Baker) Date: Fri, 21 Nov 2003 10:58:24 -0500 Subject: httplib and Proxy References: Message-ID: > > With urllib: > > f = urllib.urlopen("http://www.python.org/index.html") > > I get: > > ... > invalid proxy for http: 'cache.ilt.fhg.de:81' > I dont have a proxy handy, but perhaps you need to include the "http://...." in the proxy environement setting. From theller at python.net Fri Nov 7 15:58:23 2003 From: theller at python.net (Thomas Heller) Date: Fri, 07 Nov 2003 21:58:23 +0100 Subject: [ANN] py2exe 0.5 for Python 2.3 prerelease Message-ID: I've uploaded a new prerelease of py2exe version 0.5. There is still no documentation, but even more samples. Note that this version uses the zipimport feature of Python 2.3, it does not work with older versions. Feedback and testing encouraged, if someone feels to contribute docs, the wiki is always open. Thanks to Chris Liechti for first contributions. Wiki: Release notes: Download: Homepage: (although the docs on this page are out of date). Thomas From richie at entrian.com Tue Nov 11 12:11:08 2003 From: richie at entrian.com (Richie Hindle) Date: Tue, 11 Nov 2003 17:11:08 +0000 Subject: Structured Text or ReStructured Text Viewer In-Reply-To: References: Message-ID: <1s52rvo994peefnf9bneqvojau5a5ght0a@4ax.com> [Hoang] > Does anyone know of a Structured Text or ReStructured Text interactive > previewer? Yes: http://python.net/~gherman/ReSTedit.html ...but it's MacOS X only. 8-( -- Richie Hindle richie at entrian.com From emile at fenx.com Tue Nov 11 18:50:33 2003 From: emile at fenx.com (Emile van Sebille) Date: Tue, 11 Nov 2003 15:50:33 -0800 Subject: response time References: <1jSrb.2419$9_.105379@news1.tin.it> <87d6bzetsz.fsf@pobox.com> <3FB01787.529425BC@engcorp.com> <87u15bf6qs.fsf@pobox.com> Message-ID: Andrew Dalke: > I am hoping for symbolic reasons that in another couple of years it > will be possible to buy a 4.77 GHz processor. Great! Another good reason to _not_ clean out the garage. Emile van Sebille emile at fenx.com From adalke at mindspring.com Fri Nov 14 18:20:29 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 14 Nov 2003 23:20:29 GMT Subject: Palindrome References: <20031112223135.29045.00000109@mb-m12.aol.com> <3FB3C016.56BCA546@hotmail.com> <3FB4BBFB.65AE0B9A@hotmail.com> Message-ID: <1rdtb.782$sb4.244@newsread2.news.pas.earthlink.net> Alan Kennedy > The possibility of the same feature occurred to me. However, I'm still > not sure if this would solve the problem. How would the "pivot point" > be recognised by such an augmented regex engine? i.e. how would it > recognise the point at which it should stop capturing, reverse the > sequence and start matching again? Back-tracking. Suppose there was such a thing as (.*).?\~1 where the \~1 matches the reverse of the first group. Now match that pattern against NOON The (.*) matches all the way up to "NOON" then tries and failes to match both the .? and the \~1 It backtracks one so that (.*) matches "NOO" and the N remains. The .? matches the N but the \~1 does not so it backtracks so that the .? matches nothing, but still the \~1 does not match the N. It backtracks another so that (.*) matches "NO" and the "ON" remains. The .? first matches with the "O" leaving the "N", but \~1 doesn't match that, so it backtracks so that the .? matchs nothing, leaving "ON" for the \~1. This matches! In other words, it goes through a lot of work to do the matching, and would take O(N) backtracks to work. But that's not quite correct. An implementation is free to analyze the pattern and notice that it's being asked to search for a palindrome then insert special case code for that pattern. > Perhaps one would need to also implement a feature whereby the length > of the entire string could be made available within expressions, so > that the size of a capture group could be limited to the first half of > the string? I.E. Something along the lines of > > ^(.{strlen/2}).?\~1$ Yup. That would work as well. There are all sorts of special things one could capture in a regex-like language. Perl 'solves' it by allowing any match to call out to embedded Perl code, which is free to tell the matcher to stop or continue matching. > One of these days I'll find the time to dig out my old course notes > and books :#) Friedl's regexp book (from ORA) is quite good. Andrew dalke at dalkescientific.com From usenet_spam at janc.invalid Sun Nov 2 21:34:51 2003 From: usenet_spam at janc.invalid (JanC) Date: Mon, 03 Nov 2003 02:34:51 GMT Subject: best GUI toolkit for python: tkinter, wxPython or what? References: Message-ID: Phil Thompson schreef: > Under Windows you need either the commercial versions of both Qt and > PyQt, or the educational versions of both Qt and PyQt. Note that > Trolltech have (quietly) withdrawn the non-commercial version of Qt > (based on the, now very old, Qt v2.3). Some people outside of Trolltech are working on a GPL'ed version for Win32: (This should compile using mingw.) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From logan at phreaker.nospam Fri Nov 28 15:19:56 2003 From: logan at phreaker.nospam (Logan) Date: Fri, 28 Nov 2003 21:19:56 +0100 Subject: newbie : using python to generate web-pages References: Message-ID: On Fri, 28 Nov 2003 10:57:31 -0800, biner wrote: > I am taking up on the work of a coleague who developed a big perl > script to generate a bunch of html files. I am taking over his task > and I looked at his code. It is quite messy because he used simple > "print" command to print the html code into files so the script is a > mix of html an perl. Quite ugly. > > I don't know much about perl but I know that there are html > shortcuts in the CGI module that could allow me to make the code more > readable. Something like "print em(toto)" that would print > "toto" I don't really think that 'print em(toto)' is more readable than 'print "toto"'. But that seems to be a matter of taste. I would always prefer the second way of writing HTML because I can see all the closing tags, indentation etc. Makes finding bugs easier. > Is there anything like that in Python. I did not find anything yet. > I don't know much about python (even less than perl) but I hear good > things about it all the time so I would like to use this project to > get familiar with python. If there are not many places in your HTML where you have to substitute strings, then an approach like the following might be enough: html = """ %s %s """ print html % ("The Title", "Content Area") (You could also use placeholders like xxTitlexx, xxContentxx in the string 'html' and replace them to create the output.) I think, the above solution is really 'readable' :-) If you have to generate 'complicated' HTML files (depending on various options, with dynamic menus etc.), I would recommend to use an XML/XSLT approach, combined with a Python script (e.g. 4Suite (Ft) or libxml2/libxslt; the first is a Python package, the second has Python bindings and both provide nice and easy to use XSLT-processors). And finally, if you have to generate your HTML files dynamically on a web server, you should use a totally different approach; but that would be another thread :-) HTH, L. -- mailto: logan at phreaker(NoSpam).net From SBrunning at trisystems.co.uk Fri Nov 21 10:00:19 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Fri, 21 Nov 2003 15:00:19 -0000 Subject: Question about Objects Message-ID: <31575A892FF6D1118F5800600846864D01200D19@intrepid> > From: campbell95 [SMTP:campbell95 at cox.net] > I've been hacking visual basic for several years and understand the basic > concepts of OOP. That said, I'm stumped here with the Python Class. > > Here is the Class... > > >class Test: > > def __init__(self, something): > > self.something = something > > > > def getSomething(self): > > return self.something > > This is what I get when I test it. Why does not return the > value of ? is obvious that has a value. I fear this > is a simple oversight but I've racked my brain for hours looking at online > doc's and examples. Thanks for any help!! > > >Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on > win32 > >Type "copyright", "credits" or "license()" for more information. > >**************************************************************** > >IDLE 1.0 ==== No Subprocess ==== > >>>> > >>>> x = Test("Microsoft Sucks") > >>>> x.getSomething > > 0x00C01940>> > >>>> x.something > >'Microsoft Sucks' > >>>> getSomething *will* return something - but you have to *call* it. See, a function (or method, a.k.a a bound method) is also an object. "x.getSomething" with no brackets at the end just *refers* to this object. To call the function, try "x.getSomething()". This can be very useful at times, 'cos it allows you to pass functions around the same way you do with any other object types. But it also confuses VBers. ;-) Cheers, Simon Brunning, http://www.brunningonline.net/simon/blog/ --LongSig ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From __peter__ at web.de Tue Nov 11 03:02:05 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Nov 2003 09:02:05 +0100 Subject: importing module as filename References: Message-ID: david farning wrote: > I am having a problem with name space contention. > I am combining two existing programs both with their own config > modules. > > I have been expermenting with > import config #grab first config > sys.path.insert(0,"/usr/share/yum/") > import config as yconfig #grab second config > > > The first config always seems to squash the second config. > There should be a yconfig.yumconf but there is not. > > any suggestions? How about a symlink to disambiguate the module names, e. g. ln -s config.py yumconfig.py, and then import config, yumconfig Somewhat more ambitious: convert the program directory into a package by adding an __init__.py script and then import config, yum.config Peter From francisgavila at yahoo.com Mon Nov 10 17:44:35 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 10 Nov 2003 17:44:35 -0500 Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: "Alex Martelli" wrote in message news:BsJrb.445840$R32.14865362 at news2.tin.it... > Francis Avila wrote: >> [a reduce() clone] > [a long and thorough critique] *Sigh* My only objective was to combine functional/recursive/iterative programming styles into an olive branch to extend to both parties of this silly war. But oh well. Like I said, I never found a use for reduce, but alas, I am a ham-fisted programmer entirely lacking in subtlety and art.... -- Francis Avila From tim.golden at viacom-outdoor.co.uk Fri Nov 28 06:48:11 2003 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 28 Nov 2003 03:48:11 -0800 Subject: extract the strings in an exe References: <1jrrrv4g350e4oft2hq7p8ukvrahj45jcf@4ax.com> Message-ID: <8360efcd.0311280348.5b4809b5@posting.google.com> Fernando Rodriguez wrote in message news:<1jrrrv4g350e4oft2hq7p8ukvrahj45jcf at 4ax.com>... > Hi, > > How can I extract all the strings in an exe with python? O:-) Looks like this might be of use (look for SRV): http://www.micon.no/PythonPage.asp I haven't tried it myself; just came across it looking for something else. TJG From aleax at aleax.it Mon Nov 10 11:57:51 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 10 Nov 2003 16:57:51 GMT Subject: reduce()--what is it good for? References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> Message-ID: David C. Fox wrote: ... >> However, so many of reduce's practical use cases are eaten up by sum, >> that reduce is left without real use cases to justify its existence. > > How about ...a typical example of *made-up* case follows...: > import operator > seq_of_flag_integers = [01020, 02300, 00132] #etc. > reduce(operator.or_, seq_of_integers) > > My simple timing tests (cumulative time for 1000 trials, each with a > sequence of 1000 integers), show no significant difference between the > above and an alternative using a for loop and |=, but the above is > clearer to read. You may consider it "clearer to read", and I might opine differently (apart from the typo/bug that you're reducing a sequence you never defined, of course:-). That (necessary) trailing underscore in the name of operator.or_ is quite unpleasant, for example. But I think the real point is another. If you're doing lots of bit-twidding in Python, you surely need to learn such Python constructs as for and |= anyway. With these can't-avoid-learning-them constructs, you can obviously code a simple, elementary loop such as: ored_flags = 0 for flags in all_the_flags: ored_flags |= flags Alternatively, you may learn _two more_ things -- that 'reduce' thingy _plus_ the fact that module operator has an or_ function that does the same job as | -- all in order to get an *equivalent* way to code the same task?! Not to mention that what you end up coding this way is most definitely NOT going to be any clearer than the simple, elementary loop to any future maintainer of your code -- if your bit-twiddling code is going to be maintained by somebody who doesn't understand for or | you are in trouble anyway, friend, while -- given that reduce and operator.or_ give NO real advantages! -- it WOULD be perfectly possible for your future maintainer to NOT be familiar with them. > I'm not claiming that the use case above is common, or particularly > useful. I'm just pointing out sum doesn't replace reduce unless the > function being applied is addition. Addition may be the most common > case, and in that case, sum is both clearer and faster. However, that > doesn't detract from the clarity and usefulness of reduce in the > remaining cases. It's hard to detract from the clarity and usefulness of a construct that never had much usefulness OR clarity in the first place. When we've taken away just about all of its reasonably frequent use cases, what remains? Essentially only a case of "more than one way to do-itis" where in the "BEST" case the existence of 'reduce' and module operator let you "break even" compared to elementary, simplest coding -- and more often than not you can fall into traps such as those exemplified by most reduce-defenders' posts on this thread. > P. S. I've seen a lot of talk about removing old features from Python, > or specifically old built-ins, because of bloat. Does this "bloat" > reduce performance, or does it refer to the extra burden on someone > learning the language or reading someone else's code? A slightly larger memory footprint, and larger built-ins dictionaries, can only reduce runtime performance very marginally. The "cognitive burden" of having built-ins that "don't carry their weight", on the other hand, is considered an issue *in Python*, because it doesn't fit in with Python's general philosophy and worldview. Python is meant to be a LEAN language (with a not-lean standard library of modules that are specifically imported when needed); certain "legacy" features are sub-optimal (and best removed, when the strict constraint of backwards compatibility can be relaxed) because they interfere with that (and built-ins are close enough to "the core language" that they _do_ need to be weighed severely in terms of "how often will they be useful"). It's a conceptual wart that the only sincere response to this thread subject can be "not much, really -- basically backwards compatibility, and some people's preference for constructs they're used to, often in preference to simpler or better performing ones, some of which didn't happen to have been introduced yet when they learned Python"...:-). Alex From __peter__ at web.de Tue Nov 25 12:41:35 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Nov 2003 18:41:35 +0100 Subject: Subclassing ConfigParser question References: Message-ID: Roy H. Berger wrote: > If I want to subclass ConfigParser and changed the optionxform method > to not return things in lower case wouldn't I just need the following > code in my subclasss module? > > from ConfigParser import * > > class MyConfigParser(ConfigParser): > def __init__(self, defaults=None): > ConfigParser.__init__(self, defaults) > > def optionxform (self, optionstr): > return optionstr > > Or do I need to re-implement all of the methods of ConfigParser? > Sorry -- haven't done much subclassing with python. You need to reimplement only methods with changed behaviour - that's the whole idea of inheritance. In the above example even the constructor is superfluous: import ConfigParser # import * is *bad* class MyConfigParser(ConfigParser.ConfigParser): def optionxform(self, optionstr): return optionstr would suffice. There is of course no guarantee that other methods of ConfigParser make assumptions about optionxform() that your modified method does not hold. These you will have to detect with a properly designed test suite. Peter From paolo at hypersonic.it Tue Nov 25 04:01:50 2003 From: paolo at hypersonic.it (Paolo Losi) Date: Tue, 25 Nov 2003 10:01:50 +0100 Subject: Execution state persistence for workflow application In-Reply-To: References: Message-ID: <3FC31A7E.4010805@hypersonic.it> Serge Orlov wrote: >>Questions are: >> >>- does there exist a python framework for workflow that use >> python script as a specification language and that >> support "long running" workflows? I don't want to reinvent the wheel... > > Not that I'm aware of. > > >>- does the implementation idea quickly depicted makes sense to you? > > Partly. It's not complete and that makes it look more simple than > data persistence when it's not. The problem is that one day you will > have to upgrade your program and your last dumpexec won't be > compatible with your next loadexec(). You will have to separate > code from data to do it. So it means execution persistence is not > enough for real life use. Why not just use data persistence alone? In fact data persistence is not sufficient to stop and resume scripts in case, for example, system reboot. I do want my workflow scripts to resume exactly (and with the same globals/locals setup) where they left... The real alternative would be to define a new script language with standard constructs (for, while,...) but again... i don't want to reinvent the wheel. I do not seen execution persistence as an alternative to data persistence: I would need both. >>- how do you suggest to implement execution persistence? Is there >> any "standard" solution? > > Use data persistence and your own custom loader. Don't be afraid > of the word loader. It's very simple. For a simple persistant "hello, > world!" program it's about 5-10 lines. I think ZoDB is the most > popular data persistence framework. It's very nice and simple. > > -- Serge. Thanks! Paolo From mis6 at pitt.edu Wed Nov 12 09:06:00 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 12 Nov 2003 06:06:00 -0800 Subject: True, False, None References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> Message-ID: <2259b0e2.0311120606.3ed0877f@posting.google.com> "Andrew Dalke" wrote in message news:... > Michele Simionato > > Better to say: singletons are classes. But True and False are not > > classes (no '__base__' attribute, for instance) so they are not > > singletons. > > I don't follow your statement. > > Not all singletons are classes. Imported modules are > singletons, yes? And as an implementation choice the > numbers -1 to 100 are singletons as are the single character > byte strings. (Implementation choice since the spec requires > that None references a singleton but not that 1 and 3-2 > always reference the same object.) It is solely a matter of conventions. I am used to the definition "a singleton is a class with only one instance". According to this definition a singleton is a class. But it is true that a lot of people extend the meaning to modules or numbers, so you are also right. It is unfortunate that many concept in CS are not very well defined (or, even if well defined, the right definition is not universally known). Michele From gradha at titanium.sabren.com Sat Nov 29 17:51:10 2003 From: gradha at titanium.sabren.com (Grzegorz Adam Hankiewicz) Date: Sat, 29 Nov 2003 23:51:10 +0100 Subject: ANN: mailbox_reader 1.0.4 -- Python module to read UNIX mailboxes sequentially. Message-ID: <20031129225110.GA1390@pedos.es> CHANGES Renamed base exception, old name maintained for backwards compatibility. Bound exceptions to Mailbox_base class, more pythonic. Updated usage example catching the exception of the Mailbox object. Added notice of http://www.linuxlinks.com/. DESCRIPTION The module provides two classes: Mailbox, a file-like object which allows you to iterate through the contents of a mailbox, and Email, an object which holds the individual emails returned by Mailbox. Mailbox inherits from Mailbox_base, but usually you don't need to even know about this class. Mailbox_base implements the file like mailbox reading part of the class, and the Email object creation. Use the Mailbox class in your code, which will always maintain the same API for backwards compatibility. This module has been written with simplicity in mind, and low memory consumption. Unless you do something bad, I estimate maximum memory consumption as twice the memory required by the largest email of the opened mailbox. But I'm guessing, maybe it is lower, like one time your biggest email. DOWNLOAD http://gradha.sdf-eu.org/program/mailbox_reader.en.html http://www.vex.net/parnassus/ http://freshmeat.net/ http://www.linuxlinks.com/ LICENSE GPL -- Please don't send me private copies of your public answers. Thanks. From tjreedy at udel.edu Sat Nov 22 22:40:57 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 Nov 2003 22:40:57 -0500 Subject: 2.2.2 Annoyance References: Message-ID: "Jegenye 2001 Bt" wrote in message news:bpoo6c$nhh$1 at namru.matavnet.hu... > According to the manuals of Python 2.2.2, passing a slice object to ... > Would someone care to pass on this info to whom this may concern? 2.2.2 was superceded by 2.2.3. This info is only of concern to people who have and will not upgrade to 2.3. > For Python 2.3 passing a slice object to __getitem__ does work though. 2.3 fixed more bugs beyond 2.2.3, added a couple of builtins, and several modules. This change in behavior between 2.2.2 and 2.3 was almost certainly intentional, due someone already noticing what you did. tjr From tdelaney at avaya.com Mon Nov 3 20:31:17 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 4 Nov 2003 12:31:17 +1100 Subject: alwayssortedlist (was Re: On PEP 322 (ireverse)) Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DEDF5C7F@au3010avexu1.global.avaya.com> > From: Alex Martelli [mailto:aleax at aleax.it] > > > Not only is it not effective, but heaps don't keep their elements in > > sorted order... so if you wanted a list to stay sorted, heaps aren't > > Please don't "top-post": somebody reading your reply can't see what > you ARE responding to. Putting your comments AFTER the phrase you're > commenting on is much kinder to readers. > > I said a heap is "not effective" (as a way to sort, in Python) because > the sort method of lists is so much faster. You CAN use a heap to > sort, it's just not an _effective_ way to perform sorting in Python. I'd argue that Alex. It may not be an "efficient" or "elegant" way to sort in Python, but there's not denying that it is "effective" - it does the job correctly. If you don't go out of your way to muck it up ;) Tim Delaney From eelgueta at navix.cl Tue Nov 11 22:12:48 2003 From: eelgueta at navix.cl (Edo) Date: Wed, 12 Nov 2003 00:12:48 -0300 Subject: trouble understanding None In-Reply-To: References: Message-ID: You should not print the function result, just invoke them. Ed. Jakle wrote: > I'm trying to write a program (with my very limited knowledge of python) > that will convert text I type into those letters drawn with ascii symbols. I > did 2 letters then went to test it. Here's the code I have so far: > > ******************************************* > def S(): > print " ________ " > print " /--------\ " > print "// \\" > print "|| ^^" > print "|| " > print "\\________ " > print " \--------\ " > print " \\" > print " ||" > print "_ ||" > print "\\________//" > print " \--------/ ", > > def T(): > print "______________" > print "------ ------" > print " || " > print " || " > print " || " > print " || " > print " || " > print " || " > print " || " > print " || " > > print S(), T() > ******************************************* > > WOW, that came out weird, but if you copy/paste it into idle it looks fine. > That an "S" and a "T". Anyways, The idea is to have a function for each > letter, then use a for loop and a ton of if statements to traverse and print > the letters/functions. I understand that I might be doing too much work to > do this, but I'm trying to practice what I am learning. OK, the test prints > the letters, but also prints "None" at the end of each function. I don't > understand it. I'm reading "How To Think Like A Computer Scientist: Learning > With Python", and it only has one little paragraph about the "None" return > value, and that's only regarding conditional statements. If someone could > throw some wisdom my way I'm be very greatful. Thanks ahead of time. > > From cce at clarkevans.com Wed Nov 26 17:02:46 2003 From: cce at clarkevans.com (Clark C. Evans) Date: Wed, 26 Nov 2003 17:02:46 -0500 Subject: portable development -- python for the pda? Message-ID: <20031126220246.GA63148@clarkevans.com> Hello. I'm going to be doing quite a bit of travel in January and I'd like to continue to program on-the-road. So, I'm in the market to buy a PDA with a fullsize (foldable) keyboard. Does anyone have this sort of setup working? I typically use python and vim, with postgresql. I don't strictly need postgresql, but having python run on the PDA would be nice. Any suggestions? Cheers! Clark From urnerk at qwest.net Tue Nov 4 15:12:38 2003 From: urnerk at qwest.net (kirby urner) Date: 4 Nov 2003 12:12:38 -0800 Subject: PEP 289: Generator Expressions (please comment) References: <62d9521c.0311022349.d85fd92@posting.google.com> Message-ID: <62d9521c.0311041212.6c4f8b42@posting.google.com> Alex Martelli wrote in message news: > d = (f(p) for p in X if g(p)) > > will have the same semantics as: > > def _aux(): > for p in X: > if g(p): > yield f(p) > d = _aux() > del _aux > > no more, no less. > > > Alex OK, thanks for the clarification. Not creating an indexable, just an iterable, got it. Some analogy with list comprehensions was throwing me off. So X in the above could be a a generator-based iterable too. This'd be one way to feed generators from other generators. Kirby From alberto.mantovaniNOSPAM at bologna.marelli.it Wed Nov 5 06:46:10 2003 From: alberto.mantovaniNOSPAM at bologna.marelli.it (Alberto Mantovani) Date: Wed, 05 Nov 2003 11:46:10 GMT Subject: from py1.5.2 to py2.2.2 Message-ID: <3ef1689d.4105304@news.marelli.it> Hi, I have a lot of scripts written in python1.5.2 that I want to bring in python2.2.2. Someone could give me some informations about the sintax difference between this 2 version? Where can I get documents about it? Are there some available tools to do this automatically? thanks Alberto From SBrunning at trisystems.co.uk Thu Nov 6 10:20:00 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Thu, 6 Nov 2003 15:20:00 -0000 Subject: screensaver Message-ID: <31575A892FF6D1118F5800600846864D01200C9D@intrepid> > From: mis6 at pitt.edu [SMTP:mis6 at pitt.edu] > I would like to disable/enable the screensaver on a Win98 box with a > Python script. Any suggestion? Thanks, Not exactly what you want, but it might set you in the right direction... http://www.brunningonline.net/simon/blog/archives/000562.html Cheers, Simon Brunning, http://www.brunningonline.net/simon/blog/ --LongSig ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From newsgroups at jhrothjr.com Mon Nov 17 20:19:12 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 17 Nov 2003 20:19:12 -0500 Subject: PEP 321: Date/Time Parsing and Formatting References: <20031117161752.GA17615@nl.linux.org> Message-ID: "Bengt Richter" wrote in message news:bpbq7h$nf2$0 at 216.39.172.122... > On Mon, 17 Nov 2003 17:59:24 -0500, "John Roth" wrote: > > > > >"Gerrit Holl" wrote in message > >news:mailman.803.1069091744.702.python-list at python.org... > >> Hi, > >> > >> PEP 321 reads: > >> > Python 2.3 added a number of simple date and time types in the > >> > ``datetime`` module. There's no support for parsing strings in various > >> > formats and returning a corresponding instance of one of the types. > >> > This PEP proposes adding a family of predefined parsing function for > >> > several commonly used date and time formats, and a facility for generic > >> > parsing. > >> > >> I was recently surprised by this fact. I don't know why there isn't > >> such a function/method. In my opinion, it isn't a question of whether > >> to add them or not, but how. > >> > >> > Input Formats > >> > ======================= > >> > > >> > Useful formats to support include: > >> > > >> > * `ISO8601`_ > >> > * ARPA/`RFC2822`_ > >> > * `ctime`_ > >> > * Formats commonly written by humans such as the American > >> > "MM/DD/YYYY", the European "YYYY/MM/DD", and variants such as > >> > "DD-Month-YYYY". > > > >I didn't notice this going past the first time: YYYY/MM/DD is the > ^--UIAM, NOT! > >ISO standard format, DD/MM/YYYY is the European variant to > >the American MM/DD/YYYY. > > I thought '-' delimiters were standard, and the yyyy-mm-dd ordering standard, > and anything else a variant. I usually don't worry about the delimiters, but you're probably right. The ISO standard is yyyy-mm-dd, however, the *customary* usage in most of the world is dd-mm-yyyy, and in the US it's mm-dd-yyyy. In fact, you'd have difficulty finding anyone around these parts who knows that year first is a standard, let alone *the* international standard. And I very seldom see it on the web sites I visit, regardless of country of origin. John Roth > > See > http://www.w3.org/TR/NOTE-datetime > or > http://www.iso.ch/iso/en/prods-services/popstds/datesandtime.html > > [...] > > Regards, > Bengt Richter From testa at allos.sytes.net Mon Nov 17 08:32:16 2003 From: testa at allos.sytes.net (F.G.Testa) Date: Mon, 17 Nov 2003 11:32:16 -0200 Subject: asyncore/asynchat References: <698f09f8.0311141355.2430c07b@posting.google.com> Message-ID: But how do you keep it updated since we don't receive any notifications of closing/removing channels from asyncore/asynchat? I've found this: asyncore.socket_map (asyncore.py:62). It is a map of your inherited asynchat class and I'm using it to search for a specific channel and send data to it, but having my own dictionary would be more elegant, I think. "Jeremy Fincher" wrote in message news:698f09f8.0311141355.2430c07b at posting.google.com... > "F.G.Testa" wrote in message news:... > > How do I access the underlying list/map/array of AcmeChannel? > > Thank you. > > There is none, but feel free to keep one yourself; I've done that, for > instance, when I want to limit the number of connections to a server > that should (barring malicious clients) have very fast sessions. > > Jeremy > -- > http://mail.python.org/mailman/listinfo/python-list > From tim.ronning at start.no Fri Nov 7 14:40:35 2003 From: tim.ronning at start.no (Tim Ronning) Date: Fri, 07 Nov 2003 20:40:35 +0100 Subject: [newbie] GTK+/QT/Tkinter ? In-Reply-To: References: Message-ID: P? Fri, 07 Nov 2003 17:51:11 +0100, skrev Alexandre Rogers : > Hi everyone ! > > I am beginner in Python, and it is, so far, the best programming language > I've seen (apart, perhaps, from Java, but the official release is not > open source, so it is a bit difficult for redistribution). > > I'm working on a (personal) project and I need a GUI, which needs to be > portable (I run a Linux system and I'd like my program to run on Windows, > at least). > > I first thought of Qt with Eric and Qt designer, but it is not portable > (for free). > Then GTK. Looks great (with Glade) but is it really portable or not ? > > I know a bit about Tkinter, which I like although it is not the most > attractive. > Is there an IDE/GUI builder for Tkinter ? > > > Many thanks in advance, > > Alex > Hi there One alternative you could try is FLTK with the pyfltk wrapper. It's multiplatform, pure GPL GUI toolkit. FLTK comes with "Fluid" a really nice and easy gui builder. The output of Fluid can be converted to python via flconvert which is a tool for pyfltk. I'm trying FLTK out now, and beeing a beginner like you, I find it quite easy to work with. You could still use Eric, it's a great code editor. It has some bugs though, but thats another story. FLTK: http://www.fltk.org/ pyfltk: http://pyfltk.sourceforge.net/index.html Best regards Tim R. -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From dek at compbio.berkeley.edu Sat Nov 8 21:04:49 2003 From: dek at compbio.berkeley.edu (David Konerding) Date: Sun, 9 Nov 2003 02:04:49 +0000 (UTC) Subject: ANN: Leo 4.1 beta 1 An outlining editor References: Message-ID: In article , Tim Churches wrote: > > --=-ay9WZH8rLWdKtLGxycO8 > Content-Type: text/plain > Content-Transfer-Encoding: quoted-printable > > On Sat, 2003-11-08 at 02:45, Edward K. Ream wrote: >> Leo 4.1 beta 1 is now available at: http://sourceforge.net/projects/leo/ >>=20 >> This is the first official release of the reorganized 4.1 code base. The >> code appears solid, and has not been widely tested. Please use caution w= > hen >> using this code. > > A small request: please don't use spaces in directory or files names in > your Leo distribution - use dashes or underscores if you need a > separator. Spaces annoy the hell out of anyone using a command line > interface. Not me... whenever I try to TAB-complete in bash and the matching file has spaces it just adds the quotes or the \ as necessary. Dave From dave at pythonapocrypha.com Wed Nov 5 12:43:46 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 5 Nov 2003 10:43:46 -0700 Subject: auto-upgradable application References: <18e22d94.0311050900.41faab5d@posting.google.com> Message-ID: <1b2c01c3a3c4$5d76f360$6400000a@YODA> > The endless request from my partners to fix the bugs or add new > features already solved on the new version was really annoying. > > So, I was thinking about adding an auto update feature to my app, if > anybody knows about any package for these purpose would be great. > > If not at least I'll write a very basic script (different 'exe' on the > distribution) that checks for a a new version (on an intranet/internet > location), if so and no update to the main core is done (the Python or > wxPython libraries) then update the changes or display a message to > update to the latest version for main core update. > > Do you have a better idea? No, that approach works pretty well. At my company I created a build process that spits out the installer, the "full update" and the "incremental" update. New users always download and install using the installer. Our app is a networked app already, and part of the message that periodically comes back from the server (client talks over XMLRPC to a Zope server) is info on the latest version number and download locations. If the client detects that it is out of date, it looks at the version info to see if it is eligible for the incremental update and downloads it, otherwise it downloads the full update (both are just zip files - full update is about 4 MB, incremental is usually around 1MB. If your users are all on a LAN then it's probably not worth the extra effort to distinguish between full and incremental IMO). Once the update has been downloaded the GUI prompts the user to see if they'd like to install it right away or wait. When the installation is kicked off, a tiny separate program waits for the main app to shutdown, unpacks the new files, and then relaunches the app. One last thing that you probably don't need is that the client reports to the server its version. This lets you keep track of how many users are still on an old version, but in our scenario we also use it so that the server can send back a "you're too old and must upgrade!" message so that the client-server protocol can gracefully evolve over time. -Dave From seberino at spawar.navy.mil Mon Nov 3 13:44:48 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 3 Nov 2003 10:44:48 -0800 Subject: Does python always need to compile ENTIRE program before it can start to run it??? Message-ID: I can achieve something similar to Python's automatic compilation in C/C++ by making a script that compiles and runs my program like this: make ; myprogram I am trying to think of an advantage Python has over this hack.... Is it true that unlike C/C++ that Python programs can start executing before compilation is COMPLETELY done??? I think so but I'm not sure. Chris From andrew-wants-no-spam at fabbro.org Mon Nov 17 12:43:16 2003 From: andrew-wants-no-spam at fabbro.org (Andrew Fabbro) Date: 17 Nov 2003 09:43:16 -0800 Subject: Variable interpolation question Message-ID: This is probably a beginner's question, but I'm stuck...please be kind to an ex-perler ;) How do I do something like this: for attr in dir(some_obj): if ( some_obj.attr == 0 ): print "Missing data: %s field %s" % ( some_obj.name, some_obj.attr) Of course, this gives "AttributeError: foo instance has no attribute 'attr'" I really don't want to use exec/eval, as that slows things down dramatically. Help? Thanks. -Drew From X.3.M__antispam__ at mail.ru Thu Nov 6 23:36:57 2003 From: X.3.M__antispam__ at mail.ru (sinisam) Date: Fri, 7 Nov 2003 05:36:57 +0100 Subject: Need help with OOP Message-ID: Object oriented programming is not a new term to me, but when I tried to do some of it... uhh... it sure looked (and felt) like Hell :) I won't bother about things like "help me learn it" (but wouldn't mind if someone recommends a good fresh-start tutorial), instead I'll ask for help... I did my share of programming several years ago... 6 or 7 to be more specific, and as I'm pretty proud of my achievements ;) I continued on the same path. Several weeks ago, Python showed up. I got the 'assignment' to start learning it... almost professionally :) OK, I did my part, but now the tests are becoming more than fair :( Next part (even though I said I know *nothing* about OOP) is: "Make class for the IP address. It should be initialized from the string. Later on, we can add functions to it." [1] What in the world I have to do here? [1a] How to make class for the IP address? What does it mean? [2] "Initialization from the string" means something like passing arguments from the command line...? Of course, I don't expect you to do the job for me, but I would sure appreciate help. I know this is easy, but as stated before, I don't know how to handle objects... yet :) I informed my 'mentor' that the training on OOP subject has begun and I started looking for good literature. In the mean time, I'm trying to buy some time, and I was hoping that your suggestions could help me. Thanks for the help, and if I was unclear at some point, just shoot :) Ciao, Sinisa P.S. Can somebody please explain how can I.... how to avoid all these "I"'s from being used as often as I'm doing it? :( It really goes on my nerves as I feel like illiterate idiot :( P.P.S. Speaking of being illiterate, no, English is not my native language. Just in case someone wanders... :o) From jjl at pobox.com Wed Nov 5 10:48:14 2003 From: jjl at pobox.com (John J. Lee) Date: 05 Nov 2003 15:48:14 +0000 Subject: Python versus VB References: <3fa057e2.14061399@news.dsl.pipex.com> Message-ID: <87ptg6yfy9.fsf@pobox.com> "Frithiof Andreas Jensen" writes: > "Jeff Hinrichs" wrote in message > news:BUGob.15745$d87.8065 at okepread05... [...] > Ahem - The point I was trying to make was: It all Depends what you need to > *do* does it not? > > If, say, all the OP needs to achieve is some massaging of strings between > one MS-office app, say Access - for example to circumvent that entirely > stupid and undocumented by MS 1 second minimum time resolution hardcoded > into Access, and maybe a MS-Word form then certainly it will be easier to > hack something up with the tools that are already lurking inside the > platform IMO. [...] Not if you don't already know about where that stuff lives, and some minimal amount of VB. It could well be easier in Python in that case, as the overhead in boilerplate code is small. John From jolsen at mail2world.com Tue Nov 18 04:36:07 2003 From: jolsen at mail2world.com (Jesper Olsen) Date: 18 Nov 2003 01:36:07 -0800 Subject: C++ extention Message-ID: <6b17fa95.0311180136.723d51b2@posting.google.com> I have a python extention implemented in C/C++ - the extention itself is internally implemented in C++, but the interface is pure C, so that it can easily be called from a python C-wrapper. The extention is compiled with distutils, and this has worked well in both Windows and Linux environments. Now, however, I get an undefined symbol _ZTVN10__cxxabiv117__class_type_infoE when I try to import the extention on Linux (only linux). I think this has happened after gcc was upgraded to gcc 3.2.2 Has anyone seen this? What could be the problem? Jesper From aleax at aleax.it Wed Nov 12 11:22:51 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 12 Nov 2003 16:22:51 GMT Subject: True, False, None References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> Message-ID: JCM wrote: > Alex Martelli wrote: > ... >> To me, personally, all of this debates only underscores yet again the >> one serious "ergonomic" defect in Python's syntax -- case sensitivity. > > You know this has been discussed repeatedly with opinions expressed on > both sides. Calling it a defect is just incitive. Nice word (I admit I had to look it up, but don't feel too bad about that, because American Heritage didn't know it either:-). But, so what? Particularly when carefully starting a sentence with "To me, personally", I _DO_ get to express my opinions, you know, even though you consider them "[adj] arousing to action or rebellion" (and I disagree with your opinion of them: I am convinced that no action nor rebellion can ever remove from Python the wart of case-sensitivity). If and when people design their own little languages they're quite likely to model some of their aspects on languages they do know. I _do_ hope to "arouse to action" some would-be designer of some such specialized language, enough that they'll consider making said future minilanguage case-insensitive; if they do, I think the overall amount of happiness in the world will be (albeit minutely) increased. Alex From email9898989 at yahoo.com Sat Nov 15 01:37:33 2003 From: email9898989 at yahoo.com (email9898989 at yahoo.com) Date: 14 Nov 2003 22:37:33 -0800 Subject: Tutorial for DB-Frontend with GUI References: <2560581.qn5EVrxEmu@usenet.pinguin.uni.cc> Message-ID: > So, does anyone know a tutorial/howto/link or whatever how to build > a database client with a GUI? Is there a sample database-fronted > built with python in the web, where one can see what is possible? Pythoncard includes a dbBrowser sample. But really you can use any GUI toolkit with the mysql python module: http://sourceforge.net/projects/mysql-python http://www.devshed.com/Server_Side/Python/PythonMySQL/print_html http://www.codespark.net/v2/articles.asp?CategoryID=45 See also SQLObject which might be a nicer way to do the MySQL coding: http://sqlobject.org/ From ny_r_marquez at yahoo.com Thu Nov 13 15:51:43 2003 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 13 Nov 2003 12:51:43 -0800 Subject: First Impressions of Linux GUI Programming References: <8a27e309.0311120842.2d873a60@posting.google.com> Message-ID: <8a27e309.0311131251.6fe5df0d@posting.google.com> > > Now, if I could only figure out a way to interact with my utility from > > Konqueror or Nautilus, as the "Send to" feature of Windows Explorer > > allows, I will be even happier. ;) > > Under Konqueror go under settings. You can map your file associations, > and have multiple associations for a file type. Type in "py" as file type. > Stephen, What I mean is that, in Windows Explorer, I am able to select a few arbitrary files and/or directories, right click on them and send them to an app as parameters. That way, the app could perform a certain job on each one of the selected files. I've now heard that I'll have to wait until KDE 3.2 comes out to be able to do this, since it will allow one to define custom context menu entries. I just hope that I will be able to easily write them through Python. (I wonder if GNOME will have something similar.) From gh at ghaering.de Thu Nov 13 05:36:45 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 13 Nov 2003 11:36:45 +0100 Subject: Newby Question: Remove files older than 7 days from a directory In-Reply-To: References: Message-ID: kbass wrote: > I would like to remove file that are older than 7 days old from a directory. > I can do this in shell script rather easy but I would like to integrate this > functionality into my Python program. How can this be achieved? Which module > can be used to perform this tasks? Thanks! > > Shell Script example: find /path/to/dir -mtime +30 -exec rm '{}' \; Here's a short example: import os, time path = r"c:\tmp" now = time.time() for f in os.listdir(path): if os.stat(f).st_mtime < now - 7 * 86400: if os.path.isfile(f): os.remove(os.path.join(path, f)) -- Gerhard From peter at engcorp.com Mon Nov 10 15:15:57 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Nov 2003 15:15:57 -0500 Subject: Blocking readline() Call? References: Message-ID: <3FAFF1FD.8449CC8F@engcorp.com> Scott Brady Drummonds wrote: > > I'm just figuring Python out but have become stalled with the following > snippit of code: For some reason, the program stalls after the "read line: > x" for the last line. The 'done reading cycle map' message is never > generated: > > while 1: > line = file.readline() > if line == '': > continue Correct this: you want "break", not continue. > data = line.strip().split(':') > cycleMap[int(data[0])] = int(data[1]) > i = i + 1 > print ('read line %d' % i) > file.close() > print ('done reading cycle map') > > I thought readline() was supposed to be non-blocking. Have I misunderstood > something? Yes, the problem wasn't where you thought it was. A well-placed print statement or two would have showed you that readline was being called repeatedly, not blocking. -Peter From francisgavila at yahoo.com Sun Nov 30 01:57:45 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 30 Nov 2003 01:57:45 -0500 Subject: Need some advice References: <2idisv45km5c64v2iqn7mj7pim3l1f4hpk@4ax.com> Message-ID: Jeff Wagner wrote in message ... >Bruno, you asked "import the dictionary from a function" ???? Yes, this is what I tried that isn't >working: Hmm... >def chaldeanValues(): > > dateValues = { ... > } > return dateValues Ok. This is roundabout, but you can do it. (Better simply to put dateValues in the module's global namespace, and get it by .dateValues directly.) It's the following I don't get: > numberValues = { ... > } > return numberValues That's all dead code (i.e., will never, ever be reached by the flow of execution.) Once you return once from a function, that's it... >chaldeanValues() So all the above line will ever return is dateValues. I never did much VB, but it either completely destroyed your mind, or you're approaching Python with the false assumption that it is far more magical and different than what you're used to. (It *is* magical and different, but it hasn't redefined the meaning of "function"...) Don't worry about modules for now; just stick to the basics. >I have another function called "def nameRoutine():" which calculates the numerical equivalent of >each letter in a name and I was going to import that function like this ... > >def nameRoutine(): > from chaldeanValues import dateValues Ah! Now I understand your confusion. I just told you not to worry about modules, but I'll break my own advice, since I see that this misconception is easy to fix. [There's a little bit of hand-waving in the following, but nothing you'll need to worry about.] The "import" statement only imports modules. Modules are a special type of object, which containes *names.* (It is not unique in that respect--every object in Python contains names. What's special about modules is that their code comes from separate files.) Module objects contain every name defined in the global space of that module's file. For example, I write a file, 'MyModule.py': --- MyModule.py --- myInt = 1024 def myfunc(): notglobal = 4021 return notglobal --- End --- I fire up Python: >>> import MyModule Now I can access any name in MyModule. Well, not *anything*: >>> MyModule.myInt 1024 >>> MyModule.myfunc() 4021 >>> MyModule.myfunc.notglobal Traceback... ... AttributeError: function 'myfunc' has no attribute 'notglobal'... It is this very property of containing names that makes modules handy, because they act as new global *namespaces*. A namespace is a collection of names. There are two kinds: local (which are used inside of blocks of code, like functions) and global (which are outside). When Python encounters a name, it looks for its value in the namespace. First it looks in the local namespace (i.e., above that point in the code, but inside the function) and if it can't find it there, it looks in the global namespace (i.e., outside the function, but not inside any other function.) Modules are neat because they have their own global namespace, which is global *to themselves*, but not *to the one who imports the module*. So any namespace that contains the name of the module, can access the contents of that module. You make *your* namespace contain the name of a module, by using 'import ', which means, "Put the name of this module in my namespace, so I can get to its namespace." Sometimes we don't really want everything in a module, but just one or two things. In such cases, we use 'from import ' 'Import' here still has the meaning of "put in my namespace", but this time you're extracting a name directly out of the module and placing it in the current namepace, instead of placing the whole module in the current namespace. Think of it as putting a screwdriver on your desk, instead of the whole toolbox. (That said, never use 'from x import y', and especially 'from x import *', which is like throwing the entire contents of your toolbox onto your desk. These two contribute to "namespace pollution", and generally lead to confusion and sloppy programming.) Let's look at your original lines again. >def nameRoutine(): > from chaldeanValues import dateValues What you're doing here is trying to import a local name from a function. So you've done two things wrong: you can only use 'from ... import' or 'import' statements with modules (which is why they're special), and you can't ever[1] import local names, only global names. Local names are only accessable from the inside, not the outside. You've also committed a style error of using an import statement in a local namespace. Generally speaking, you shouldn't do that, but put all your imports at the top of a file. Here's what you should do: --- chaldeanValues.py -- dateValues = {...} nameValues = {...} --- END --- --- Numerology.py --- import chaldeanValues #If that hurts your fingers, use: # #import chaldeanValues as cV def nameRoutine(): # here, if you need dateValues, get it with # the name "chaldeanValues.dateValues". # ... --- END --- If you don't have enough to warrant using a new module, use a class instead: --- Numerology.py --- class chaldeanValues: dateValues = {..} nameValues = {..} def nameRoutine(): # Get it with "chaldeanValues.dateValues", as above. --- END --- Classes are much more than mini-modules, of course, but you can use them that way if you need. An even higher-level concept is a package, which is a collection of modules. You don't need to know about this right now, but for the details see the very end of 6.12 in the Python Language Reference (also the url cited there). Packages are still module objects, however, even though they contain module names. -- Footnotes -- [1] Unless you're using dirty tricks. >and then check the key of say, December, and find out it equals 12 (for the birthday) and then check >the key of say, "o" and find out it equals 7. I guess I do need to go back and learn more about this >concept. You seem to understand dictionaries just fine, and you probably understood modules, too (just needed it spelled out for you), but you're starting to run into problems with names and namespaces. These are fundamental, grand, all-unifying concepts in Python, so it's good to get aquainted with them. In the future, when you start asking questions like "Why is this default list argument of my function being shared by everyone?!", we'll give you the "Names are not objects; names point to objects" lecture. :) -- Francis Avila From deets.nospam at web.de Fri Nov 21 06:23:49 2003 From: deets.nospam at web.de (Diez B. Roggisch) Date: Fri, 21 Nov 2003 12:23:49 +0100 Subject: jython lacks working xml processing modules? In-Reply-To: References: Message-ID: Jane Austine wrote: > I'm trying to parse an xml file with jython (not through java parsers > like xerces). > > I tried minidom in jython 2.1 and 2.2a but all failed. > > What can I do? The last resort would be using java parsers. Then how > can I use them like python xml parsers? It seems like javadom and > javasax has something to do, but I don't know how. There is a really goog xml toolkit wich even covers xslt and some other fancy stuff. Its called 4suite, and you can get it here: http://www.4suite.org/ One of the authors, Uche Ogbuji, has some tutorials on working with it on developerworks. Diez From pecora at anvil.nrl.navy.mil Fri Nov 7 14:32:55 2003 From: pecora at anvil.nrl.navy.mil (Louis Pecora) Date: Fri, 07 Nov 2003 14:32:55 -0500 Subject: Why does changing 1 list affect the other? References: <8ufjqvc24b7o1v0c32p2cpv7us32gtsdic@4ax.com> Message-ID: In article , "Cy Edmunds" wrote: > Try this: > > >>> x = 5 > >>> y = x > >>> print x is y > True > > y is second reference to the immutable value 5, not a copy. So the action is on the binding end? Only one 5 is created, but the x=4 following statement UNbinds x and rebinds it to '4', rather than changing the object. y remains bound to '5'. Did that come out right? Then for lists, when we do x[0]=4 we are NOT unbinding x, but rather just changing the object? Sounds like if we try harder we will get to the _binding_ actions of the '=' operator. Let me try harder right here (off the top of my head). So, let's see, we view '=' as a binding operation. x=list binds x to the list, but each list element is bound to something else (I refer to this as a second level binding). For lists we are allowed to change that second level binding. This second level action does NOT affect the first level y=x binding. Now, does that sound right? Anyone? -- Lou Pecora From godoy at ieee.org Sat Nov 22 06:45:33 2003 From: godoy at ieee.org (Jorge Godoy) Date: Sat, 22 Nov 2003 09:45:33 -0200 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <3FBB805D.40A8DA75@engcorp.com> <3FBBA68A.6D819C5C@engcorp.com> <7x8ymcp2eh.fsf@ruckus.brouhaha.com> <87y8ubw5lm.fsf@pobox.com> <87wu9utvuf.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) writes: > Jorge Godoy writes: > >> jjl at pobox.com (John J. Lee) writes: > [...] >> Sorry for my ignorance, but how do you get to decrypt the code to run? > > What code? Weren't you obfuscating Python code? Or did I read it all wrong? -- Godoy. From see_signature__ at hotmail.com Wed Nov 19 04:55:53 2003 From: see_signature__ at hotmail.com (Georgy Pruss) Date: Wed, 19 Nov 2003 09:55:53 GMT Subject: New Guy References: Message-ID: "Duncan Booth" wrote in message news:Xns943859F3B8551duncanrcpcouk at 127.0.0.1... | "Michael Geary" wrote in | news:vrm8hq74kdcsba at corp.supernews.com: | | > Is that the *exact* program? Nothing is indented | | I suggest you need to use a different newsreader program. The indentation | is present in the code from the OP, so it must have been stripped out by | Outlook Express. # OE test: if 1 is None: if str(2): print "OE" | | -- | Duncan Booth duncan at rcp.co.uk | int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" | "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From tzot at sil-tec.gr Mon Nov 3 20:30:43 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 04 Nov 2003 03:30:43 +0200 Subject: Please explain the meaning of 'stealing' a ref Message-ID: I invested some time today because I got this crazy idea that if I implemented a simple attribute-getting caching scheme implemented in PyObject_GetAttr / PyObject_SetAttr that would turn out to be good. So I did implement one touching Objects/object.c (and pythonrun.c for init/final purposes), and I got a 5% increase in pystone... of course, when I exited the interpreter, I got a nice segfault :-) Also, test.testall segfaulted at test_anydbm. I didn't expect anything better, to be honest; it's obviously got something to do with inc/dec refs. Now I'm googling for the various debug building options (I'm not sure that -DDEBUG is enough etc), however I realised it's time to ask what I never understood so far: what exactly is the meaning of a function "stealing a reference"? Is it that the function does an incref or a decref? Or is it something more obscure? TIA for any answers. PS Do we have still time to help Guido be the one that throws the pie?-) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From pclinch at internet-glue.co.uk Mon Nov 17 16:27:47 2003 From: pclinch at internet-glue.co.uk (Paul Clinch) Date: 17 Nov 2003 13:27:47 -0800 Subject: Tkinter uses a lot of memory?! References: Message-ID: <8cf2994e.0311171327.14a5e49e@posting.google.com> servantofthesecretfire at fea.st (ServantOfTheSecretFire) wrote in message news:... > Hi there, > > I wrote my first Python program this weekend, Conway's Game of Life, > and I used Tkinter for the graphics. I thought I had done something > wrong when I saw the memory consumption, so I wrote the simplest Tk > program I could, and yep, it takes about 40MB of memory! I'm using Red > Hat Linux 9.0 and recent versions of the software. Please look at the > output below, and tell me if I am confused... Wow! > ~/python: cat /etc/redhat-release > Red Hat Linux release 9 (Shrike) > Suse 8.2 > ~/python: rpmquery python > python-2.2.2-26 > rpm -qf $(which python) python-2.2.2-82 > ~/python: rpmquery tk > tk-8.3.5-88 > rpm -q tk tk-8.4.2-27 > ~/python: rpmquery tkinter > tkinter-2.2.2-26 > rpm -q python-tk python-tk-2.2.2-92 > ~/python: cat hello.py > #!/usr/bin/python > import Tkinter as Tk > root = Tk.Tk() > Tk.Button(text='Quit', command=root.quit).pack() > root.mainloop() > > ~/python: python hello.py & > [1] 25633 > > ~/python: ps u > USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND > sjm 23897 0.0 0.2 4980 1088 pts/0 S 12:18 0:00 -csh > sjm 25633 4.8 7.2 41576 37352 pts/0 S 22:35 0:00 python > hello.py pac 2947 1.6 2.1 11216 5556 pts/1 S 21:24 0:00 python > sjm 25634 0.0 0.1 2616 660 pts/0 R 22:35 0:00 ps u I suppose all can suggest is that you do a lsof | grep sjm and spent some time working out what shared libraries have been pulled in. Regards, Paul Clinch From brian at sweetapp.com Mon Nov 17 12:15:07 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 17 Nov 2003 09:15:07 -0800 Subject: looking for a name for a python SIP phone In-Reply-To: <740c1dd4.0311170849.78d29393@posting.google.com> Message-ID: <01be01c3ad2e$5af48120$21795418@dell8200> > so maybe "Parrot" or "Polly" would work. Parrot is taken :-) From Matteo.Risoldi at cern.ch Tue Nov 25 08:47:08 2003 From: Matteo.Risoldi at cern.ch (Matteo Risoldi) Date: Tue, 25 Nov 2003 14:47:08 +0100 Subject: command line arguments (newbie...) Message-ID: Hello, I could not find the answer to the following through a search, so I thought I could ask here. Thanks to everyone who would try and give a suggestion. In this program I did, I am parsgin command line arguments through the getopt.getopt function in the following way (note: try/except and other non-relevant stuff has been omitted for clarity). Note that thr "argv" parameter of main is actually sys.argv[1:]. def main(argv): opts, args=getopt.getopt(argv, "f:q:d:vro:t:h", ["file=","query=","database=","verbose","reformat","outfile=","tabulate=","h elp"]) .... .... for opt, arg in opts: if opt in ("-t","--tabulate"): separator=arg This lets me assign the parameter of the "-t" argument to the "separator" variable. Still, I would like to be able to use the "-t" argument with OR without a parameter, i.e. if I specify something after -t, it should go into "separator", but if I don't specify anything, "separator" should keep its default value (which is set elsewhere). Now, the problem is that with getopt.getopt, if I put "t:"in the option list, then I HAVE to put something after it; if I put only a "-t" on the command line, I get a getopt.GetoptError exception. I have tried putting both "t:" and "t" in the option list, but this won't work. At first I had thought about testing "if arg" and only then assigning a value to separator, but as I said the "-t" argument without parameters would not even be accepted. Any suggestion on how to achieve this? Thank you very much. Cheers. Matteo From wilkSPAM at OUTflibuste.net Wed Nov 19 06:01:27 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Wed, 19 Nov 2003 12:01:27 +0100 Subject: Python Database Objects (PDO) 1.2.0 Released References: <8rtgrvkl8vae90116u3opgdn2inias1ti4@4ax.com> Message-ID: <87znes1v20.fsf@blakie.riol#flibuste.net> "Jon Franz" writes: >> > while results.next(): >> > print "Name: " + results['Name'].value >> > print "Address: " + results['Address'].value >> > print "Size of 'Name' column in the db: " + > str(results['Name'].length) >> >> Why don't you use iterators for that? >> for result in mycon.open("SELECT * FROM Customers"): >> print ... > > Individual rows are not objects in PDO. Why did'nt you choose to make row and field objects ? -- Wilk - http://flibuste.net From SEE_AT_THE_END at hotmail.com Sat Nov 1 04:12:17 2003 From: SEE_AT_THE_END at hotmail.com (Georgy Pruss) Date: Sat, 01 Nov 2003 09:12:17 GMT Subject: Why I love Python: More rambling... References: <20031028061245.12451.00000133@mb-m01.aol.com> Message-ID: "Fernando Perez" wrote in message news:bnu7ck$aaa$1 at peabody.colorado.edu... > Alex Martelli wrote: > > > Ville Vainio wrote: > >> Another aspect of motivation is accomplishment - a thing that might > >> make a C++ programmer proud of his achievement seems like a trivial 15 > >> minute job for a Pythonista, and when that Pythonista is tasked w/ the > >> C++ job he doesn't get the kick from the accomplishment. And 6 hours > >> of debugging that "trivial" program doesn't help either. > > > > Yep. Managing to write even just "SPQR" with the marble and chisel > > without cracking the slab makes you proud (that Q is _so_ tricky!) -- > > with a word processor, or pen and paper, you'd get no kick from the > > accomplishment. And six hours of sandpapering and polishing that > > marble slab doesn't help either. > > Data point (real world, from a few weeks ago): after spending ~2 weeks (spread > over a month) writing about 1400 lines of C++, debugging a nasty coredump, and > pounding the documentation, I had my 'fast' extension module finished for some > numerical work. Great, sweaty and exhausted but all proud of myself, I turn > my attention to the problem of writing a unittest. I decided to write it in > python, since I figured it would be easier, and an independent implementation > of the algorithm (simple one) should suffice, if tested with enough random > data. > > Python code: 15 lines (no, it's NOT a typo: fifteen). Time to write it: 10 > minutes. > For a J programmer (www.jsoftware.com) it might as well be just a hundred characters and half an hour. Regards, G-: > The sad part (to my ego, at least:)? The python runs faster! The C++ version > is now in the dustbin. At least I learned a bunch about the STL and > templates. The consolation... > > Cheers, > > f. > > ps for those thinking: you must be an idiot of a C++ programmer. That may well > be true. But still, there are reasons for the difference. The C++ version > uses a heavily templated library for handling multidimensional arrays with a > bearable syntax, and g++ isn't the best compiler out there for that kind of > code. The python version relies on Numeric.innerproduct(), which is very well > optimized, and tackles head-on the problem I was avoiding with the templates, > namely very annoying pointer manipulations for multidimensional tensors. The > Numeric guys got their hands dirty, did it once RIGHT, and it works extremely > well. From rzantow at ntelos.net Sat Nov 15 09:19:57 2003 From: rzantow at ntelos.net (rzed) Date: Sat, 15 Nov 2003 09:19:57 -0500 Subject: Books I'd like to see References: Message-ID: <1068905986.987418@r02.usenetserver.com> I'd love to see a book (or series) on small-office systems based on Python: database interfacing, order-entry, printing and reporting, graphic display, communications -- with examples of how to use Python as the glue language it is often said to be, as well as how to use it in its role as a powerful processing language. And I'd like to jump on Nick Vargish's bandwagon as well. I love wxPython/wxWindows, but jeez, the documentation is terrible! -- rzed From k at k.com Mon Nov 3 05:02:49 2003 From: k at k.com (kk) Date: Mon, 03 Nov 2003 18:02:49 +0800 Subject: Parameters passing in Python Message-ID: When I learnt Java, I was told that for its primitive types, parameter passing is done by value. For objects, by reference. I started to learn Python months ago, but I still can't figure out the parameter passing style of Python. List, Dict, Object... When I search in mailing list, I found that someone raised the same question and someone responded Python uses 'pass by object'. Would anyone explain a bit more in detail? Thank you in advance. From buzzard at urubu.freeserve.co.uk Sat Nov 8 22:38:21 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sun, 9 Nov 2003 03:38:21 -0000 Subject: Nested for loop problem References: <3fad715f$0$58715$e4fe514c@news.xs4all.nl> Message-ID: "Don Low" wrote in message news:boju9f$1fgli4$1 at ID-145503.news.uni-berlin.de... > In article <3fad715f$0$58715$e4fe514c at news.xs4all.nl>, Irmen de Jong wrote: > > Don Low wrote: > >>>>>for x in range(2, 2): > >> > >> ... print x > >> ... > >> > >> Since x prints nothing, I guess x = NULL. If I try: > > > > That's your misunderstanding. That loop does *nothing*, > > it doesn't enter the loop body. When you're looping over > > an empty sequence, the loop body is never entered. > > OK, so python knows not to even bother going through the loop if the > range is []. > > > > (also, NULL is meaningless in Python. I think you meant > > None, right?) > > Yes, as in range(2, 2) yields nothing. > It doesn't return nothing; it returns an empty list. You *can* write a function that returns None. >>> def func(): return >>> a = func() >>> a is None True >>> Duncan From tchur at optushome.com.au Sun Nov 2 02:36:00 2003 From: tchur at optushome.com.au (Tim Churches) Date: 02 Nov 2003 18:36:00 +1100 Subject: Shelve operations are very slow and create huge files In-Reply-To: References: Message-ID: <1067758560.1188.16.camel@emilio> On Sun, 2003-11-02 at 03:38, Eric Wichterich wrote: > One script searches the MySQL-database and stores the result, the next > script reads the shelve again and processes the result. But there is a > problem: if the second script is called too early, the error "(11, > 'Resource temporarily unavailable') " occurs. The only reason to use shelves is if your query results are too large (in total) to fit in memory, and thus have to be retrieved, stored and processed row-by-row. > So I took a closer look at the file that is generated by the shelf: The > result-list from MySQL-Query contains 14.600 rows with 7 columns. But, > the saved file is over 3 MB large and contains over 230.000 lines (!), > which seems way too much! But that doesn't seem to be the case - your query results can easily fit in memory. However, the query may still take a long time to execute, so it may be reasonable to want to store or cache the results for further processing later. However, it is much quicker to just pickle (cPickle) the results to a gzipped file than to use shelve. The use of gzip actually speeds things up, provided that your CPU is reasonably fast and your disc storage system is mundane (any CPU faster than about 500 Mhz sees gains on most result sets). Also it saves disc space. Ole Nielsen and Peter Christen have written a neat set of Python functions which will automatically handle the caching of query results from an MySQL datadase in gzipped pickles - see http://csl.anu.edu.au/ml/dm/dm_software.html - except the files don't seem to be available from that page - Ole and Peter, please fix! -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From logan at phreaker.nospam Sat Nov 22 12:29:43 2003 From: logan at phreaker.nospam (Logan) Date: Sat, 22 Nov 2003 18:29:43 +0100 Subject: Python 3.0 Roadmap? Message-ID: Is there something like a roadmap for Python3 (i.e. v3.0)? IIRC, formerly people talked about Python 3000 resp. P3k and it was speculated, that Python3 will not be backwards compatible with Python2. Now I get the feeling, that many features (e.g. new style classes, iterators) are implemented in the 2.x branch to gradually prepare for Python3. (Some of Python's warts were also eliminated in the recent 2.2 and 2.3 versions.) So maybe Python3 will not be very different from its direct predecessor Python 2.x!? Does anyone have (up2date) links to information on Python3 plans, maybe a roadmap etc.??? (Could not find any decent information.) L. -- mailto: logan at phreaker(NoSpam).net From mis6 at pitt.edu Sun Nov 2 13:16:20 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 2 Nov 2003 10:16:20 -0800 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <87d6cjope5.fsf@pobox.com> <87he1vsopi.fsf@pobox.com> <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> <2259b0e2.0311012219.73aa445f@posting.google.com> Message-ID: <2259b0e2.0311021016.496105ea@posting.google.com> Stephen Horne wrote in message news:... > OK - but if you are describing superfluidity as a single macroscopic > effect then you must describe it within a macroscopic framework. At > which point it has nothing to do with quantum effects because it isn't > within a quantum framework - it is just that the macroscopic > phenomenon called electricity (distinct from electrons moving en > masse) is not subject to the macroscopic phenomenon called resistance > (distinct from energy loss through the electomagnetic interactions > between electrons and atoms en masse) when the macroscopic phenomenon > called temperature (distinct from the kinetic energy of atoms en > masse) is sufficiently low. > > There is nothing wrong with this per se - it is the limit of most > peoples (mine included) understanding of superconductivity - but it > has nothing to do with the framework of quantum mechanics. > I am sure I am misreading you again, but the equation is not microscopic=quantum, macroscopic=classical. It can be very well quantum=macroscopic. For instance, there is no classical theory able to describe superfluidity, it must be quantum. If I am misreading you again, let's say that I am doing this remark for the other readers here ;) Michele From cbrown at metservice.com Wed Nov 26 14:38:24 2003 From: cbrown at metservice.com (Colin Brown) Date: Thu, 27 Nov 2003 08:38:24 +1300 Subject: Extract double in binary file References: Message-ID: <3fc4fff2$1@news.iconz.co.nz> "Pascal" wrote in message news:e567c03a.0311260616.205efca0 at posting.google.com... > Hello, > > I've a binary file with data in it. > This file come from an old ms dos application (multilog ~ 1980). > In this application, a field is declared as a 'decimal' (999 999 > 999.99). > I put 0.00 in the field and save the record to the file. > When I look in the binary file (with python or an hex editor), the > field is stored on 8 bytes: 00-00-00-00-00-00-7F-00. > I try unpack from struct module but the result isn't good. > > Can someone help me? > > Thanks If the number is saved in a floating point representation (IEEE?), typically [sign][exponent][fraction] then you really need to know what the type is. For example, I had to make cross-platform real numbers at one stage and fabricated them as below. Colin Brown PyNZ import math def vmsR4(real): '''vmsR4(real): returns an integer that is equivalent to a VMS real*4 ''' (m, e) = math.frexp(real) if m == 0.0: return 0 else: sign = m < 0 exp = e + 128 mant = int((16777216L * abs(m)) + 0.5) - 8388608 return (sign << 15) + (exp << 7) + (mant >> 16) + (mant << 16) From webmistress_kimmy53 at yahoo.com Wed Nov 19 20:29:44 2003 From: webmistress_kimmy53 at yahoo.com (webmistress_kimmy53) Date: Thu, 20 Nov 2003 01:29:44 -0000 Subject: Date Gone Bad Message-ID: Have a horror story to share? Need a laugh? We have plenty of Documentation regarding this hillarious DATES GONE BAD. Read, write, comment, suggestions we have it all. Even some visual eveidence to back up the stories. http://www.AdultInternetMovies.com/landing.asp?afl=TYHO Some of the stories you read you just wont believe... like the story about the Athletic coach who tried to date his Athelete... oh just go read for yourself. From ark at acm.org Thu Nov 27 15:33:05 2003 From: ark at acm.org (Andrew Koenig) Date: Thu, 27 Nov 2003 20:33:05 GMT Subject: if - else References: <871xrtr8yb.fsf@pobox.com> Message-ID: <5ctxb.120283$Ec1.5141313@bgtnsc05-news.ops.worldnet.att.net> > True, also someone's being careless with their code. > > if SumOfNumbers = 10: > SumOfNumbers = 1 > > What happens with that? :) In Python? Easy -- it doesn't compile. From adalke at mindspring.com Tue Nov 18 19:40:05 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 19 Nov 2003 00:40:05 GMT Subject: syntax philosophy References: Message-ID: Tuang: > That use of Perl for one-liners, though, is why having them be easy, > automatic, and memorable matters. That's why I would prefer the same > convenience in anything I use to replace Perl for "Swiss Army knife" > use. I would apparently have to give up a bit of the convenience at > the one-liner level to buy the superior scaling (and other relative > benefits) of Python. One thing to consider is Python's interactive nature means you don't have to do everything as one-liners. For more complicated cases where I would have done a one-off one-liner I now start up Python and to things step-by-step. Python is *not* a good shell substitute, though PyShell does help a lot, judging from the demo I saw. > I find Perl's defaults to be right almost *all* of the time. That is true, but only works because of weak types and typed operations. > Increment a counter? Fine, $counter++ creates the counter if it > needs to be created, initializes it if it was just created, and then > increments it. And your use of ++ tells it to be a number. I agree that Perl puts a lot of flexibility into just a few characters. > On the rare occasions when I want it initialized to something > other than 0, I just initialize it myself, but the default > initialization of zero is right almost all the time for numbers, so > why not take advantage of that fact? It doesn't initilize to 0, I think it initializes to undef. It's only when you do ++ or += 1 where the undef gets converted into an integer. You can test it out by doing ' .= "X"' instead of ++. It should not start with a '0', which it would if the default value was 0. > Amen. But $hist{$word++} works beautifully. Especially if you typed it correctly ;) > Thanks. That perfectly explained the philosophy behind my example. You're welcome. Andrew dalke at dalkescientific.com From ulysses_dm at yahoo.com.cn Wed Nov 12 20:00:15 2003 From: ulysses_dm at yahoo.com.cn (ulysses) Date: 12 Nov 2003 17:00:15 -0800 Subject: can't run py app after compile to exe by py2exe , gettext References: <43e3984e.0311120110.2bea96cc@posting.google.com> Message-ID: <43e3984e.0311121700.1a7e642e@posting.google.com> I do a small test app for this. Still can't run. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #!/usr/bin/env python #Boa:App:BoaApp from wxPython.wx import * def setLan(): import gettext lan=gettext.GNUTranslations(open('en.mo')) lan.install() class BoaApp(wxApp): def OnInit(self): wxInitAllImageHandlers() setLan() self.main = wxFrame1(None) # needed when running from Boa under Windows 9X self.SetTopWindow(self.main) self.main.Show();self.main.Hide();self.main.Show() return True class wxFrame1(wxFrame): def __init__(self, parent): wxFrame.__init__(self, id=-1, name='', parent=parent, pos=wxPoint(193, 111), size=wxSize(505, 223), style=wxDEFAULT_FRAME_STYLE, title='wxFrame1') self.SetClientSize(wxSize(497, 196)) self.SetBackgroundColour(wxColour(192, 192, 192)) self.SetFont(wxFont(14, wxSWISS, wxNORMAL, wxNORMAL, False, 'Tahoma')) self.staticText2 = wxStaticText(id=2222, label=_('help me'), name='staticText2', parent=self, pos=wxPoint(72, 128), size=wxSize(336, 40), style=0) self.staticText1 = wxStaticText(id=3333, label=_('show text'), name='staticText1', parent=self, pos=wxPoint(72, 56), size=wxSize(320, 48), style=0) def main(): application = BoaApp(0) application.MainLoop() if __name__ == '__main__': main() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ full source package please download from http://211.90.187.42/ourbt/gettexttest.rar you test in in your computer. Thanks. Ulysses From edreamleo at charter.net Mon Nov 10 16:46:19 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Mon, 10 Nov 2003 15:46:19 -0600 Subject: Leo + Python: the ultimate scripting tool: gui issues References: Message-ID: I forgot to mention that Leo already has plugins that allow fairly easy integration with vim, xemacs and word. Another plugin allows full customization of Leo's Open With menu. These plugins aren't perfect, and they are a real good start. These plugins were easy to write. For example, the guts of the xemacs plugin is: def open_in_emacs (tag,keywords): if top(): top().frame.OnOpenWith(("os.spawnl",path,None),) Tighter integration with emacs/xemacs would take more work, and it would be well worth it. I hope that it will happen soon. The Aha for me came when I saw tetris in an xemacs window. xemacs probably can host Leo and make Leo look good. I see hints about "foreign" windows in the emacs docs, and I haven't followed up on that yet... Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From s011362 at student.dtu.dk Wed Nov 19 10:33:33 2003 From: s011362 at student.dtu.dk (Halfdan Holger Knudsen) Date: Wed, 19 Nov 2003 16:33:33 +0100 Subject: It's a bug!....but is it me or the script? (Global var assign) Message-ID: Hey here's a relatively simple question...the code is for a mock-up passwd, usrname dict storagesystem. Why doesn't the variable enc behave globally (the admin function turns up a "local var referenced before assignment" error, when inputting 's')? In all likelyhood I've just managed to stare myself blind, so to anyone w/ a spare pair of eyes - the help would be appreciated. It's run under Python 2.3.0 in Win2k. T/x H PS: I know it's long and I apologize, but basically it's just the first 8 lines that should matter. ----------------------------------- #!/usr/bin/env python import time import rotor passenc = rotor.newrotor('lockkey', 8) db = {} enc = 0 'Solution for exercise 7 a, b and c. Unresolved: Why is enc treated as global in newuser() but local in admin()?' def newuser(): prompt = 'login desired: ' while 1: name = raw_input(prompt) if len(name) < 3: prompt = 'name too short, try another: ' continue elif db.has_key(name): prompt = 'name taken, try another: ' continue else: break pwd = raw_input('passwd: ') # If admin has turned in encryption encrypt new pass. Unresolved issue regarding switching the feature on and off (conditional decrypt) if enc: pwd = passenc.encrypt(pwd) time1 = time.time() #creates the user w/ a name, pass and a timestamp for last login db[name] = [pwd, time1, enc] print name, db[name][0], db[name][1], db[name][2] def olduser(): name = raw_input('login: ') pwd = raw_input('passwd: ') passwd = db.get(name)[0] #Possible solution for conditional decrypt if db.get(name)[2]: passwd = passenc.decrypt(passwd) #checks if pass is good and updates timestamp (saves a copy for comparison) if passwd == pwd: chktime = db[name][1] time1 = time.time() db[name][1] = time1 #checks if last login is less than four hours ago if time1-chktime < 14400: print 'You already logged in at '+time.strftime('%H:%M',time.localtime(chktime)) pass else: print 'login incorrect' return print 'welcome back', name def admin(): prompt = """ (V)iew list of users (D)elete user account (S)et password encryption (Q)uit Enter choice: """ while 1: adchoice = raw_input(prompt) if adchoice not in 'vdqs': prompt = 'invalid choice, try again: ' continue elif adchoice == 'v': for eachkey in db.keys(): print 'user', eachkey, 'has password', db[eachkey][0] prompt = 'Enter new choice: ' continue elif adchoice == 'd': delusr = raw_input('User to remove: ') if db.has_key(delusr): del db[delusr] prompt = 'User deleted. Enter new choice: ' else: prompt = 'No such user. Enter new choice: ' continue elif adchoice == 's': if enc==1: enc = 0 print 'Encryption off' continue else: enc = 1 print 'Encryption on' continue elif adchoice == 'q': break def showmenu(): prompt = """ (N)ew User Login (E)xisting User Login (A)dministration (Q)uit Enter choice: """ done = 0 while not done: chosen = 0 while not chosen: try: choice = raw_input(prompt)[0] except (EOFError, KeyboardInterrupt): choice = 'q' print '\nYou picked: [%s]' % choice if choice not in 'aneq': print 'invalid menu option, try again' else: chosen = 1 if choice == 'q': done = 1 if choice == 'n': newuser() if choice == 'e': olduser() if choice == 'a': admin() if __name__ == '__main__': showmenu() From frr at easyjob.net Fri Nov 21 05:52:51 2003 From: frr at easyjob.net (Fernando Rodriguez) Date: Fri, 21 Nov 2003 11:52:51 +0100 Subject: extract the strings in an exe Message-ID: <1jrrrv4g350e4oft2hq7p8ukvrahj45jcf@4ax.com> Hi, How can I extract all the strings in an exe with python? O:-) From cjw at sympatico.ca Thu Nov 6 07:48:13 2003 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 06 Nov 2003 07:48:13 -0500 Subject: nearest neighbor in 2D In-Reply-To: <3FA8DF50.3050000@unileoben.ac.at> References: <3FA8DF50.3050000@unileoben.ac.at> Message-ID: <8qrqb.2807$143.147770@news20.bellglobal.com> This enquiry has generated a lot of interest. I thought it might be useful to try numarray on the problem. numarray has a compress function, which is used to discard points which are not of interest. The code is below. As would be expected, each scan over the points in the neigbourhood discards, on average, a little more than half the points. I have not tried it, but it should be possible, with numarray, to generalize this from 2D to multimimensional space. Colin W. # Neighbour.py ''' To find the closest neighbour, in a neghbourhood P, to a point p. ''' import math import numarray as N import numarray.numerictypes as _nt import numarray.random_array as R trial= 0 lengthRemaining= [] def find(P, p): ''' In the 2D neighbourhood P, find the point closest to p. The approach is based on the selection of a trial value Pt, from P, and discarding all values further than Pt from p. To avoid repeated sqrt calculations the discard is based on an enclosing square. ''' global lengthRemaining, trial lengthRemaining+= [[P.shape[0]]] Pz= P - p # zero based neighbourhood while len(Pz): Pt= Pz[0] # trial value Pta= N.abs(Pt) Pz= Pz[1:] pd= math.sqrt(N.dot(Pta, Pta)) # distance of p from the trial value goodCases= N.logical_and((Pz < pd), (Pz > -pd))# use the enclosing square goodCases= N.logical_and.reduce(goodCases, 1) Pz= N.compress(goodCases, Pz) # discard points outside the square if len(Pz) == 1: Pt= Pz[0] # We have found the closest Pz= [] lengthRemaining[trial]+= [len(Pz)] z= 100 trial+= 1 return Pt + p if __name__ == '__main__': for sampleSize in range(100, 5000, 100): P= R.random(shape= (sampleSize, 2)) for i in range(20): p= R.random((1, 2)) # point a= find(P, p) ## print 'Closest neighbour:', a[0] ## print 'Check - Point(p):', p[0] ## check= [] ## for i in range(len(P)): ## check+= [(math.sqrt((P[i, 0]-p[0, 0])**2 + (P[i, 1]-p[0, 1])**2), P[i, 0], P[i, 1])] ## print P[i], math.sqrt((P[i, 0]-p[0, 0])**2 + (P[i, 1]-p[0, 1])**2) ## check.sort() ## print check[0] ## print check print 'Number of scans:', sum([len(lst) for lst in lengthRemaining]) print 'Sample size:', P.shape[0], ' Average numner of scans:', sum([len(lst) for lst in lengthRemaining])/float(len(lengthRemaining)) WEINHANDL Herbert wrote: > John Hunter wrote: > >> I have a list of two tuples containing x and y coord >> (x0, y0) >> (x1, y1) >> ... >> (xn, yn) >> >> Given a new point x,y, I would like to find the point in the list >> closest to x,y. I have to do this a lot, in an inner loop, and then I >> add each new point x,y to the list. I know the range of x and y in >> advance. > > >> Can anyone point me to some code or module that provides the >> appropriate data structures and algorithms to handle this task >> efficiently? The size of the list will likely be in the range of >> 10-1000 elements. > > > The plotting-library dislin (http://www.dislin.com) > contains a really fast triangulation subroutine > (~1 hour for 700000 points on an 1.5 GHz Athlon). > > For an example triangulation/nearest-neighbor-search see > the attached python-script. > > Dislin is available for many platforms (Linux, Winxxx, ...) > and it can be used for free if you are using free languages like > Python, Perl, etc. > > Happy pythoning > > Herbert > > > ------------------------------------------------------------------------ > > #!/usr/bin/python > > # (c) by H. Weinhandl 04.Nov.2003 > > import math > import dislin > > > def dist( ia,ib ) : > return math.sqrt( (X1[ia]-X1[ib])**2 + (Y1[ia]-Y1[ib])**2 ) > > > def find_nearest_neighb() : > > print 'extracting neighbours ... ', > > for i in range( nr_dat+3 ) : > # initualize list wit the point i itself > neighb.append( [i] ) > > for i in range( nr_tri ) : > # get a indes-triple, dislin seems to start indices with 1, > # so I'm subtracting 1 to get a zero-based index > U,V,W = I1[i]-1, I2[i]-1, I3[i]-1 > > # add indices from all triangles, which contain the point itself > if ( U in neighb[U] ) : > if not (V in neighb[U] ) : neighb[U].append( V ) # do not append V if already in the list > if not (W in neighb[U] ) : neighb[U].append( W ) # do not append W if already in the list > > if ( V in neighb[V] ) : > if not (U in neighb[V] ) : neighb[V].append( U ) # do not append U if already in the list > if not (W in neighb[V] ) : neighb[V].append( W ) # do not append W if already in the list > > if ( W in neighb[W] ) : > if not (U in neighb[W] ) : neighb[W].append( U ) # do not append U if already in the list > if not (V in neighb[W] ) : neighb[W].append( V ) # do not append V if already in the list > > print ' OK' > for i in range( nr_dat ) : > neighb[i].remove( i ) # remove the point i itself > neighb[i].sort() > r_mi = 9.9e9 > i_mi = i > > # search for the nearest neighbor of point i > for j in neighb[i] : > r = dist( i, j ) > if r < r_mi : > r_mi = r > i_mi = j > print 'NB %2d : r_mi=%5.3f, i_mi=%2d '% (i, r_mi, i_mi), neighb[i] > > > > > if __name__ == '__main__' : > > X1 = [ 1.0, 2.0, 3.0, 4.0, 5.0, 4.0, 3.0 ] > Y1 = [ 1.0, 6.0, 3.0, 3.0, 2.0, 6.0, 0.0 ] > nr_dat = len( X1 ) > nr_max = 2 * nr_dat + 1 > I1 = [ 0 ] * nr_max > I2 = [ 0 ] * nr_max > I3 = [ 0 ] * nr_max > neighb = [ ] > > # padding the 2 input-lists with 3 additional elements is required by dislin > X1.append( 0 ) > X1.append( 0 ) > X1.append( 0 ) > Y1.append( 0 ) > Y1.append( 0 ) > Y1.append( 0 ) > > > # delaunay triangulation of the input lists > # I1,I2,I3 are the indices of the triangular edge-points > nr_tri = dislin.triang( X1,Y1, nr_dat, I1,I2,I3, nr_max ) > > print X1 > print Y1 > print nr_dat, nr_tri, nr_max > print I1 > print I2 > print I3 > > find_nearest_neighb() > > #---- end ---- From ville.spammehardvainio at spamtut.fi Wed Nov 5 06:59:47 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 05 Nov 2003 13:59:47 +0200 Subject: bash Vs python ?? References: <84fc4588.0311050214.4133e333@posting.google.com> Message-ID: pythonguy at Hotpop.com (Anand Pillai) writes: > bash vs python? > > Does it make sense to compare a rudimentary unix shell with > minimal capabilities to a powerful programming language > like python? I dont feel so. Some people's idea of optimization is selecting the worst tool that is tolerable for any particular tasl. That way, no tool feels neglected. If no language of "just right" amount of suckage is available at the moment, it needs to be implemented. -- Ville Vainio http://www.students.tut.fi/~vainio24 From jfranz at neurokode.com Tue Nov 18 14:15:10 2003 From: jfranz at neurokode.com (Jon Franz) Date: Tue, 18 Nov 2003 14:15:10 -0500 Subject: Python Database Objects (PDO) 1.2.0 Released References: <8rtgrvkl8vae90116u3opgdn2inias1ti4@4ax.com> <1ankrv4ieuncf20o9bhfsc1bamc0o5i4p0@4ax.com> Message-ID: <009401c3ae08$49b53690$7401a8c0@voidmk9> > I havent looked at the other DBAPI implementations lately, but with > MySQLdb you can set the cursor type to DictCursor, and then you get > back a sequence of dictionaries with the field names as the dict keys. This is true, but unfortunately it isn't standard behavior according to the DBAPI 2.0 spec (pep 249). Since it isn't standard, it seems everyone that does provide it in the module provides it a different way.- if they provide it at all. With PDO you get this functionality everytime, with no need to change your code when you switch databases and DBAPI modules to get it. Plus, PDO's implementation of acccess-by-name uses less memory than a sequence of mapping objects - excluding the case of very small (1-3 record) results, that is. I can exapnd upon how/why if people are curious. cheers. ~Jon Franz NeuroKode Labs, LLC From stephen at dino.dnsalias.com Wed Nov 5 03:21:14 2003 From: stephen at dino.dnsalias.com (Stephen J. Bevan) Date: Wed, 05 Nov 2003 08:21:14 GMT Subject: Explanation of macros; Haskell macros References: <87brs2tjut.fsf@memetrics.com> Message-ID: "Coby Beck" writes: > Here's a nice example from some production code I wrote that is easy to > grok. I follow it to a certain extent but the problem now is that we are given a solution with together with an explanation of what it does, but we don't know all the details of the problem that shaped the solution. Therefore while it is possible to agree that the macro version obviously hides a lot of detail, it isn't entirely clear if that is the best way to hide it or even if that detail is required. I'm not asking you to give the full requirements for your program, only explaining why if it isn't clear what the problem is then nobody can easily tell if the macro-based solution is an improvement over anything else. For example, if the commands have any kind of grammar then solution is to define the grammar and let a parser generator take care of parsing and building an AST. Whether the parser generator is an extension of the language (as is possible in Lisp and Forth) or a separate language (most other languages) is to a certain extent an implementation detail. At the other extreme is a simple flat file that is processed by an AWK program to generate source in the target language. To someone used to using macros, the AWK approach looks like a really poor substitute for a subset of what macros can do and it is from that perspective. However, the AWK route is also an approach that can solve a lot of simple problems, probably even the one you solved using macros. Note I'm not going to argue that it any solution using AWK is *better* than using a macro based solution, only that to sell macros to someone using the AWK approach the pitch has to convince them that the macro approach is significantly better in order to be worth investing the time and effort to learn. What constitues "significant" obviously varies. From bkc at Murkworks.com Thu Nov 20 12:10:24 2003 From: bkc at Murkworks.com (Brad Clements) Date: Thu, 20 Nov 2003 12:10:24 -0500 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: <7N6dnUz1P9CKZTOiRVn-hQ@comcast.com><3FBA3FDA.C5385A9C@engcorp.com> Message-ID: _ "Terry Reedy" wrote in message news:vvCdnWylDZ8CeyaiRVn-hQ at comcast.com... > The above is a paraphrase designed to expose the essence of what I see > as an oddity. The key words 'acceptable' 'reason' are direct quotes > from the original message, which I quoted in full in my original > message (Nov 9, when I very briefly stated my objection reason). Here > is the response message again.. > > ---""" > You recently sent a message to me at the email address > edreamleo at charter.net. To help cope with the ever increasing volume of > junk e-mail, I am using ChoiceMail, a permission-based e-mail > filtering tool. Your original e-mail is being held by ChoiceMail until > you complete the following simple one-time process. > Please click on the link > [Click here to request approval] > When your browser opens, fill in your name and a short reason for > wanting to send e-mail to me. If your reason is acceptable, your first > email and all subsequent e-mails from you will be delivered to me > normally. > """--- Ah, how interesting I hardly noticed the "if your reason is acceptable". Hmm, I'd consider this more of a failing of the english language. I didn't take it literally to mean "if I deign to speak to you on this subject" but rather to mean "if you're not sending me spam". > We may, of course, disagree on the importance of these even if we > agree that they are accurate. Yes, I think it's a matter of degree. Well, I understand what you're saying now. I guess I didn't read that much into his 'reason is acceptable'. I do think the web response is a pita compared to email, but I wanted a response bad enough to do it. I can't say the same would be true for everyone else. From exarkun at intarweb.us Mon Nov 10 15:15:02 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 10 Nov 2003 15:15:02 -0500 Subject: Blocking readline() Call? In-Reply-To: References: Message-ID: <20031110201502.GA10537@intarweb.us> On Mon, Nov 10, 2003 at 11:59:42AM -0800, Scott Brady Drummonds wrote: > Hi, everyone, > > I'm just figuring Python out but have become stalled with the following > snippit of code: For some reason, the program stalls after the "read line: > x" for the last line. The 'done reading cycle map' message is never > generated: > > while 1: > line = file.readline() > if line == '': > continue I think you mean "break" here, not "continue". > data = line.strip().split(':') > cycleMap[int(data[0])] = int(data[1]) > i = i + 1 > print ('read line %d' % i) > file.close() > print ('done reading cycle map') Another way to write this loop would be: for line in file: ... Jp From martin at v.loewis.de Wed Nov 5 14:27:59 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 05 Nov 2003 20:27:59 +0100 Subject: unichr() question References: Message-ID: "Ezequiel, Justin" writes: > I am converting XML files with entities to utf-8 using a lookup table: > > ⏞ 0FE37 > ⏟ 0FE38 > O 1D4AA The last one is not an XML entity reference, of course. Also, you are not converting to UTF-8, atleast not in this table - you convert to Unicode code points. > I have no idea what I am doing but I sure think that I absolutely > need it. If you eventually need UTF-8, you might just as well create a mapping table that translates to UTF-8. > Can you explain more on non-BMP characters (and Python's > capabilities to represent these) and how it applies (if it does) to > my needs? Well, the BMP (basic multilingual plane) is the first 65536 characters of Unicode. Recent Unicode revisions added characters beyond the first 64k, for characters rarely used; the MathML characters got allocated there as well. Python traditionally was using a two-byte type to represent Unicode, so it cannot represent characters outside the BMP, atleast not in Unicode strings of length 1. If you compile Python with --enable-ucs4, you can readily represent all these characters. If you have only UCS-2, you need two-character surrogate pairs to represent non-BMP characters; this is called UTF-16. If you want to learn more about UTF-16, see http://www.wikipedia.org/wiki/UTF-16 http://www.faqs.org/rfcs/rfc2781.html Python supports UTF-16 in the following contexts: - encoding and decoding surrogate pairs in the UTF-8 codec - representing surrogate pairs as a single \U unicode string escape sequence. Other aspects of UTF-16, such as distinguishing between the length of a string in code points vs. the length of the string in code units are not considered. Regards, Martin From max at cNvOiSsiPoAnMtech.com Fri Nov 14 14:49:16 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Fri, 14 Nov 2003 19:49:16 GMT Subject: python STL? Message-ID: <0latb.95267$ri.14418352@twister.nyc.rr.com> Hi, being recently introduced to the joys of programming in a powerful dynamic language (go snake!) I periodically rethink which parts of C++ I still miss. One thing I really enjoy is the generics of C++ - i think they are the single strong benefit of a strongly typed system. I was wondering about the possibility of implementing STL-like algorithms in Python and the one thing that I cannot think of doing without a kludge is the object comparsion that so much of STL relies on, which in turn relies on types and function(<) overloading. Is there a way to implement something similar in python (short of multimethods?). How does the python dictionary object allow arbitrary key types? Is in internally using the references' addresses to impose the tree ordering? thanks, max. From gumuz at looze.net Tue Nov 4 10:32:40 2003 From: gumuz at looze.net (Guyon Morée) Date: Tue, 4 Nov 2003 16:32:40 +0100 Subject: UserDict question References: <3fa7b8c4$0$259$4d4ebb8e@news.nl.uu.net> Message-ID: <3fa7c52a$0$251$4d4ebb8e@news.nl.uu.net> Thanks, this is exactly what I wanted to know. "Alex Martelli" wrote in message news:ASOpb.411624$R32.13653684 at news2.tin.it... > Guyon Mor?e wrote: > > > Hi all, > > > > I am using the UserDict baseclass and I want to add a __init__ to it to > > set up some initial values. > > > > my question is: do I have to run UserDict.UserDict.__init__ before doing > > anything else? > > The normal way to proceed is indeed to call your base class's __init__ > before proceeding, yes. > > > as in: > > > > class myClass(UserDict.UserDict): > > def __init__(self): > > UserDict.UserDict.__init__ (self) > > self.value = 1 > > If you don't want to support myClass being called with arguments > in order to initialize its instances to non-empty dictionaries, > this may indeed be sufficient. > > > > it seems so easy, but somehow i don't really grasp it... what do i have to > > do? > > If you also want to support optional arguments, you'll code something like: > > class myClass(UserDict.UserDict): > def __init__(self, adict=None, **kwargs): > UserDict.UserDict.__init__ (self, adict, **kwargs) > self.value = 1 > > in order to accept such optional args and pass them on to UserDict > for initialization. But, if you want to myClass to be always > called without arguments (all its instances start out empty) then > the code you wrote above is indeed correct. > > > Alex > From reply.in.the.newsgroup at my.address.is.invalid Fri Nov 14 10:01:53 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 14 Nov 2003 16:01:53 +0100 Subject: Function reference -> name? References: <2lo9rvsob1ejjju20ut308temf0p8l0gbo@4ax.com> Message-ID: Emile van Sebille: >Rene Pijlman: >> When I have a reference to a function, how can I get the name of that function? [...] >>>>>>> dir (f1) Of course. I forgot to mention that the function reference is an XML-RPC client stub, which makes quite a difference :-) dir() told me I need functionReference._Method__name in that case. Thanks Emile and Duncan. -- Ren? Pijlman From nicolas.lehuen at thecrmcompany.com Thu Nov 20 12:38:09 2003 From: nicolas.lehuen at thecrmcompany.com (Nicolas Lehuen) Date: Thu, 20 Nov 2003 18:38:09 +0100 Subject: Suggestion for a new regular expression extension Message-ID: Hi Skip, Well, that's what I am doing now, since I cannot hold my breath until my suggestion gets implemented :). But in my case, it forces me to duplicate each alternative in the big regexp in my normalisation function, which causes quite tedious maintenance of the whole piece of code. It would feel pretty much more natural just to say to the RE engine "if you match B(?D|LD|VD|OUL(?:EVARD)) within this big ugly regexp, just return me BD, please". Anyway, I think I'm going to try using sre.Scanner, we'll see if it's stable enough for that. I'll build 3 scanners that I'll call in sequence (each one reusing the part of the string that was not scanned, handily returned in the second part of the returned sequence of the 'scan' method) : - one for the number (or numbers) within the street : "14", or numbers like "14-16" or "14/16" or whatever separator the person entering the address could imagine. - one for the number extension : "B" or "BIS", "T" or "TER" or "TRE" (misspelled, but that's the way some people write it...) - one for the street/place type : most of the tricky regexp are there, most of the rewriting will be performed by actions defined in the Scanner's lexicon - and the rest of the string is the street/place name. This way the address will be processed in one pass without code duplication. But still, this (?PR<...>...) notation would be handy. I had a look at the sre source code, in hope that I would be able to implement it myself, but it's a bit too much for me to handle right now ;). Regards, Nicolas "Skip Montanaro" a ?crit dans le message de news:mailman.931.1069347639.702.python-list at python.org... > Nicolas> re_adresse = re.compile(r''' > ... [big, ugly re snipped] ... > Nicolas> ''',re.X) > > Nicolas> Note for example the many abbreviations (correct or not) ouf > Nicolas> "boulevard" : BD, BLD, BVD, BOUL, BOULEVARD. For normalisation > Nicolas> purposes, I need to transform all those forms into the only > Nicolas> correct abbreviation, BD. > > Nicolas> What would be really, really neat, would be a regular > Nicolas> expression extension notation that would make the RE engine to > Nicolas> return an arbitrary string when a substring is matched. > > Why not just use named groups, then pass the match's groupdict() result > through a normalization function? Here's a trivial example which > "normalizes" some matches by replacing them with the matched strings' > lengths. > > >>> import re > >>> pat = re.compile('(?P
a+)(?Pb+)') > >>> mat = pat.match("aaaaaaaabbb") > >>> def norm(d): > ... d['a'] = len(d['a']) > ... d['b'] = len(d['b']) > ... > >>> d = mat.groupdict() > >>> d > {'a': 'aaaaaaaa', 'b': 'bbb'} > >>> norm(d) > >>> d > {'a': 8, 'b': 3} > > Skip > From jay at jaydorsey.com Thu Nov 6 13:23:49 2003 From: jay at jaydorsey.com (Jay Dorsey) Date: Thu, 06 Nov 2003 12:23:49 -0600 Subject: return multiple values from fuction In-Reply-To: References: Message-ID: <3FAA91B5.2000803@jaydorsey.com> Lupe wrote: > hi, if someone can help me I would be grateful > > when I do > > def function > kjklj > llkl? > > return variableA, variableB > > how can I assign the two return values to two distinct variables, as for ex. > > varC = variableA > varD = variableB > >>> def a(): ... return "value 1", "value 2" ... >>> c, d = a() >>> c 'value 1' >>> d 'value 2' >>> e = a() >>> e ('value 1', 'value 2') HTH Jay From peter at engcorp.com Tue Nov 11 11:24:45 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Nov 2003 11:24:45 -0500 Subject: threads References: Message-ID: <3FB10D4D.8C7439CA@engcorp.com> Zunbeltz Izaola wrote: > > I have create two threads (from threading module). I want to > synchronize this two in the folowwing way > > def Threa1func(): > do stuff.. > while something > if test: > CHANGE TO Thread2 > do stuff... > > def Thread2func(): > do stuff ... > CHANGE TO Thread1 > > Thread1 = threading.Thread(target=Thread1func) > Thread2 = threading.Thread(target=Thread2func) > > them i've started this two threads > > Thread1.start() > Thread2.start() > > I want to know if it is posible to do this CHANGE of threads. Not exactly, or yes, depending on what you really want to do. Can you describe the problem in different terms, without reference to actual Python code or the threading module? It's not at all clear that you really want to use threads for your problem, and if you do, you are looking for a different concept than "CHANGE"... maybe semaphores or something. -Peter From nicholas_wieland at y_a_hoo.it Tue Nov 18 03:30:18 2003 From: nicholas_wieland at y_a_hoo.it (Nicholas Wieland) Date: Tue, 18 Nov 2003 08:30:18 +0000 (UTC) Subject: Unit Testing Examples References: Message-ID: - Tom Verbeure : > snip > What I'm looking for is some examples, existing open source projects > that make heavy use of unit testing. I'd like to see a real life > example about how those tests are structured and how the complexity of > these tests expands from object level to system level. IMHO Twisted Matrix is a good example. www.twistedmatrix.com -- __Nicholas Wieland Errors should never pass silently. Unless explicitly silenced. __The Zen of Python From newsgroups at jhrothjr.com Tue Nov 11 07:02:23 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 11 Nov 2003 07:02:23 -0500 Subject: Pruss Manifesto - Long numbers References: <87he1bdbdk.fsf@pobox.com> Message-ID: "John J. Lee" wrote in message news:87he1bdbdk.fsf at pobox.com... > "John Roth" writes: > [...] > > However, if you do, I'd be much more inclined to support > > the idea of writing them the way everyone else does: > > with commas and periods. That, at least, has the advantage > > of being familiar to people, and it can be supported with > > string notation: e"6,882.56" could be implicitly converted > > to a float by the compiler. > > Not everyone does write numbers like that. In Germany, IIUC, dots and > commas are reversed: 6.882,56. Quite true. I didn't elaborate the suggestion to cover that (and some other cases like spaces in the number) because I don't think it really matters. > > On balance, I doubt if I'd like to see that, though. It > > just doesn't seem useful enough. > > Agreed. Michele is right -- it's easy to do this with a string. > > > John John Roth From aleaxit at yahoo.com Sat Nov 8 12:24:03 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 08 Nov 2003 17:24:03 GMT Subject: reduce()--what is it good for? References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> Message-ID: Anton Vredegoor wrote: > anton at vredegoor.doge.nl (Anton Vredegoor) wrote: > >> def factorial(x): >> b = _Memo.biggest >> if x > b: return reduce(mymul, xrange(b+1,x+1), b) >> return _Memo.facdict[x] > > Sorry, this part should be: > > def factorial(x): > b = _Memo.biggest > if x > b: > start = _Memo.facdict[b] > return reduce(mymul, xrange(b+1,x+1), start) > return _Memo.facdict[x] The horrid complication of this example -- including the global side effects, and the trickiness that made even you, its author, fall into such a horrid bug -- is, I think, a _great_ testimonial to why reduce should go. I would also include in this harrowing complexity the utter frailty of the (textually separated) _Memo / mymul coupling, needed to maintain _Memo's unstated invariant. This code is as close to unmaintainable, due to complexity and brittleness, as Python will allow. I will gladly concede that reduce IS hard to beat if your purpose is to write complex, brittle, hard-to-maintain code. Which is exactly why I'll be enormously glad to see the back of it, come 3.0 time, and in the meantime I heartily suggest to all readers that (like, say, apply) it is best (_way_ best) avoided in all new code. Alex From ameLista at telia.com Sun Nov 16 12:20:22 2003 From: ameLista at telia.com (Anders Eriksson) Date: Sun, 16 Nov 2003 17:20:22 GMT Subject: Running Gramps on Windows? Message-ID: <14u2i5r2uev3e.1vce72mkkz8cw$.dlg@40tude.net> Hello! I wonder if there's anyone that has been able to run Gramps on Windows 2000? The trick, as far as I can tell, is to get a windows version of Gnome. Anyone that can recommend a Gnome windows version. It has to be verson 1.2 or later. // Anders From reply.in.the.newsgroup at my.address.is.invalid Fri Nov 14 09:14:30 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 14 Nov 2003 15:14:30 +0100 Subject: Function reference -> name? Message-ID: <2lo9rvsob1ejjju20ut308temf0p8l0gbo@4ax.com> When I have a reference to a function (as in parameter 'function' of f1 below), how can I get the name of that function ('f2' in the example below)? def f1(function): pass # How to get 'f2' from function? def f2(): pass f1(f2) -- Ren? Pijlman From bokr at oz.net Thu Nov 20 14:01:20 2003 From: bokr at oz.net (Bengt Richter) Date: 20 Nov 2003 19:01:20 GMT Subject: Analyse of PDF (or EPS?) References: <3fbcc67e$0$9836$edfadb0f@dread14.news.tele.dk> Message-ID: On Thu, 20 Nov 2003 14:48:52 +0100, Johan Holst Nielsen wrote: >Hi, > >Is there any Python packages to analyse or get some information out of >an PDF document... > >Like where the text are placed - what text are placed - fonts, embedded >PDFs/fonts/images etc. > >Please let me know :) > IIRC you can get the full specs of pdf and eps at the adobe site. Some stuff is easy to get at, some may be compressed and/or encrypted, and not so easy. Conforming docs are supposed to be structured so that it is relatively easy to grab chunks of document and do the kinds of things printing business s/w does, like rotating and scaling and reordering pages, etc. There are whole books on pdf and postscript also, which you could browse at a good tech book store or tech library. Regards, Bengt Richter From aleax at aleax.it Wed Nov 12 07:21:29 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 12 Nov 2003 12:21:29 GMT Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> <%Fcsb.10225$hV.422723@news2.tin.it> Message-ID: David Eppstein wrote: ... >> Wen seq is any iterable, all you need is izip(seq, islice(seq, 1, None)), >> and you'll be creating no new list whatsoever. Still, tradeoffs in >> obscurity (and performance for midsized lists) are quite as clear. > > If I'm not mistaken, this is buggy when seq is an iterable, and you need Sorry, I should have said something like "re-iterable" -- an object such that e.g.: it1 = iter(seq) val1 = it1.next() it2 = iter(seq) val2 = it2.next() assert val1 == val2 holds (and keeps holding as you keen next'ing:-). list, tuple, dict, etc. In particular, when the idiom zip(seq, seq[1:]) works, so should this one (note in passing that, in said idiom, there is no need to slice the first seq in the zip call to seq[:-1] -- zip truncates at the end of the _shorter_ sequence anyway). > to do something like > seq1,seq2 = tee(seq) > izip(seq1,islice(seq2,1,None)) > instead. Yes, this is totally general. However, even though tee has now (2.4) been implemented very smartly, this overall approach is still way "conceptually heavy" (IMHO) when compared to, e.g.: def window_by_2(it): it = iter(it) first = it.next() for second in it: yield first, second fist = second in any case, I do think that such 'windowing' is a general enough need that it deserves its own optimized itertool... Alex From jjl at pobox.com Mon Nov 3 17:40:07 2003 From: jjl at pobox.com (John J. Lee) Date: 03 Nov 2003 22:40:07 +0000 Subject: programming languages (etc) "web popularity" fun References: <1b0569eff1ff540df7b1bf4ad2d5da1f@news.teranews.com> Message-ID: <874qxl9iuw.fsf@pobox.com> Alex Martelli writes: > Dang Griffith wrote: > > > Any chance of seeing PowerBuilder in the list? > > Sure -- goes near the end of the current list of 31 languages, with > about helf the hits of Ruby or smalltalk, but over twice as many as > caml of all sorts: > > matlab 104000 > smalltalk 91300 > ruby 90000 > powerbuilder 49500 > caml OR ocaml OR "o'caml 19500 How about Mathematica (or Maple)? too-lazy-to-find-my-google-key-ly y'rs, John From __peter__ at web.de Sun Nov 9 16:23:15 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 09 Nov 2003 22:23:15 +0100 Subject: sharing dictionaries amongst class instances References: Message-ID: Kerry Neilson wrote: > Hi, > Really hung up on this one. I'm trying to get all the fields of a > dictionary to be unique for each class: > > class A { > my_dict = [] > dict_entry = { 'key1':0, 'key2':0 } > > __init__(self): > for x in range(10): > tmp = copy.deepcopy(self.dict_entry) > tmp['key1'] = x > self.my_dict.append(tmp) > } class A { ... } is *not* Python. Are you converting from Java :-) ? >From what follows, I conclude that you want the dicitonary to be unique for each *instance* (if you want it unique for the class, you are already there). Unlike Java, you must put it in the constructor then (untested): class A: def __init__(self): self.my_dict = {"key1": 0, "key2": 0} Dictionaries are the {} thingies, [] indicate list literals. Deepcopy should be buried very deep in the documentation, where no newbie will ever find it... Seriously, take the time to read the excellent tutorial that comes with Python, and only then try to clean up this mess. Peter From mis6 at pitt.edu Fri Nov 14 00:51:32 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 13 Nov 2003 21:51:32 -0800 Subject: a python book hint References: Message-ID: <2259b0e2.0311132151.1f21444@posting.google.com> claird at lairds.com (Cameron Laird) wrote in message news:... > I've been writing and rewriting a review of *TPIP* since (before?) its > publication (to David's frustration--it'd be better for him if I just > published *something* about it, rather than reworking so much). *I* > don't think it's for beginners, and in fact I think it's going to lose > a lot of the current crop of professionals. I like the book, but I > think it's too demanding for many of the people who might consider it. > > I've been surprised, though, how much enthusiasm it's inspired already > in readers I've encountered. > > My conclusion: I solicit others' views and experience. too demanding ??? A book can be too demanding when it requires the reader to follow a too hard path, meaning that there is an easier, maybe longer, but equivalent path; but a text that take a not-so-trivial matter as text processing and make it as simple as it can be, is not at all too demanding. It is just the opposite! One cannot pretend to learn text processing without a minimal effort, unless he limits himself to a very superficial study; I found David's text really good in the sense of being not more difficult than needed, not too much "academic" but also not too much "practical" (here "practical" means giving a set of practical recipes without any better understanding behind). Alex was right not to cite this book to the OP, since it is NOT a text for Python beginners; actually, in my view, it is not a Python book at all. It is a book on *text processing*: the fact that the chosen language is Python is somewhat secondary, the same concepts could have been expressed in any other language (even if not as well as in Python, of course ;). TPiP is a good book for someone who wants to understand (some of) the theory behind text processing, as well as the practice (I value very much the practice, only I think it should not be disconnected from the theory). It is not a reference book, nor a book of recipes: it is kinda of a textbook. IMO, it is especially suitable to "non-canonical" programmers, people without a computer science background, which still need or want to learn something about parsers, state machines and all the rest, without going trough a real CS course. David is well qualified to understand what are the likely gaps of non-canonical programmers, since himself has a background in philosophy, not in CS and it is clear he learned what it is in his book through self-study (David correct me if I am wrong). OTOH, people with a CS background often give a lot of things for obvious (who said 'reduce' was obvious ?;) which are not obvious to us "amateur" programmers, so they are less effective as teachers (outside academia, I mean). BTW, I read TPiP when it was in fieri, before starting my collaboration with David, so my opinion on the book is not affected by my following work with him (actually the opposite is true). Michele Simionato P.S. I could say equally positive things both for the cookbook and "Python in a nutshell", they are *really* good books, but they are *different* books: they cannot be put in the same category as TPiP, just because they share the word "Python" in the title. The same for "Dive into Python" and "Thinking as a computer scientists": they are all excellent books, but they have different scope and aims. From aleax at aleax.it Thu Nov 6 15:24:52 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 06 Nov 2003 20:24:52 GMT Subject: return multiple values from fuction References: Message-ID: Lupe wrote: > hi, if someone can help me I would be grateful > > when I do > > def function this needs of course to be def function(): > kjklj > llkl? > > return variableA, variableB > > how can I assign the two return values to two distinct variables, as for > ex. > > varC = variableA > varD = variableB "just do it": varC, varD = function() Alex From FBatista at uniFON.com.ar Wed Nov 12 12:06:22 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 12 Nov 2003 14:06:22 -0300 Subject: a python book hint Message-ID: Eduardo Patto Kanegae wrote: #- so, my question finally is: what book could be for a Python #- beginner - but NOT a programming beginner - which intends to #- develop *windowed* Python programms and intends to develop #- for Windows and for Linux? *My* recomendation is first to start programming in Python, then go GUI. For Python specifically, I think the best "learning roadmap" is: 1. The basic tutorial: http://www.python.org/doc/current/tut/ 2. Dive into Python: http://diveintopython.org/ You may want to read this (short) page: http://www.python.org/topics/learn/, where answers your question less subjetivally. Then, for GUI, you need to choose on what you will work: Tkinter, GTK+, QT, wxWindows, etc... Each one has its advantages and disadvantages, you must specify your needs if want some help there. And always, of course, post your questions to the list! . Facundo From evan at 4-am.com Fri Nov 21 11:47:32 2003 From: evan at 4-am.com (Evan Simpson) Date: Fri, 21 Nov 2003 10:47:32 -0600 Subject: Using an interable in place of *args? In-Reply-To: References: Message-ID: <3FBE41A4.30308@4-am.com> Nick Vargish wrote: > def pack(self): > # need some way to call struct.pack with a list/tuple of values > # built with [ self.__dict__[v] for v in self.fields ] > pass Shouldn't this work? struct.pack(*tuple([ self.__dict__[v] for v in self.fields ])) Cheers, Evan From martin at v.loewis.de Tue Nov 4 16:39:41 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 04 Nov 2003 22:39:41 +0100 Subject: Memory leak in python-2.2.3 on solaris? References: <6205cf4c.0311040750.461213e9@posting.google.com> Message-ID: edahl at mindspring.com (Erwin Dahl) writes: > - is this really a leak in python (or one of its libraries)? Without seeing the source code, nobody can tell. > - if gettotalrefcount() stays the same it must be a C level leak, > correct? If it is a leak: yes. > - if so what is the best way to figure it out? Add a breakpoint on malloc, and find out what its callers are. > I'm on solaris 2.8 and python is built with gcc 3.2.2. The program > doesn't use many libraries the ones that I haven't been able to pull > when debuging are socket and select so I suspect them. You might want to incorporate them statically into Python, by modifying Modules/Setup. Regards, Martin From eppstein at ics.uci.edu Mon Nov 24 19:05:51 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 24 Nov 2003 16:05:51 -0800 Subject: Bug or Feature? References: Message-ID: In article , "Delaney, Timothy C (Timothy)" wrote: > > From: David Eppstein > > > > It is very useful that ImmutableSet is closed under set operations. > > By making the set operations copy the types of their arguments, the > > author of sets.py was able to achieve this without > > duplicating each set > > operation's implementation. If you don't like this behavior you can > > always override it... > > So what happens when I make a set subclass that takes no parameters (other > than self) to init ? What do you expect to happen in general when you define a class that does not adhere to some protocol, and then use it in that protocol anyway? >>> import sets >>> class FunkySet(sets.Set): ... def __init__(self): ... sets.Set.__init__(self) ... >>> f=FunkySet() >>> f.add(1) >>> g=FunkySet() >>> g.add(2) >>> g.add(3) >>> f&g Traceback (most recent call last): File "", line 1, in ? File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/s ets.py", line 205, in __and__ return self.__class__(common) TypeError: __init__() takes exactly 1 argument (2 given) -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From ConfuseYourSpamBot-parzp at ConfuseYourSpamBot.shaw.ca Sat Nov 8 15:21:04 2003 From: ConfuseYourSpamBot-parzp at ConfuseYourSpamBot.shaw.ca (Parzival) Date: Sat, 08 Nov 2003 20:21:04 GMT Subject: mmap file won't open properly with Linux Message-ID: I have a program which works well on under Windows, which I am trying to get to work under Linux (Mandrake 9.1) It accesses a binary file with mmap. Under Windows, the file maps and reads withut porblems, but under linux an attempt to access the mapped data fails with a cryptic error message. I thought that perhaps the file was corrupted, so I recreated it in my Linux environment and examined it with a hex editor, and it appears to be perfect. The mmap call does not raise an exception, so how can the subsequent access to the fail? Traceback (most recent call last): File "./ACSatlasBuilder.py", line 292, in ? acs.writeAll(limit=None) File "./ACSatlasBuilder.py", line 45, in writeAll header += self.writeLocations(fin, fout, limit) File "./ACSatlasBuilder.py", line 65, in writeLocations ACS = Tz.TzDatabase("ACStt.dat") File "/home/parz/xAtlas/Tz.py", line 25, in __init__ header = struct.unpack(">16i", self.Map[0:16*4]) ValueError: mmap closed or invalid Here is the relevant portion of the program source: DefTzFile = "Ott.dat" class TzDatabase: minyear = idt.date(1830) magic0 = 0x108bead + 0 magic1 = 0x108bead + 1 nsegments = 4 def __init__(self, filename=DefTzFile): self.filename = filename self.fd = os.open(filename, os.O_RDONLY) self.Map = mmap.mmap(self.fd, 0, access=mmap.ACCESS_READ) #### exception occurs here: ##### header = struct.unpack(">16i", self.Map[0:16*4]) if header[0] == self.magic0: self.ztSeg, self.ttSeg, self.txSeg, self.znSeg = range(self.nsegments) elif header[0] == self.magic1: self.ttSeg, self.txSeg, self.ztSeg, self.znSeg = range(self.nsegments) else: assert False, 'File %s is not a TzDatabase file' % filename (-: Stop, smile, and enjoy your breathing :-) -- Parzival -- Reply-to is confuggled: parzp (@) shaw (.) ca From just at xs4all.nl Mon Nov 17 07:28:48 2003 From: just at xs4all.nl (Just) Date: Mon, 17 Nov 2003 13:28:48 +0100 Subject: for what are for/while else clauses References: Message-ID: In article , "Fredrik Lundh" wrote: > > the fact that the 'controlling condition' is "a break statement > > has executed" > > that's not how it works. But it is: the only time the else clause is _not_ executed is when the loop was stopped due to a break statement: >>> for x in []: ... print x ... else: ... print "else" ... else >>> for x in [1]: ... print x ... else: ... print "else" ... 1 else >>> for x in [1]: ... print x ... break ... else: ... print "else" ... 1 >>> You're either speaking in tongues, or you're wrong. Am I missing something? Just From max at alcyone.com Mon Nov 17 05:40:56 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 17 Nov 2003 02:40:56 -0800 Subject: trouble with os.path.exists() and wildcards References: Message-ID: <3FB8A5B8.3D359C27@alcyone.com> Fernando Rodriguez wrote: > How can I check for the xistence of any file that matches a wildcard? > > For example: ppis-*.iss > > os.path.exists() doesn't expand the wildcard... Use glob.glob and then os.path.exists in a loop. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ Get married, but never to a man who is home all day. -- George Bernard Shaw From aleax at aleax.it Tue Nov 4 09:20:18 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 04 Nov 2003 14:20:18 GMT Subject: Please explain the meaning of 'stealing' a ref References: <7h3wuagiagy.fsf@pc150.maths.bris.ac.uk> Message-ID: Christos TZOTZIOY Georgiou wrote: ... > Oh, definitely, ext/refcountsInPython.html is the page I believe. I can > understand the second paragraph, but I wanted some reasoning. For > example, you call a function that its API specifies that it "steals" a > reference to its argument; therefore, you got to incref in advance and Yes, you have to incref IF you want to keep owning that reference. > decref afterwards yourself. What's the reason? Efficiency for You'll decref when you don't want to own that reference any more, and you incref'd it, but if you do that soon, why bother incref'ing?-) The typical use case to explain the stealing is in the "Reference Count Details" section of the API manual: PyObject *t; t = PyTuple_New(3); PyTuple_SetItem(t, 0, PyInt_FromLong(1L)); PyTuple_SetItem(t, 1, PyInt_FromLong(2L)); PyTuple_SetItem(t, 2, PyString_FromString("three")); PyTuple_SetItem is very often called with a completely new reference as its 3d argument, so it steals it to enable this easy idiom... w/o the stealing you'd have to code, e.g.: PyObject *t; PyObject *temp; t = PyTuple_New(3); temp = PyInt_FromLong(1L); PyTuple_SetItem(t, 0, temp); Py_DECREF(temp); etc -- much less handy. > simplicity of the function? If yes, why not enclose the function call > in a incref / decref cycle and then export the enclosing function in the > API? I don't know what you're talking about. Explain please? E.g. with one of the few reference-stealing functions, PyTuple_SetItem ? > Such stuff I wanted to know. > > Also, "borrowing" and "stealing" are the same thing? I just think that No! You get a borrowed reference when you get a reference but are not transferred the ownership of it. That's a pretty widespread use regarding references that are returned to objects that surely pre-existed. You must then incref in the relatively rare case you want to keep hold of that reference for the longer term. > "beautifying" terminology at the C level is more confusing than helpful. What 'beautifying'...? Alex From nessus at mit.edu Wed Nov 12 14:37:57 2003 From: nessus at mit.edu (Douglas Alan) Date: Wed, 12 Nov 2003 14:37:57 -0500 Subject: case-sensitivity References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> Message-ID: Nick Vargish writes: > Douglas Alan writes: >> I better be quiet now, lest I give anyone ideas. > Too late... have you seen this? > http://www.colorforth.com/ See? I'm not paranoid -- they really are out to get me! |>oug From usenet_spam at janc.invalid Mon Nov 10 01:02:33 2003 From: usenet_spam at janc.invalid (JanC) Date: Mon, 10 Nov 2003 06:02:33 GMT Subject: ANN: Leo 4.1 beta 1 An outlining editor References: Message-ID: Tim Churches schreef: > I think this may relate to my reply, which is reproduced below. I did > send it to your address but received an automated reply asking me to > visit a Web page, register there and then give three good reasons why my > message should be forwarded to you. You have to be joking if you expect > anyone to bother doing that! > >> A small request: please don't use spaces in directory or filenames >> in your Leo distribution - use dashes or underscores if you need a >> separator. Spaces annoy the hell out of anyone using a command line >> interface. > > -- > > Tim C Quoted your reply in plain text. OE has problems with the pgp-signature attachment you use... BTW: most people don't like attachments in text newsgroups, and the mailing list is gatewayed to comp.lang.python ... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From mark at hahnca.com Sun Nov 9 18:15:12 2003 From: mark at hahnca.com (Mark Hahn) Date: Sun, 9 Nov 2003 15:15:12 -0800 Subject: pickle complexity limit? Message-ID: I have a heavily interlinked dom like tree structure of objects. A node will link to many children redundantly and many children will reference parents redundantly. So there are many cycles of references. When I tried to cPickle one of these structures with about 700 nodes the python interpreter crashed. I did a binary search limiting the number of nodes added and it could handle 217 nodes. I switched to pickle and now it gives a recursion limit exception instead of crashing. I don't understand how this could happen with pickle. Isn't it supposed to stop when it runs into an object it has already pickled? Couldn't it have been coded in a stackless way? What do I do now? I don't want to recompile with a deeper stack as this will obviously only help in limited cases, not solve the real problem. From bokr at oz.net Thu Nov 20 16:31:47 2003 From: bokr at oz.net (Bengt Richter) Date: 20 Nov 2003 21:31:47 GMT Subject: How do you pass a standard operator such as '<' as a parameter? References: Message-ID: On Fri, 21 Nov 2003 08:13:03 +1100, "Peter Milliken" wrote: >I am creating a subclass of list that will allow 'ordered' lists via the > [...] You might find the bisect module interesting ;-) Regards, Bengt Richter From not.available at na.no Tue Nov 4 17:33:52 2003 From: not.available at na.no (Noen) Date: Tue, 04 Nov 2003 22:33:52 GMT Subject: XORing long strings opimization? In-Reply-To: References: Message-ID: Noen wrote: > Tim Peters wrote: > >> [Noen] >> >>> ... >>> # Xoring >>> for c1 in s1: >>> for c2 in s2: >>> output += chr(ord(c1) ^ ord(c2)) >>> return output >>> >>> This way is very slow for large strings. >>> Anyone know of a better and faster way to do it? >> >> >> >> First do an ord() only once per character: >> >> ord1 = map(ord, s1) >> ord2 = map(ord, s2) >> >> Now loop over that and accumulate the individual results in a list: >> >> alist = [chr(x ^ y) for x in ord1 for y in ord2] >> >> Now paste those all together: >> >> return ''.join(alist) >> >> The major inefficiency in the original is that "output += ..." copies >> all of >> output each time it's executed (strings in Python are immutable -- you >> cannot append to a Python string in-place). >> >> > alist = [chr(x ^ y) for x in ord1 for y in ord2] > > This creates a way too big list... Im not familiar with two for loops in > one, so I cant see whats wrong :( > Oh, my debugger says that it works like: for x in range ord1: for y in range ord2: chr(x^y) which does it x*y times... wonder how the line really should look like... From fumanchu at amor.org Fri Nov 21 22:22:14 2003 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 21 Nov 2003 19:22:14 -0800 Subject: Newbie here... getting a count of repeated instances in a list. Message-ID: > I started trying to learn python today. The program I am > trying to write > will open a text file containing email addresses and store > them in a list. > Then it will go through them saving only the domain portion > of the email. > After that it will count the number of times the domain > occurs, and if above > a certain threshhold, it will add that domain to a list or > text file, or > whatever. For now I just have it printing to the screen. > > This is my code, and it works and does what I want. But I want to do > something with hash object to make this go a whole lot faster. Any > suggestions are appreciated a great deal. Well...it doesn't work as written. The value of "d" within count_domains(), for example, is never set. Avoid the temptation to rewrite your working code into broken code for email purposes. :) Here's a cleaned-up version, using hashes as you requested (untested): def get_domains(email_list): """Form a dictionary of email addresses by domain.""" domains = {} for email in email_list: try: domain = email.split('@', 1)[1] except IndexError: domain = 'No domain' try: domain_list = domains[domain] except KeyError: domain_list = domains[domain] = [] domain_list.append(email.strip()) return domains def count_domains(domains, threshhold): """Domains which occur more than number of times.""" threshhold_domains = [] for key, addresses in domains.iteritems(): if len(addresses) > threshhold: threshhold_domains.append(key) return threshhold_domains file = open(sys.argv[1], 'r') mail_list = file.readlines() domains = get_domains(mail_list) counted = count_domains(domains, 10) print counted Some commentary: 1) Notice the use of """docstrings""" instead of #comments for function descriptions. 2) You could reduce count_domains() to a single line with a 'list comprehension'. Look them up in the Tutorial. Instead of writing: counted = count_domains(domains, 10) you could write: counted = [key for key in domains if len(domains[key]) > 10] 3) Notice the try/except block around the email.split() call, and that I used 'No domain' for error cases. You might just as well use '', or None. 4) Since we are not modifying the lists in place, it's much cleaner to use for: instead of while:. 5) I assumed the step which removed addresses from the list wasn't necessary anymore. Put it back in if it is. 6) I forgot what point 6 was. I'm sure it'll come to me after I hit 'Send'. :) 7) Finally, if you just want the counting and aren't going to reuse the dictionary of domain-sorted addresses, you can perform the counting within the dictionary-formation code to save a *lot* of time. Combining this with point 2 we get: def domain_count(email_list): """Number of addresses for each domain.""" domains = {} for email in email_list: try: domain = email.split('@', 1)[1] except IndexError: domain = 'No domain' try: domains[domain] += 1 except KeyError: domains[domain] = 1 return domains file = open(sys.argv[1], 'r') mail_list = file.readlines() counted = [key for key, count in domain_count(mail_list) if count > 10] print counted HTH! Robert Brewer MIS Amor Ministries fumanchu at amor.org From bignose-hates-spam at and-benfinney-does-too.id.au Tue Nov 11 22:16:52 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 12 Nov 2003 14:06:52 +1050 Subject: trouble understanding None References: Message-ID: On Wed, 12 Nov 2003 02:56:43 GMT, Jakle wrote: > def S(): > # [print a bunch of stuff] > > def T(): > # [print a bunch of other stuff] > > print S(), T() > ******************************************* > > OK, the test prints the letters, but also prints "None" at the end of > each function. That's because you've asked for the following sequence of events: - Invoke S()... - which prints a bunch of stuff - then returns None. - Print the return value of S(). - Invoke T()... - which prints a bunch of other stuff - then returns None. - Print the return value of T(). If you just want the functions invoked (called) instead of getting their return value and printing it, then do that. Define the function: >>> def S(): ... print "Bunch of stuff" ... Print the return result of S(), which necessitates calling the function and doing whatever is inside it: >>> print S() Bunch of stuff None Call the function, thus doing whatever is inside it, then throw away the return value: >>> S() Bunch of stuff Please try to get into the practice of reducing the problem you want to describe to a minimal working example. This often has the side effect that you understand the problem better, and don't end up needing to post it. In the cases where that doesn't happen, at least you've got something that doesn't have irrelevant extra code in it. -- \ "If you ever drop your keys into a river of molten lava, let | `\ 'em go, because, man, they're gone." -- Jack Handey | _o__) | Ben Finney From ulope at gmx.de Sun Nov 2 21:34:49 2003 From: ulope at gmx.de (Ulrich Petri) Date: Mon, 3 Nov 2003 03:34:49 +0100 Subject: global variables ? References: Message-ID: "ruari mactaggart" schrieb im Newsbeitrag news:bo0cuk$sj0$1 at news6.svr.pol.co.uk... > John Roth wrote in message > news:vq78f2gc8bgv59 at news.supernews.com... > > Using a dictionary, it looks like this: > > > > foodict = {foobar: "huh?"} > > > > def snafu(): > > foodict["foobar"] = "what?" > > > > That lets you consolidate all of those messy global variables > > in one place as well as giving you a name you can use for > > better internal documentation. > > > > John Roth > > thank you ! It works now. This is very satisfying. > Well - no. It's not. Globals are bad, ugly, ... From jroznfgre at jngpugbjreQBGbet.cy Sun Nov 23 05:47:36 2003 From: jroznfgre at jngpugbjreQBGbet.cy (JZ) Date: Sun, 23 Nov 2003 11:47:36 +0100 Subject: Zope3 & Plone Message-ID: <1241svcjjhcgvdfaegcpqqljdcnm74ic09@4ax.com> I heard Zope3 has implemented CMF inside. What about Plone? Will it be added also? -- JZ From TalksLikeGargoyle at hotmail.com Thu Nov 13 16:35:57 2003 From: TalksLikeGargoyle at hotmail.com (Bernard Fields) Date: Thu, 13 Nov 2003 21:35:57 GMT Subject: Making a maze.... Message-ID: <1PSsb.44675$jy.34613@clgrps13> Greets, all. As the title suggests, I'm trying to make a maze. Specifically, it's a top-down, 2-d maze, preferably randomly generated, though I'm willing to forego that particular aspect as this point. I've done many, many web-searches, but nothing that I've found so far has provided any clues.... From fred at bigisp.com Mon Nov 17 17:38:56 2003 From: fred at bigisp.com (Fred) Date: Mon, 17 Nov 2003 14:38:56 -0800 Subject: ActivePython Installation problem on win95 Message-ID: Python 2.3.2 (build 232) After installing (completes without error) I cannot start the PythonWin IDE; get an error: "The application can not locate win32ui.pyd for Python (1157). One of the library files needed to run this application cannot be found." Certainly a file with this name exists so it is probably a dependent DLL that is missing. Suggestions? Thanks tom semple From brian at sweetapp.com Thu Nov 13 12:40:59 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 13 Nov 2003 09:40:59 -0800 Subject: XLM and XSLT In-Reply-To: <3FB3B061.B72526CA@mortauxspams.bz> Message-ID: <00be01c3aa0d$4d611290$21795418@dell8200> > I would like to create a file from a xml file with a xslt transformation > in a python program. If you use Pyana (http://pyana.sourceforge.net/) it is as simple as: import Pyana Pyana.transform2File( Pyana.URI("in.xml"), Pyana.URI("in.xsl"), "outfile.xml") Cheers, Brian From joshway_without_spam at myway.com Mon Nov 24 12:28:57 2003 From: joshway_without_spam at myway.com (JCM) Date: Mon, 24 Nov 2003 17:28:57 +0000 (UTC) Subject: code blocks in Python References: <8ef9bea6.0311221215.804bdb3@posting.google.com> <8ef9bea6.0311221913.427cb53e@posting.google.com> <8ef9bea6.0311231634.1ca497ac@posting.google.com> Message-ID: JCM wrote: > Hung Jung Lu wrote: > ... >> It just occurred to me a better syntax: >> def A: >> x = 1 >> y = 2 >> def B: >> z = x + y >> print z >> No new keyword needed, beside, it uses the same keyword as function >> definition, so the purpose of the code block is clear: it's something >> that you will invoke. > I dislike this because it looks too much like function definition > (which I realize was your intent). The problem is that name-lookup in > function bodies is lexical, but the proposed semantics for name-lookup > in codeblocks is dynamic. Sorry, that was badly worded. Take 2: The problem is that name-lookup in function bodies is lexical at the point of definition, but the proposed semantics for name-lookup in codeblocks is lexical at the point of use. From nomail_nospam at verizon.net Sat Nov 29 21:04:59 2003 From: nomail_nospam at verizon.net (Jay) Date: Sun, 30 Nov 2003 02:04:59 GMT Subject: Need some advice In-Reply-To: <2idisv45km5c64v2iqn7mj7pim3l1f4hpk@4ax.com> References: <2idisv45km5c64v2iqn7mj7pim3l1f4hpk@4ax.com> Message-ID: One lesson that I remember from an old college prof: Often it is better to have something that works and isn't 100% correct than a program that does nothing 100% correctly. Of course, you stated that you goal is to learn Python, so a working program is only a side effect. I'd get all the info and do it right.... Jay Bird Jeff Wagner wrote: > I am in the process of learning Python (obsessively so). I've been through a few tutorials and read > a Python book that was lent to me. I am now trying to put what I've learned to use by rewriting that > Numerology program I wrote years ago in VB. > > There are times I am totally stuck (for instance, I just had an idea to put the numerical values of > the alphabet and months of the year in a dictionary located in a function. Then, I can import the > dictionary I need from that function ... well, I'm getting import errors). > > So the question is this ... when I get stuck like this and seem to be banging into walls with > everything I try, is it better to continue trying different things or stop, take a break and go back > to reading a tutorial or a Python book? Or is it better that after I've tried everything I can think > of, I just post the question here, get the answer and move forward? > > Thanks, Jeff From ianb at colorstudy.com Sat Nov 1 16:30:26 2003 From: ianb at colorstudy.com (Ian Bicking) Date: Sat, 1 Nov 2003 15:30:26 -0600 Subject: ANN: SQLObject 0.5 Message-ID: <9BE85BA2-0CB2-11D8-92EF-000393C2D67E@colorstudy.com> SQLObject 0.5 ============= SQLObject is an Object-Relational Mapper (ORM), wrapping your database tables in easy-to-use Python classes. Changes ------- * Firebird support. * Generic conversion routines (makes a BoolCol possible). * Non-integer primary keys. * Instance (row) caches can be synced or expired relative to the database. * Many transaction-related bugs fixed. * And smaller stuff too. Where ----- Home: http://sqlobject.org Changes: http://sqlobject.org/docs/News.html Docs: http://sqlobject.org/docs/SQLObject.html Download: http://prdownloads.sf.net/sqlobject/SQLObject-0.5.tar.gz?download -- Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org From erno-news at erno.iki.fi Thu Nov 13 09:53:09 2003 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 13 Nov 2003 16:53:09 +0200 Subject: source code of a function object References: <5167rv812n95t978ie9spciso2ru2cojuj@4ax.com> Message-ID: Fernando Rodriguez writes: > Hi, > > Is ti possible to get the source code of a given function object? O:-) > > TIA >>> import pickle, inspect >>> print inspect.getsource(pickle.dumps) def dumps(obj, protocol=None, bin=None): file = StringIO() Pickler(file, protocol, bin).dump(obj) return file.getvalue() >>> -- erno From mcherm at mcherm.com Thu Nov 13 07:54:30 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Thu, 13 Nov 2003 04:54:30 -0800 Subject: What's an "atomic" operation (in a threaded context)? Message-ID: <1068728070.3fb37f061d4f2@mcherm.com> > This is what's more interesting: object access is threadsafe in the sense that > you can't get Python's internal data structures into an inconsistent state via > pure Python code (or, for that matter, well-behaved C extensions). IOW, the > above code won't ever crash the interpreter or screw up Python's internal > state. Even if two different threads did tss[5] = (both setting a > value using the same key) you wouldn't get an inconsistent internal state, > although you would obviously have no guarantees about the ordering of the > operations - you'd never know if thread A or thread B changed it last. > > > Can anyone clarify this for me? I'd like to avoid littering my > > threaded code with huge numbers of unnecessary locks... > > The above applies to CPython - I'm not too sure about Jython. The same is true for Jython. In Jython, individual python bytecodes are NOT performed atomically, but there are locks to protect all of the built-in data types (lists, dicts, etc), so that concurrent access can never leave it in an inconsistant state. -- Michael Chermside From santanu at softhome.net Thu Nov 6 02:35:23 2003 From: santanu at softhome.net (Santanu Chatterjee) Date: Thu, 06 Nov 2003 12:35:23 +0500 Subject: Python shortcut ? References: Message-ID: On Sun, 12 Oct 2003 13:21:21 -0700, David Eppstein wrote: > In article , > "Santanu Chatterjee" wrote: > >> Suppose I have the following list: >> myList = [('a','hello), ('b','bye')] >> >> How do I get only the first element of each tuple in the above list to >> be printed without using: >> for i in range(len(myList)): >> print myList[i][0] >> or: >> for i in myList: >> print i[0] >> >> I tried: >> print myList[:][0] >> but it seems to have an altogether different meaning. > > If you're set on a one-liner, you could try > print zip(*myList)[1] > or > print [word for letter,word in myList] > > These are no quite the same -- zip makes tuples, the list comprehension > makes a list. My own preference would be for the list comprehension -- > it's not as concise, but the meaning is clearer. Thanks for the solution. I was already using the second solution. I did not know about the zip function. Regards, Santanu From gerson.kurz at t-online.de Wed Nov 5 06:02:51 2003 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Wed, 05 Nov 2003 11:02:51 GMT Subject: Unicode and Zipfile problems Message-ID: <3fa8d5ee.304218@news.t-online.de> AAAAAAAARG I hate the way python handles unicode. Here is a nice problem for y'all to enjoy: say you have a variable thats unicode directory = u"c:\temp" Its unicode not because you want it to, but because its for example read from _winreg which returns unicode. You do an os.listdir(directory). Note that all filenames returned are now unicode. (Change introduced I believe in 2.3). You add the filenames to a zipfile.ZipFile object. Sometimes, you will get this exception: Traceback (most recent call last): File "collect_trace_info.py", line 65, in CollectTraceInfo z.write(pathname) File "C:\Python23\lib\zipfile.py", line 416, in write self.fp.write(zinfo.FileHeader()) File "C:\Python23\lib\zipfile.py", line 170, in FileHeader return header + self.filename + self.extra UnicodeDecodeError: 'ascii' codec can't decode byte 0x88 in position 12: ordinal not in range(128) After you have regained your composure, you find the reason: "header" is a struct.pack() generated byte string. self.filename is however a unicode string because it is returned by os.listdir as unicode. If "header" generates anything above 0x7F - which can but need not happen, depending on the type of file you have an exception waiting for yourself - sometimes. Great. (The same will probably occur if filename contains chars > 0x7F). The problem does not occur if you have "str" type filenames, because then no backandforth conversion is being made. There is a simple fix, before calling z.write() byte-encode it. Here is a sample code: import os, zipfile, win32api def test(directory): z = zipfile.ZipFile(os.path.join(directory,"temp.zip"),"w",zipfile.ZIP_DEFLATED) for filename in os.listdir(directory): z.write(os.path.join(directory, filename)) z.close() if __name__ == "__main__": test(unicode(win32api.GetSystemDirectory())) Note: It might work on your system, depending on the types of files. To fix it, use z.write(os.path.join(directory, filename).encode("latin-1")) But to my thinking, this is a bug in zipfile.py, really. Now, could anybody please just write a "i-don't-care-if-my-app-can-display-klingon-characters" raw byte encoding which doesn't throw any assertions and doesn't care whether or not the characters are in the 0x7F range? Its ok if I cannot port my batchscripts to swaheli, really. From jegenye2001 at fw.hu Fri Nov 14 15:01:37 2003 From: jegenye2001 at fw.hu (Jegenye 2001 Bt) Date: Fri, 14 Nov 2003 21:01:37 +0100 Subject: how to choose element from list based on probabilities? References: Message-ID: Well, giving it a second thought, it's perhaps better to build up a list of the cumulative sums of the normalized areas ,instead of sorting according to the normalized area, and then do the comparison against that. [narea1, narea1+narea2, narea1+narea2+narea3, ....] Mikl?s Jegenye 2001 Bt wrote in message news:bp10k7$k32$1 at namru.matavnet.hu... > Is this a school homework? ;) > > 0/ add a method to your class Circle which computes the area > 1/ make the list (list comprehension!) with tuples of the form > (circleobject, circleobject.area() ) > 2/ normalize the values to one, i.e. change the the list elements into a > form like (circleobject, circleobject.area()/S) , > where S is the sum of the areas of all the circles > 3/ sort the elements according to the normalized value so that they are in > increasing order > 4/ roll a uniform number between 0 and 1 with using the random module > 5/ find which element is the first one in the sequence where the normalized > value is already greater than (or equal to) this random value > > Use a seed taken from, say, the current time for the random number generator > so that the subsequent calls are randomized. > > Best, > Mikl?s > > > From Jon_Aquino at shaw.ca Wed Nov 12 03:10:34 2003 From: Jon_Aquino at shaw.ca (Jonathan Aquino) Date: 12 Nov 2003 00:10:34 -0800 Subject: Python binary for Mac System 6? Message-ID: I just bought a retro Mac IIsi (5MB memory, 500MB HD), and I would be thrilled if I could run Python on it (MacOS 6) -- does anyone have an old binary for it? I've scoured the net with Google and AltaVista, and found nothing. Well, I guess I could run Python 1.5.2 with System 7, but I'd prefer to run it on zippy old-school System 6! Jon From curty at freeze.invalid Fri Nov 21 06:46:44 2003 From: curty at freeze.invalid (Curt) Date: 21 Nov 2003 12:46:44 +0100 Subject: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com> <3FBC2025.B2A33B6F@alcyone.com> <87d6bncbaj.fsf@einstein.electron.net> <3FBD3D6F.E4068821@alcyone.com> <878ymad3ga.fsf@einstein.electron.net> <3FBD6419.A5A863C8@alcyone.com> Message-ID: <874qwyaqqj.fsf@einstein.electron.net> Erik Max Francis writes: > The tweak I made to your sample file wasn't sorted. It just had two > identical adjacent lines. The modified sample again was: > max at oxygen:~/tmp% cat > uniq.txt > flirty > curty > curty > flirty > ^D > max at oxygen:~/tmp% uniq uniq.txt > flirty > curty > flirty > You don't really think the sequence [flirty, curty, curty, flirty] is > sorted, do you? Well, you did do _something_ to the sample for which you fail to find a more descriptive word than "tweak". I certainly do think that the proper word for the modified sample is "sorted"; yes, you sorted the file on the word "curty", by which I mean that you performed "an operation that segregates items into groups according to a specified criterion" (WordNet). You segregated the item "curty" into a group and therefore sorted the file by what we will now refer to as the "curty criterion". That you didn't apply the "flirty criterion" to your sort (or simply apply an alphabetical criterion) does not demonstrate anything other than your cleverly disguised reticence to employ the "sort" command. ;-) From reply.in.the.newsgroup at my.address.is.invalid Thu Nov 20 03:27:28 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 20 Nov 2003 09:27:28 +0100 Subject: PYTHONPATH problems References: Message-ID: <7luorvoeffvk0ohth5iujapqs8ord5risa@4ax.com> Tim Isakson: >I'm having a problem getting the PYTHONPATH to work - I've got the >variable set in the shell (and exported), and it's showing up when I do >this: So why do you think the problem has to do with PYTHONPATH? Perhaps there's something wrong with your import statement, the name of the files, ... Tell us more. -- Ren? Pijlman From schreibmal at heribert.de Sat Nov 1 14:46:12 2003 From: schreibmal at heribert.de (Herbert Fritsch) Date: Sat, 01 Nov 2003 20:46:12 +0100 Subject: what is this? Message-ID: Hi, I'm a real beginner with python and I don't really know if I will get it. But here is one of my first exercises: Python 2.3+ (#1, Sep 23 2003, 23:07:16) [GCC 3.3.1 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 3 >>> b = 4 >>> b / 2 + a 5 >>> b / (2.0 + a) 0.80000000000000004 There must be something wrong. I' running the new Suse 9.0. Herbert From nomail at hursley.ibm.com Fri Nov 21 02:03:44 2003 From: nomail at hursley.ibm.com (Derek Fountain) Date: Fri, 21 Nov 2003 15:03:44 +0800 Subject: Exceptions, assigning a tuple Message-ID: <3fbdb857$0$1727$5a62ac22@freenews.iinet.net.au> This came up in another thread, but I thought it was worth asking to the group in a thread of its own. What I don't understand is the assignment of a tuple in the except clause. The O'Reilly Nutshell book says "The optional target is an identifier that names a variable that Python binds to the exception object just before the exception handler executes". This doesn't make sense in this case: except IOError, (errno, strerror): The target is a tuple of 2 variable names so how can it bind "the exception object" to them? The documentation for try/except says that "the exception's parameter is assigned to the target". So what, exactly, is an "exception's parameter"? From francisgavila at yahoo.com Wed Nov 12 09:40:54 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Wed, 12 Nov 2003 09:40:54 -0500 Subject: any telnetlib equivalent in Python for rlogin? References: Message-ID: "walala" wrote in message news:bopo66$rev$1 at mozo.cc.purdue.edu... > Dear all, > Considering I am quite new to Python, is there any way that I can easily > change this program to be used on "rlogin"? For example, is there a library > called "RLOGIN" that I can simply use self.tn = tn = > rloginlib.Rlogin(self.host), or something like that? Yes: replicate the public interface of telnetlib, and use the rlogin protocol instead of the telnet protocol behind-the-curtain. Much of the telnetlib public interface will be redundant, because these protocols don't have many escape or control characters, and hence do very little data cooking. As for the behind-the-covers implementation, you can either go expect-like and communicate with an rlogin/ssh subshell through os.popen2/3, or reimplement an rlogin/ssh client in Python. Reimplementing the rlogin client looks pretty easy--its a simple protocol (rfc1282). Reimplementing ssh is _far_ more ambitious--I think communicating with a subshell is probably a better idea for that. It seems odd to me that your network supports rlogin but not telnet--rlogin is iirc far more insecure because of the .rhosts nonsense. I think ssh is certainly a better choice here, even though using it will be messier. -- Francis Avila From jzgoda at gazeta.usun.pl Fri Nov 14 14:21:02 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 14 Nov 2003 19:21:02 +0000 (UTC) Subject: Help with Kinterbasdb SQL Error -206 Column unknown References: Message-ID: R Baumann pisze: >>>> import kinterbasdb >>>> con = kinterbasdb.connect( > host='localhost', > database='c:/Data/FireBirdIB/employee.gdb', > user='SYSDBA', > password='masterkey', > dialect=3 > ) Try with dialect 1. If this will not help, check database integrity (i.e. with IBConsole). -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From mis6 at pitt.edu Wed Nov 5 02:54:35 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 4 Nov 2003 23:54:35 -0800 Subject: programming languages (etc) "web popularity" fun References: <1b0569eff1ff540df7b1bf4ad2d5da1f@news.teranews.com> <874qxl9iuw.fsf@pobox.com> Message-ID: <2259b0e2.0311042354.7071a22e@posting.google.com> Skip Montanaro wrote in message news:... > Please add Macsyma to your list. There must be one or two Lisp Machines > still out there... ;-) > > Skip Maxima now is a Sourceforce projects and runs on every PC: http://maxima.sourceforge.net/ Michele From abelikov72 at hotmail.com Tue Nov 4 10:38:07 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Tue, 04 Nov 2003 15:38:07 GMT Subject: Reporting important unhandled exceptions before they occur Message-ID: <8jhfqvcujik1ff0cln3qhc0f5crh6n27d3@4ax.com> I recently decided it would be best for me to know about unhandled exceptions before they occur. I imagined some tool could check for this, possibly even an extreme mode of PyChecker. However, I found none. I suppose, without much thought, that some tool could just list the last few levels in which an exception could be thrown but is not handled. Does such a tool exist? P.S. I do not need to be lectured on why you might think this is bad. From adalke at mindspring.com Tue Nov 11 19:42:18 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 12 Nov 2003 00:42:18 GMT Subject: True, False, None References: <20031110065915.07735.00000461@mb-m07.aol.com> Message-ID: Douglas Alan: > Can someone remind me as to why [None, True, False] are > capitalized? They clash annoyingly with the common coding > convention that capitalizes only classes. Here's a conjecture -- those are singletons, and note that classes are singletons too. Andrew dalke at dalkescientific.com From nessus at mit.edu Tue Nov 11 17:04:43 2003 From: nessus at mit.edu (Douglas Alan) Date: Tue, 11 Nov 2003 17:04:43 -0500 Subject: Python's simplicity philosophy References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: "Dave Brueck" writes: >> Of course I am not joking. I see no good coming from the mantra, when >> the mantra should be instead what I said it should be: >> "small, clean, simple, powerful, general, elegant" > It's really a matter of taste - both "versions" mean about the same to me > (and to me both mean "get rid of reduce()" ;-) ). No, my mantra plainly states to keep general and powerful features over specific, tailored features. reduce() is more general and powerful than sum(), and would thus clearly be preferred by my mantra. The mantra "there should be only one obvious way to do it" apparently implies that one should remove powerful, general features like reduce() from the language, and clutter it up instead with lots of specific, tailored features like overloaded sum() and max(). If so, clearly this mantra is harmful, and will ultimately result in Python becoming a bloated language filled up with "one obvious way" to solve every particular idiom. This would be very bad, and make it less like Python and more like Perl. I can already see what's going to happen with sum(): Ultimately, people will realize that they may want to perform more general types of sums, using alternate addition operations. (For intance, there may be a number of different ways that you might add together vectors -- e.g, city block geometry vs. normal geometry. Or you may want to add together numbers using modular arithmetic, without worrying about overflowing into bignums.) So, a new feature will be added to sum() to allow an alternate summing function to be passed into sum(). Then reduce() will have effectively been put back into the language, only its name will have been changed, and its interface will have been changed so that everyone who has taken CS-101 and knows off the top of their head what reduce() is and does, won't easily be able to find it. Yes, there are other parts of The Zen of Python that point to the powerful and general, rather than the clutter of specific and tailored, but nobody seems to quote them these days, and they surely are ignoring them when they want to bloat up the language with unneccessary features like overloaded sum() and max() functions, rather than to rely on trusty, powerful, and elegant reduce(), which can easily and lightweightedly do everything that overloaded sum() and max() can do and quite a bit more. >> To me, there is never *one* obviously "right way" to do anything > Never? I doubt this very much. When you want to add two numbers in a > programming language, what's your first impulse? Most likely it is > to write "a + b". Or b + a. Perhaps we should prevent that, since that makes two obviously right ways to do it! > Having said that though, part of the appeal of Python is that it hits the > nail on the head surprisingly often: if you don't know (from prior > experience) how to do something in Python, your first guess is very often > correct. Correspondingly, when you read someone else's Python code that uses > some feature you're not familiar with, odds are in your favor that you'll > correctly guess what that feature actually does. All of this falls out of "clean", "simple", and "elegant". > And that is why I wouldn't be sad if reduce() were to disappear - I don't > use reduce() and _anytime_ I see reduce() in someone's code I have to slow > way down and sort of rehearse in my mind what it's supposed to do and see if > I can successfully interpret its meaning (and, when nobody's looking, I > might even replace it with a for-loop!). C'mon -- all reduce() is is a generalized sum or product. What's there to think about? It's as intuitive as can be. And taught in every CS curiculum. What more does one want out of a function? |>oug From gabor at z10n.net Sun Nov 30 17:30:40 2003 From: gabor at z10n.net (gabor) Date: Sun, 30 Nov 2003 23:30:40 +0100 Subject: python-unicode doesn't support >65535 symbols? In-Reply-To: <2c60a528.0311270946.4233a55c@posting.google.com> References: <2c60a528.0311270946.4233a55c@posting.google.com> Message-ID: <1070231440.2052.5.camel@wintermute.atriaky.sk> On Thu, 2003-11-27 at 18:46, Andrew Clover wrote: > gabor wrote: > > > so text[3] (which should be \U00010330), > > was split to 2 16bit values (text[3] and text[4]). > > The default encoding for native Unicode strings in Python in UTF-16, which > cannot hold the extended planes beyond 0xFFFF in a single character. Instead, > it uses two 'surrogate' characters. Bit of a nasty hack, but that's what > Unicode does and there's nothing can be done about it now. does that mean that python when compiled in utf-16 mode, uses surrogates? then it should also correctly tell me that the length is 9, not 10, don't you think? as i see there are 2 possibilities: 1. python, when compiled for narrow-unicode, uses surrogates to encode non-plane0 characters in utf16. if that's true, python has a bug, because in my example text[3] should be what i wrote, and length should also work correctly. or 2. python, when compiled for narrow-unicode, doesn't work with characters outside plane0. if that's true, i would expect python to at least tell me, throw an exception for example, if i try to decode for example an utf8 string, with non-plane-0 characters. what do you think? gabor From mark at hahnca.com Sat Nov 8 23:09:30 2003 From: mark at hahnca.com (Mark Hahn) Date: Sat, 8 Nov 2003 20:09:30 -0800 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: Message-ID: This may be a really off-the-wall question, but how different would Leo be if the outline were just directories and text files? Would it be a set of file utilities and a kind of super-editor? It seems to me that a lot of Leo features can be found in standard directories and files. "Edward K. Ream" wrote in message news:vqq69dh7rg5ne7 at corp.supernews.com... > Conclusion > > All the power of Leo derives directly from the power, flexibility and > dynamism of Python. But making structure explicit as Leo outlines do adds > an important new dimension, literally and figuratively, to Python. > Moreover, Leo's Find/Change dialog creates a new environment from which to > run Python scripts. At long last the full power of the unification of code > and data is becoming apparent. > > Edward > -------------------------------------------------------------------- > Edward K. Ream email: edreamleo at charter.net > Leo: Literate Editor with Outlines > Leo: http://webpages.charter.net/edreamleo/front.html > -------------------------------------------------------------------- > > From reply.in.the.newsgroup at my.address.is.invalid Mon Nov 3 03:52:26 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 03 Nov 2003 09:52:26 +0100 Subject: Unicode -> Python -> DBAPI -> PyPgSQL -> PostgreSQL Message-ID: <375cqv82qeo8agtlodmbkc8fgo6aa7v2q6@4ax.com> I can't seem to find any way to specify the character encoding with the DB API implementation of PyPgSQL. There is no mention of encoding and Unicode in the DB API v2.0 spec and the PyPgSQL README. When I have Unicode strings in Python and store it in a PostgreSQL Unicode database, will the data automatically be correctly encoded? Or do I need to specify the UTF-8 client encoding on the database connection somehow? I'm using the current packages of Debian stable (woody): Python 2.2 PyPgSQL 2.0 PostgreSQL 7.2 (database created with UNICODE / UTF-8 encoding) -- Ren? Pijlman From exarkun at intarweb.us Sat Nov 22 10:52:15 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sat, 22 Nov 2003 10:52:15 -0500 Subject: Use of GPLed Python extension modules In-Reply-To: References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> Message-ID: <20031122155215.GA31979@intarweb.us> On Sat, Nov 22, 2003 at 05:37:38PM +0800, kk wrote: > Paul Rubin wrote: > > Tim Churches writes: > > > >>If a compiled Python extension module B includes code from some > >>other software A which is licensed only under the GPL, do other > >>Python programmes, C, which import module B also need to be licensed > >>under a GPL-compatible license (assuming C is/are to be distributed > >>to third parties)? > > > > > > It's not enough for B and C to be under "GPL-compatible licenses". > > They have to be under the actual GPL. > > > > From http://www.gnu.org/licenses/gpl-faq.html#LinkingWithGPL > > > > You have a GPL'ed program that I'd like to link with my code to build > > a proprietary program. Does the fact that I link with your program > > mean I have to GPL my program? > > > > Yes. > AFAIK, ur python program, which is interpreted, is considered data in > view of the program interpreter. So the GPL license is not needed. > Correct me if I am wrong. I'm pretty sure that's wrong. Jp From __peter__ at web.de Mon Nov 10 10:14:01 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 Nov 2003 16:14:01 +0100 Subject: On python syntax... References: Message-ID: Steve H wrote: > I'm writing a library in which I have a stream object supporting a > Write mehod, and I require to provide support for writing arbitrary > strings in arbitrary nested contexts. A simplified example solution > might look like this. > > -- > # Simplified matching marker calls. > def Open(s) : > s.write("(") > def Close(s) : > s.write(")") > > #Main body > def Square(s) : > s.Open() > for i in range(100) : > s.open > for j in range(100) : > s.write("{%s,%s}"%i,j) > s.close > s.close > -- > > While this solution would work, I'm less than happy that the > programmer is left to ensure calls to Open are matched with calls to > close. It is significant to note that every call to open is at the > beginning of a nested context, and every call to close is at the > corresponing end of the same nested context. > > Having glanced through the python manual I notice that the C++ trick > of using an object with a destructor to manage this sort of behaviour > is inappropriate for a phython script (as __del__ may be called at any > time once the ref-count for an object is 0.) I wonder, is there a > better approach to this problem than the solution above (maybe using > lambda functions?) I'd like a main body of the following form to > generate the same result: > > def Square(s) : > ManageContext(s) > for i in range(100) : > ManageContext(s) > for j in range(100) : > s.write("{%s,%s}"%i,j) > > Any suggestions? Below is a Context class with a random mix of ways to tackle your problem. Instead of ctx.open() yourfunc(ctx, arg1, ..., argN) ctx.close() just write ctx.wrap(yourfunc, arg1, ..., argN) While in doubt about the wrap() and wrapItems() methods, I think that the level-counting approach is worth consideration. Store the level at the begin of a function and assert that it has not changed at the end, putting it into a try ... finally statement for functions with more then one exit point (or just query it with your debugger). class Context: def __init__(self, write=None): if write is None: import sys write = sys.stdout.write self.write = write self.level = 0 def open(self): self.write("(") self.level += 1 def close(self): assert self.level > 0 self.write(")") self.level -= 1 def done(self): assert self.level == 0 def wrap(self, fun, *args): self.open() fun(self, *args) self.close() def wrapItems(self, seq, mapfunc=str): for item in seq: self.open() self.write(mapfunc(item)) self.close() def b(ctx, i, j): ctx.write("%s %s" % (i, j)) def square(ctx, n, m) : for i in range(n): ctx.open() for j in range(m) : ctx.wrap(b, i, j) ctx.close() ctx.write("\n") ctx = Context() ctx.wrap(square, 5, 4) ctx.write("\n") ctx.wrapItems(range(6), lambda x: str(x*x)) ctx.done() Peter From abhjrpe at comcast.net Mon Nov 10 18:14:20 2003 From: abhjrpe at comcast.net (Aubrey Hutchison) Date: Mon, 10 Nov 2003 18:14:20 -0500 Subject: What do you think of this Python logo? References: Message-ID: "Douglas Alan" wrote in message news:lcekwfyhqj.fsf at gaffa.mit.edu... > "Brandon J. Van Every" writes: > > > What do you think of this Python logo? > > http://pythonology.org/logos > > Good, bad, indifferent, love it, hate it? > > I like it! > > |>oug Nice, Neat, Clean Aubrey From sombDELETE at pobox.ru Tue Nov 18 19:42:54 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Wed, 19 Nov 2003 03:42:54 +0300 Subject: Python Database Objects (PDO) 1.2.0 Released References: <8rtgrvkl8vae90116u3opgdn2inias1ti4@4ax.com> Message-ID: [Jon Franz] > PDO: > import pdo > > mycon = pdo.connect("module=MySQLdb;user=test;passwd=foobar;db=sample") > results = mycon.open("SELECT * FROM Customers") > while results.next(): > print "Name: " + results['Name'].value > print "Address: " + results['Address'].value > print "Size of 'Name' column in the db: " + str(results['Name'].length) Why don't you use iterators for that? for result in mycon.open("SELECT * FROM Customers"): print ... Besides you're even "abusing" .next() method which you use to provide iterations in a different way. Confusing... -- Serge Orlov. From peter at engcorp.com Fri Nov 21 18:59:47 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Nov 2003 18:59:47 -0500 Subject: python regular expression References: Message-ID: <3FBEA6F3.2CDEA50@engcorp.com> eddieNOSPAM at eddiecentral.net wrote: > > I am trying to edit a bunch of files that are similar. I want to remove all > the ASP code that appears before the tag. Can some one help me with a > regex that can replace everything before the tag with nothing? stuff = 'whatever ASP blah\nblah more blah blahmaybe even more' try: shortStuff = stuff[stuff.index(''):] except: shortStuff = stuff No regex required... From mwilson at the-wire.com Sun Nov 16 22:21:03 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 16 Nov 2003 22:21:03 -0500 Subject: how to choose element from list based on probabilities? References: Message-ID: In article , Matthew Wilson wrote: >I have a list of very simple circle objects: > >class Circle: > def __init__(self, x,y,r): > self.center =(x,y) > self.r = r > >I want to write a function that accepts a list of circle objects and >then chooses one of the circles and returns that circle. The circles >with the biggest areas should be the most likely to be chosen, but there >should be some randomness. > >Subsequent calls to the function should not return the same circle. Given a list of objects and probability weights: things = [(o1,p1), (o2,p2), (o3,p3), (o4,p4), (o5,p5)] accum = 0 for o, p in things: accum += p if accum * random.random() < p: selected = o At the end the probability of any one of the things being selected is equal to that things probablity weight divided by the sum of all the weights. The way to meet the non-duplication requirement is to remove the object from the working list when it's selected. Keep track of each candiates index through the selection loop if you need to. Regards. Mel. From hanzspam at yahoo.com.au Thu Nov 6 04:33:13 2003 From: hanzspam at yahoo.com.au (Hannu Kankaanp??) Date: 6 Nov 2003 01:33:13 -0800 Subject: Why does changing 1 list affect the other? References: <8ufjqvc24b7o1v0c32p2cpv7us32gtsdic@4ax.com> Message-ID: <840592e1.0311060133.6eca5ce8@posting.google.com> oom wrote in message news:<8ufjqvc24b7o1v0c32p2cpv7us32gtsdic at 4ax.com>... > why does altering one list affect the other list ? it is driving me > insane! Because both variables refer to the same object (the list object). You can check if 2 variables refer to same object with 'is' operator: >>> a = 3 >>> b = a >>> a is b True >>> b = 2 + b >>> a is b False >>> a 3 >>> b 5 Now, when you later think you're changing b's number, you're actually constructing a new number object and making b refer to it. Here 2 + b creates the new object, 5, and "b=..." assigns this object to variable b. Two objects can be different even though they have the same value: >>> a = 1000 # 1000 constructs a number object that has value 1000 >>> b = 1000 >>> a == b # do a & b have the same value? True >>> a is b # do a & b refer to the same object? False Doing this with integers smaller than 100 may be confusing though: >>> a = 50 # surprise: 50 doesn't construct a new number object. >>> b = 50 # It just selects a commonly shared 50-object >>> a is b True Python handles small numbers by sharing the same object to make the implementation more efficient. Variables and objects must be understood being separate things so that you'll see what's happening. In your example, you only did a simple assignment that made two variables refer to the same list. You could then modify this same list through either variable. Like the number addition example above, you could do: >>> a = [1, 2, 3] >>> b = [] + a >>> a[0] = 5 >>> a [5, 2, 3] >>> b [1, 2, 3] Where []+a creates again a new list object, concatenation of empty list and a. Thus a and b won't refer to same object, and changin a's contents doesn't show as a change when you check b's contents (or more precisely, the contents of the object that b refers to). But the preferred way to create a copy of a list is this: >>> b = a[:] You'll need to look up how "slicing" works to know what this one actually does. From tjreedy at udel.edu Tue Nov 18 01:47:16 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Nov 2003 01:47:16 -0500 Subject: Origin of the term "first-class object" References: <8ef9bea6.0311171335.356a7af6@posting.google.com> Message-ID: "Rainer Deyke" wrote in message news:wHcub.227649$Tr4.672235 at attbi_s03... > I would consider variables to be second-class citizens. In a sense, 'they' are not even citizens. In Python, names are syntactic entities, not runtime objects (although they sometimes get embodied in or represented as strings). They are part of the code directing computation but are not the subject of computation themselves (although strings representing them can be). (But the CPython interpreter usually represents local function names as C integers instead.) In themselves, names have neither id, type, nor value, just a current binding to an object that does. "Variable' is an informal term with multiple meanings even in mathematics. In named-memory-block languages like C, a 'variable' is a name associated with a fixed-address, mutable-content (value) block, which before 'const', was (to my memory) every number (including chars), array, and structure/union. Python, being about objects rather than memory, has no direct equivalent. Nor is there a formal definition of 'variable' for Python. Python names are used much like C variables, but I think people sometimes use 'variable' in a way that more refers to objects than to names. For instance, in Python 'the value of i' is 'the value of the ojbect currently associated with i' whereas in C it is 'the value currently in memory block i'. > You can change their value, You can change the value of objects, but only the binding of names. > delete them, You can delete objects but only the binding of names. 'Del a' means unbind 'a' from its currently associated object and if that was the last remaining binding of that object, make the *object* eligible for de-existence. Thus far, you are using 'variable' more to describe objects than names. > and get at the object to which they refer, But here you clearly mean 'variable' = 'name' unless you also mean 'variable' = collection slot or object attribute ('dotted name'). > but you can't do much else with them. It is hard to do much with an ill-defined abstraction ;-). Terry J. Reedy From netspam at shic.co.uk Mon Nov 10 08:41:17 2003 From: netspam at shic.co.uk (Steve H) Date: 10 Nov 2003 05:41:17 -0800 Subject: On python syntax... Message-ID: I'm writing a library in which I have a stream object supporting a Write mehod, and I require to provide support for writing arbitrary strings in arbitrary nested contexts. A simplified example solution might look like this. -- # Simplified matching marker calls. def Open(s) : s.write("(") def Close(s) : s.write(")") #Main body def Square(s) : s.Open() for i in range(100) : s.open for j in range(100) : s.write("{%s,%s}"%i,j) s.close s.close -- While this solution would work, I'm less than happy that the programmer is left to ensure calls to Open are matched with calls to close. It is significant to note that every call to open is at the beginning of a nested context, and every call to close is at the corresponing end of the same nested context. Having glanced through the python manual I notice that the C++ trick of using an object with a destructor to manage this sort of behaviour is inappropriate for a phython script (as __del__ may be called at any time once the ref-count for an object is 0.) I wonder, is there a better approach to this problem than the solution above (maybe using lambda functions?) I'd like a main body of the following form to generate the same result: def Square(s) : ManageContext(s) for i in range(100) : ManageContext(s) for j in range(100) : s.write("{%s,%s}"%i,j) Any suggestions? From faizan at jaredweb.com Tue Nov 25 16:32:02 2003 From: faizan at jaredweb.com (Fazer) Date: 25 Nov 2003 13:32:02 -0800 Subject: String Regex problem References: <7b454334.0311241844.210b4846@posting.google.com> Message-ID: <7b454334.0311251332.51fe4580@posting.google.com> djw wrote in message news:... > Fazer wrote: > > Hello, > > > > I have a string which has a url (Begins with a http://) somewhere in > > it. I want to detect such a url and just spit out the url. Since I > > am very poor in regex, can someone show me how to do it using a few > > examples? > > > > Thanks a lot! > > I would look here to improve your re-ex skills: > > http://www.amk.ca/python/howto/regex/ > > Also, I find Kodos to be invaluable in developing and debugging regexs. > Highly recommended. > > http://kodos.sourceforge.net > > Of course, you could just use urlparse in the standard library... > > Good luck, > > Don Wow awesome! Thanks a lot for kodos. I hope I find it useful. I have actually found a better solution rather than using regex it self. Here's my solution and I think it works well: [x for x in moo.split(' ') if x.startswith('http://')] From radam2 at tampabay.rr.com Fri Nov 14 13:02:22 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Fri, 14 Nov 2003 18:02:22 GMT Subject: Palindrome References: <20031112223135.29045.00000109@mb-m12.aol.com> <3FB3C016.56BCA546@hotmail.com> <2pi9rvotmcdah2mij27a4mn9ggb9me4t0j@4ax.com> <3FB4E7EF.DC6D9814@hotmail.com> Message-ID: On Fri, 14 Nov 2003 14:34:23 +0000, Alan Kennedy wrote: > >If I were going to follow this approach, I would try to eliminate any >copying, like so: > >def palindrome_test(p): > p = p.lower() > p = re.sub(r'\W','',p) > plen = len(p) > for i in xrange(plen/2): > if p[i] != p[plen-i-1]: > return False > return True > >regards, Good point. Ok, how about like this? """ Test if a string is a palindrome. """ import re def palindrome_test(p): p = re.sub(r'\W','',p.lower()) i = len(p)//2 while i and p[i] == p[-i-1]: i -= 1 return not i palindrome_list = [ "A", "ab", "Oo!", "Bolton", "This is not a palindrome!", "Was it a car or a cat I saw?", "No 'H' type, mate, no spot stops one tame python!", "A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal--Panama!", ] for p in palindrome_list: print '"'+p+'"', if palindrome_test(p): print 'is a palindrome.' else: print 'is not a palindrome.' From pythonguy at Hotpop.com Fri Nov 14 06:35:04 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 14 Nov 2003 03:35:04 -0800 Subject: Books I'd like to see References: Message-ID: <84fc4588.0311140335.7ea1ada3@posting.google.com> Oh, you were listing books that were *not* in the market. I got it the other way round ;-) Anyway, my argument for "Sofware development in Python" holds. regards -Anand Bryan wrote in message news:... > Nick Vargish wrote: > > I would like to see "wxPython Programming" from Grayson, John E. > > > > His book on tkinter is pretty darn good, but I'm much more interested > > in wxWindows. I find the need to look up the C++ wxWindows > > documentation and do a translation to the Python equivalent really > > gets in my way of learning how to use the widgets properly. > > > > Nick > > > > i 2nd this > > bryan From nagylzs at freemail.hu Wed Nov 19 07:33:07 2003 From: nagylzs at freemail.hu (=?ISO-8859-1?Q?Nagy_L=E1szl=F3_Zsolt?=) Date: Wed, 19 Nov 2003 13:33:07 +0100 Subject: rotor alternative? References: Message-ID: <3FBB6303.6040700@freemail.hu> You can try pycrypto if you want. What OS do you use? Unfortunately, I could not find an installer for Windows, but I created my own - mail me if you want it. Installing on BSD and Linux is quite easy. With the pycrypto library, you can use several famous block ciphers like AES, BlowFish etc. - these are for private key encryption. It can do public key cryptography (RSA) and digital signatures (RSA & DSA) too. However, this lib is NOT SSL compatible. It has a documentation but you can find examples on the net too. This may or may not be the library you need. It depends on your needs. There are many others: ezPyCrypto, yawPyCrypto, PyOpenSSL - please look for them on google, they are easy to find. I choose PyCrypto because it can be compiled almost anywhere and it is easy to use. But for example, PyOpenSSL can give you full control over the OpenSSL library. However, you must be familiar with OpenSSL to use it. Well, none of those libraries are part of Python 2.3. I think this is partly because it would not allow Python to be used in some countries. (These can do strong encryption.) Conclusion: there is no obvious replacement for you. Cheers, Laci 1.0 Jimmy Retzlaff wrote: >Robin Becker wrote: > > > >>It seems that the rotor module is being deprecated in 2.3, but there >>doesn't seem to be an obvious alternative. I'm using it just for >>obfuscation. It seems we have ssl available in 2.3 for sockets, but >>there seems no obvious way to use that from python code. >> >>Is an alternative to rotor planned? >> >> > >If the goal is simple obfuscation (and not encryption) then the base64 >module might work: > > > >>>>import base64 >>>>base64.encodestring('Can you read this?') >>>> >>>> >'Q2FuIHlvdSByZWFkIHRoaXM/\n' > > >>>>base64.decodestring('Q2FuIHlvdSByZWFkIHRoaXM/\n') >>>> >>>> >'Can you read this?' > >Jimmy > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fumanchu at amor.org Wed Nov 26 21:20:50 2003 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 26 Nov 2003 18:20:50 -0800 Subject: polymorphism in python Message-ID: Roy Smith wrote: > But how often is it actually useful to do such a thing? I can't > remember the last time I wanted to do something like that in > Python. And Jay O'Connor replied: > Generally, if you are programming to the interface and not to > the class (which is what you are usually doing in OO programming, > or should be if your language allows it) than testing for the > actual type of an object is usually a no-no I find this comes up quite often in application interfaces; that is, points at which your code manipulates someone else's code in someone else's language. A prime example is forming valid SQL statements: "SELECT * FROM xyz WHERE %(Name)s = %(Value)s" % ({'Name': fieldName, 'Value': fieldValue}) If fieldValue is an int, fine. If it's a string, you're probably going to wrap '%(Value)s' in quote marks. So do you: 1) Explicitly check type. 2) Design your language so you can set attributes on basic type classes: def format_str_for_SQL(...): ... str.format_for_SQL = format_str_for_SQL 3) Use custom subclasses of basic types like int and str throughout the app. 4) Same as #3, with metaclassing. 5) Hard-code every possible SQL statement. 6) Try: the SQL statement each way. Watch the permutation explosion with multiple fields (now I'm just getting silly, but I've seen sillier things in the field, sometimes written by me). There are other ways. I'm probably going to go with option 1 in this limited case, although in other cases option 3 has appeal. Robert Brewer MIS Amor Ministries fumanchu at amor.org From peter at engcorp.com Fri Nov 7 18:22:41 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 07 Nov 2003 18:22:41 -0500 Subject: binary string question References: Message-ID: <3FAC2941.C8D1EF61@engcorp.com> Dan Jones wrote: > > I'm trying to figure out how to get bit operators to work on a binary > string. This is what I'm trying to do: > > list(frame) #where frame is a binary string > y = frame[x] << 8 You don't describe what you want this to do. How about an example, showing input and desired output? > It gives me a TypeError. Whats the best way to get around that? I think > the struct module may be what I'm looking for, if so could someone give > me an example? Also, is there a better way to be able to access > individual bytes than converting the string to a list? Yes, use an array (see the module by that name). On the other hand, depending on what you really want, the answer might be as simple as taking your string and skipping the first element. After all, shifting each byte in a long sequence to the left by 8 bits is pretty much synonymous with that approach: out = in[1:] + '\x00' But I suspect that's not really what you meant. Please explain. -Peter From mwilson at the-wire.com Sat Nov 8 10:11:31 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Sat, 08 Nov 2003 10:11:31 -0500 Subject: prePEP: Decimal data type References: Message-ID: In article , "John Roth" wrote: >My personal opinion in the matter is that setting the precision high >enough so that you won't get into trouble is a hack, and it's a dangerous >hack because the amount of precision needed isn't directly related to the >data you're processing; it's something that came out of an analysis, >probably by someone else under some other circumstances. Given >a software implementation, there's a performance advantage to setting it as >low >as possible, which immediately puts things at risk if your data >changes. It puzzles me. In the COBOL days, we used to worry over setting the sizes of our data fields large enough. We'd set a size we thought was ridiculously large and then worry whether today would be the day that the company would do the unprecedented amount of business that would blow up the night-shift batch runs. We escaped from that with Python's long ints and now we're trying to invent it again. >Fixed precision is also counter to the infinite precision we're moving >toward with the integers; and integers are a more comfortable metaphor >for money than floats. >The natural implementation for fixed decimal is much simpler >than for floating decimal. And I frankly don't think that floating >decimal is going to get that much use outside of an accounting >context, given that I think it's going to be a *lot* slower than >built-in binary floating point. Especially if PyPy succeeds in >their dream of creating a JIT for Python. Float decimal can nice for intermediate results because you don't have to worry about precision limits until you reach a point where you have a specific need for a specific precision. Software speed won't beat hardware speed, but a float multiply can still be just return self.__class__ (self._v*other._v, self._e+other._e) multiplying two longs and adding two ints. Add is tougher v, vo, e = self._match_exp (self, other) return self.__class__ (v+vo, e) ... def _match_exp (self, other): v, e = self._v, self._e vo, eo = other._v, other._e de = e - eo if de > 0: v *= pow (10, de) elif de < 0: vo *= pow (10, -de) return v, vo, min (e, eo) With COBOL we had powerful declarations in the data division and we could fully control the precision of every intermediate result in a calculation; of course the one-verb-per-line form also encouraged this. In ALGOL-flavoured languages the expression-oriented statements make this less natural. And Python with no variable declarations makes this hardest of all. Regards. Mel. From gafStopSpamData at ziplink.stopallspam.net Sun Nov 9 19:41:35 2003 From: gafStopSpamData at ziplink.stopallspam.net (G.A.) Date: Mon, 10 Nov 2003 00:41:35 GMT Subject: Emacs python mode equivalent to c-tab-always-indent Message-ID: Does anyone have a modification to python-mode.el that implements something along the lines of c-tab-always-indent? Currently, it a) gets the indentation wrong inside of """ module strings; and b) reindents the line if I try to use tabs inside subsequent lines of the """ comment string. I can live with the first problem but not the second. With c/c++ my solution is to set c-tab-always-indent to nil, which changes the behavior so that it only reindents the line if the cursor is in the leading whitespace, and otherwise it inserts a real tab (though a virtual tab is fine, too). Thanks, Gary From skemplay at dingley.net Fri Nov 7 06:31:00 2003 From: skemplay at dingley.net (S Kemplay) Date: Fri, 7 Nov 2003 22:31:00 +1100 Subject: Why does this choke? Message-ID: <200311072229.25855.skemplay@dingley.net> Hi all, I wrote a script to choose random dates for a statistics assignment. I only need to choose 30 dates from one year with no leap years and it works fine. However I tested with different numbers of dates. It hangs from 450 up. I only need 30 dates but it would be good to know why it hangs. (My coding probably has something to do with it :)) import random def getmonth(): month = random.randint(1,12) return month def getday(month, leaps): thirtyones = [1,3,5,7,8,10,12] thirties = [4,6,9,11] if month in thirtyones: day = random.randint(1,31) elif month in thirties: day = random.randint(1,30) else: if leaps == 1: leap = random.randint(1,4) else: leap = 1 if leap in [2,3,4]: day = random.randint(1,29) else: day = random.randint(1,28) return day def getdates(n, leaps): dates = [] i = 0 while i < n: month = getmonth() day = getday(month, leaps) if (day, month) in dates: continue i += 1 dates.append((day, month)) return dates Thanks Sean Kemplay From fumanchu at amor.org Mon Nov 24 19:57:47 2003 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 24 Nov 2003 16:57:47 -0800 Subject: For those of you using ADO Message-ID: This has to be the oddest thing I've yet come across. My current Big Project uses a win32com wrapper to ADO. For weeks now, I've wrestled with connection strings: adding parameters, then removing them, then changing the order, then trying silly things like extra semicolons, etc. I finally nailed down a thesis for Why It Was So Hard--the ADO 2.7 dll ignores the first parameter in the connection string. I have to admit I'm guessing it's ADO's fault, that win32com.client just passes the string along. Correct me if I'm wrong, but the fix is simple enough I don't feel I need to track it down further. The fix is the same as the proof: "DSN=RE7_1;UID=mcuser;PWD=*******;" doesn't work, giving an error like "Neither DSN nor SERVER found in connection string," (this is for MS SQL Server; different messages with the same intent result on e.g. MS Access), while: "DSN=RE7_1;UID=mcuser;PWD=*******;DSN=RE7_1;" does work. Further combinations with and without duplicating the first param produce similar results. Go figure. Not really a Python problem, I don't think, but I figured someone might be aided by the theory/fix. Adding another page to the Googlable universe, Robert Brewer MIS Amor Ministries fumanchu at amor.org From jjl at pobox.com Mon Nov 10 17:10:03 2003 From: jjl at pobox.com (John J. Lee) Date: 10 Nov 2003 22:10:03 +0000 Subject: cgi module doesn't process query string values with POST, old bug report References: <3fb00826$0$58716$e4fe514c@news.xs4all.nl> Message-ID: <87llqneuys.fsf@pobox.com> Irmen de Jong writes: > I've got a nuisance with the cgi module. (Python 2.3.2) > When processing a HTTP POST request, it ignores the > query string parameters that may also be present. [...] I've forwarded this to the web-sig list, where discussions about this issue have been taking place. The discussions have mostly been about adding a new module (mostly to decouple web frameworks from the facilities that web hosting providers offer), but I don't see why the old cgi module shouldn't be dealt with at the same time. http://mail.python.org/mailman/listinfo/web-sig/ John From kadamski at usun.onet.pl Mon Nov 17 11:24:27 2003 From: kadamski at usun.onet.pl (Krzysztof Adamski) Date: Mon, 17 Nov 2003 17:24:27 +0100 Subject: Mapping PyLong -> BigInteger Message-ID: Hi, Is it possible in jython to map an PyLong object to other class than BigInteger (i.e. java.lang.Long) ? Thanks for you help, Krzysztof Adamski From dman at dman13.dyndns.org Thu Nov 20 16:23:10 2003 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Thu, 20 Nov 2003 21:23:10 GMT Subject: best Wx editor References: Message-ID: On Thu, 20 Nov 2003 08:19:58 -0600, Jason Tesser wrote: > What is the best overall ide studio that can be used to develop > crossplatform apps (win,linux,mac) for python? wxGlade is usable for development of the static portions of the GUI. It is rather new and has some bugs and limitations, but I used it quite happily in the spring for a school project. (I was learning wx at the same time). I found wxGlade easier to understand and achieve results than wxDesigner or Boa. Boa did help me a little, though. wxDesigner isn't "Free", btw. For coding, UNIX is the best :-). (vim as editor, cvs for source control, python for execution, ls/cp/mv/grep/ for file management, you get the picture) -- Q: What is the difference between open-source and commercial software? A: If you have a problem with commercial software you can call a phone number and they will tell you it might be solved in a future version. For open-source sofware there isn't a phone number to call, but you get the solution within a day. www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From davidb at dcs.st-and.ac.uk Tue Nov 18 17:04:29 2003 From: davidb at dcs.st-and.ac.uk (David Boddie) Date: Tue, 18 Nov 2003 22:04:29 +0000 (UTC) Subject: Trouble Importing Tkinter in embedded C program References: Message-ID: Rick Olson wrote: > I'm trying to add a Tkinter interface to an existing C program with > embedded python, but seem to have trouble importing Tkinter (or > accessing it). [...] Sounds like a fairly familiar issue with compiled extensions, but I could be wrong. > Using Py_GetPath reported: > > /usr/lib/python2.2/:/usr/lib/python2.2/plat-linux2:/usr/lib/python2.2/lib-tk: > /usr/lib/python2.2/lib-dynload > > On my SuSE 8.2 installation Tkinter.py is in usr/lib/python2.2/lib-tk/ [...] > Can someone guide me in the right direction to allow calls to Tkinter > through the embedded python? I know there are ways of using Tk/Tcl > through C, but I'm not familiar enough with Tk/Tcl to try that. If you are able to change the conditions under which the C program is built (paths, libraries, etc.) then you may want to link against the _tkinter.so library in the /usr/lib/python2.2/lib-dynload directory. That's just a guess, however. Maybe this is answered in an FAQ somewhere. -- http://www.boddie.org.uk/david/Projects/ From NOSPAM at xyzxyzxyz.yy Fri Nov 14 11:27:48 2003 From: NOSPAM at xyzxyzxyz.yy (Christoph) Date: Fri, 14 Nov 2003 17:27:48 +0100 Subject: how to return a StringIO of an Image In-Reply-To: References: Message-ID: Fredrik Lundh schrieb: >> image.save('test', 'JPEG') >> image=StringIO(image.????()) # what's the right method? >> return image >> >>Any hints? Thanx! > > > file = StringIO() > image.save(file, "JPEG") > return file.getvalue() > That's what I wanted. Perfect! Thanx a lot! Christoph From andrewfelch at yahoo.com Wed Nov 19 20:28:25 2003 From: andrewfelch at yahoo.com (Andrew Felch) Date: 19 Nov 2003 17:28:25 -0800 Subject: Props to numpy programmers! Message-ID: <9ed149b8.0311191728.117b4566@posting.google.com> So I wanted to matrixmultiply [[a,b], [c,d]] * [e,f] Of course this is impossible, because the number of columns in the first factor is not equal to the number of rows in the second. Wrong! It is impossible because the second matrix is rank1! So numpy happily converts it to a column vector so the multiplication will work, and converts the answer back into a rank1 vector!!!! I love NUMPY!!!!!!!!!!! I was reading my code and thought I had a bug, I couldn't figure out why the code was still working right! It's because the numpy people are geniouses! Hooray numpy!!!!!!!!!! Numpy is smarter than me! From scott_list at mischko.com Mon Nov 10 16:15:55 2003 From: scott_list at mischko.com (Scott Chapman) Date: Mon, 10 Nov 2003 13:15:55 -0800 Subject: Matrix - Metaphors, Analogies and the REAL In-Reply-To: References: <3FAFF339.E499F960@engcorp.com> Message-ID: <200311101315.55665.scott_list@mischko.com> On Monday 10 November 2003 12:30, 3seas wrote: > Its in python code > > http://threeseas.net/vic/vic/ > > -- > 3 S.E.A.S -- Virtual Interaction Configuration (VIC) > Changing how we preceive and use computers > email @ translate not to net, remove capitol letters, one . > web @ http://threeseas.net If it's a Python-related announcement, it should go on Python Announce. If it's a python issue, it should go here. If it's a Matrix issue, it should not go here. Your email was not a Python-related announcement. The blog entry it points to was not Python-related. There was no Python-related content in your email. I think that adds up to off-topic. This would have probably gone mostly unnoticed except for your attitude. If everyone posted their latest advertisement for some pet web site that happened to be written in python, we'd be flooded with CLEARLY OFF-TOPIC posts regarding CLEARLY OFF-TOPIC subject matter. Post your pet web site posts where they are on-topic. Finally, if you _are_ going to post off-topic and you've gotten "bitched" at in the past, please don't respond with a bad attitude post like the one that started this thread. Do you really think such attitudes will be of any value in furthering your ends in any way? Why not learn from your mistakes? Post your pet web site posts in an appropriate manner. You don't owe the list any further details about the nature of the web site. I think you owe the list an apology and a different pattern of behavior in the future. You joined this list as an adult understanding that it exists with certain criteria which you, being a member of the list, are supposed to honor. Police yourself so that the list doesn't have to. We have work to do. ' Hoping you get smarter as you get older, not just older. Scott From gry at ll.mit.edu Mon Nov 17 12:03:43 2003 From: gry at ll.mit.edu (George Young) Date: Mon, 17 Nov 2003 12:03:43 -0500 Subject: dynamically set PYTHONVERBOSE (-v) flag? Message-ID: [python 2.3.2, x86 SuSE Linux 8.2] How can I dynamically set/unset the PYTHONVERBOSE flag? During an interactive session I often want to trace an import but not *all* the imports before that. There must be some builtin variable I can set to control this... -- George Young From aleax at aleax.it Fri Nov 14 11:40:59 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Nov 2003 16:40:59 GMT Subject: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <653b7547.0311121826.65b6b2d4@posting.google.com> Message-ID: Douglas Alan wrote: ... > The argument that some programmers might be too lazy to want to learn > powerful, simple, and elegant features that can be taught in seconds, Programmers may be quite ready to learn anything whose claimed "power" IS actually there. But this complex of thread started with somebody asking for good use cases for reduce, and NONE has been shown. Programmers need not have any interest in spending what may well be more than 'seconds' in learning something that will never given them any *practical* return. Computer "scientists", maybe, have to be, by some definition of "scientist". Fortunately, *programmers* are still allowed to be very pragmatical types instead. > Besides, if you weren't exposed at all to LISP (or a LISP-like > language) while getting a CS degree, it wasn't a very good CS > program! They're going to teach you AI techniques in a different Aha, showing your true colors: I see you have now moved from a "CS 101 course" (which is given to majors in MANY disciplines) to a "CS degree". Quite a different thing. Around here (for the same length of course, say 3 years), graduates in "informatical engineering", for example, may well not know what a Turing machine is, nor be able to name any "AI technique" of practical use (they may have learned, e.g. alpha-beta pruning, which historically did originate within AI, but may be more practical today to learn in completely different contexts) -- but they're likely to know more than graduates in "informatics" (computer science) about, e.g., statistics, and/or how to organize a security-audit. (I have to phrase it in terms of likelihood because most majors do offer quite a bit of choice in terms of what exact courses you can take). I wouldn't be surprised to find an "ingegnere informatico" (3-years degree, i.e. BS-equivalent) who doesn't understand 'reduce' at first; and once he or she has grasped it, I _would_ be surprised not to get challenged with an "OK, now, what IS it GOOD for?". When Plato was asked the same question about Geometry, he had a slave give the querant a gold coin then throw him out of the school: caring about USEFULNESS was OH so icky to Greek philosophers! I would not be surprised if a similar stance (maybe not quite as overt) lingers in several academic environments. Fortunately, though, it seems to me that Engineering faculties have managed to stay pretty free of it (yep, I'm an engineer, and proud of it, and proud that my daughter has chosen an engineering major too -- my son chose Economics, a lovely calling to be sure, and is having a much harder time selecting the courses that concentrate on the _useful_ stuff ["how do I make a cool million before I'm 30" kind of stuff:-)] from those which are the Economics equivalent of "Suppose cows were spheres of uniform density"...:-). Alex From aleax at aleax.it Fri Nov 14 12:28:30 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Nov 2003 17:28:30 GMT Subject: Python's simplicity philosophy References: <2259b0e2.0311112248.3be2d304@posting.google.com> <17lsb.109042$fl1.4548960@twister.southeast.rr.com> Message-ID: <2h8tb.28069$hV.1030501@news2.tin.it> Robin Becker wrote: ... > on oop in this thread nobody has pointed out that we could have > > sequence.sum() > sequence.reduce(operator.add[,init]) > > or even > > sequence.filter(func) etc etc > > and similar. That would make these frighteningly incomprehensible ;) > concepts seem less like functional programming. Personally I wouldn't > like that to happen. Maybe nobody "pointed it out" because it's utterly absurd to even conceive of somehow magically adding all of those methods to *EVERY* iterator under heavens?! E.g., today, this works just fine: >>> class BAH(object): ... def __init__(self): self.seq = [1, 5, 3, 7, 19] ... def __iter__(self): return self ... def next(self): ... try: return self.seq.pop() ... except IndexError: raise StopIteration ... >>> sum(BAH()) 35 having instances of class BAH automagically spout such methods as .sum(), etc, would be an absurdity. Numeric's design -- considering that *functions* able to do .reduce and the like are very special and should expose those as methods (they're known as "ufuncs" in Numeric), taking the array as argument, is a design which looks quite sound to me. So, for example, Numeric.sum(x, axis) boils down (after some error checks &c) to Numeric.add.reduce(x, axis) [summing, of course, IS by far important enough that having to spell it out as add.reduce would be silly]. Alex From BoteDesSchattens at web.de Thu Nov 20 15:40:22 2003 From: BoteDesSchattens at web.de (Tobias Pfeiffer) Date: 20 Nov 2003 20:40:22 GMT Subject: PIL and jpg -> png conversion, do I really need java for this??? References: Message-ID: Hi! On 19 Nov 2003, Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: > I can't figure out why the PNG converted in PIL won't work in the > MIDP applications written in Java. There is something different but > I really don't know what. All PNG generated from ImageMagick, GIMP > or whatever, they work fine, from PIL, no. The conversion in Java > using JIMI works fine as well. The option of executing scripts from > Python using these external tools is not really what I like. What is with JPGs or other formats? Can you write them? How did you install PIL? RPM? I'm on Debian Sarge and I have no single Java package installed, and my PNGs work. So you don't need it, actually. And how did you test the PNGs; opened them in GIMP or what? May I give you a typical Windows hint? *grin* Take the newest version and reinstall it... Bye Tobias From pf_moore at yahoo.co.uk Tue Nov 18 16:56:53 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Tue, 18 Nov 2003 21:56:53 +0000 Subject: PEP 321: Date/Time Parsing and Formatting References: Message-ID: <7k1xgx22.fsf@yahoo.co.uk> "A.M. Kuchling" writes: > On Mon, 17 Nov 2003 22:00:38 +0000, > Paul Moore wrote: >> I'd go for this option. Actually, I'd support including Gustavo's >> dateutil module in the standard library. This PEP then involves adding >> a number of additional (specialised) parsers to the dateutil.parser >> subpackage. > > Actually I think the PEP mostly evaporates, especially if verbal dates > aren't covered. The common cases are then trivial with DateUtil, leaving > only a few cases such as RFC-2822 times. The PEP is pretty borderline, in any case. Not because the functionality isn't useful, but because most of it exists somewhere already. So the PEP is more of the form "now that we have datetime, consolidating the parsing stuff would be good". Specifically: def dt_strptime(s, fmt): tm = time.strptime(s, fmt)[:6] return datetime(*tm) def dt_rfc2822(s): tm = email.Utils.parsedate(s)[:6] return datetime(*tm) This isn't to say that these are immediately obvious (it took me a while to realise that using the * form of call saved a horribly long and ugly constructor call) If this is worth doing, I'd have to say that time.strptime, and email.Utils.parsedate should get deprecated in favour of the "new forms". And I'm not sure I can see that being acceptable. I guess I'm -0 on the PEP as it stands. Incorporate it into a more general "date/time utilities" module, and I'm +1. Also, I'm -1 on adding anything to the datetime module itself (this includes adding more classmethods to the types). The module is clean, and lean as it stands. Bloating it (particularly under the banner of "it's more OO to keep the functions as part of the classes") doesn't appeal to me at all. Paul. -- This signature intentionally left blank From __peter__ at web.de Mon Nov 10 13:09:30 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 Nov 2003 19:09:30 +0100 Subject: make order of function definitions irrelevant References: Message-ID: Joerg Schuster wrote: > according to > > http://mail.python.org/pipermail/tutor/2001-July/007246.html > > the order of function definitions does matter in python. Does anyone > know a trick to avoid this? Is there a way to "declare" functions > without defining them? > > (Making the order of function definitions irrelevant would be useful > for automatically generated python scripts.) You cannot *call* a function before it is defined: fun() def fun(): pass will choke. But there is no problem with def first(): second() def second(): pass So I cannot see where this could be an obstacle to script generation. Could you provide an example? Peter From janeaustine50 at hotmail.com Mon Nov 10 10:16:43 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 10 Nov 2003 07:16:43 -0800 Subject: Talking through pipes interactively (on win32) References: Message-ID: > Can you please post a small script showing the exact problem you have? > Communicating with a program via pipes works on Windows: we do it all the > time. It can be pretty complicated, but it can be done. Okay. For example, python interactive shell: >>> import os >>> sout,sin=os.popen2('python -u') >>> sout.write('print 2*3\n') >>> sout.flush() >>> sin.read(1) ...(it hangs from here)... However, it works if sout is closed before reading from sin: >>> import os >>> sout,sin=os.popen2('python -u') >>> sout.write('print 2*3\n') >>> sout.close() >>> sin.read(1) '6' From theller at python.net Fri Nov 14 14:56:18 2003 From: theller at python.net (Thomas Heller) Date: Fri, 14 Nov 2003 20:56:18 +0100 Subject: C API : setting the message of an exception References: Message-ID: Benoit Dejean writes: > (sorry for my english) > > when an excpetion is raised (like Overflow), before i return NULL, i'd > like to modify the message held by the exception. I use PyErr_SetString, > but i don't know how to retreive the current message > > excaption is raised -> extending error message -> raising exception > > thank you I have used this code: void Extend_Error_Info(char *fmt, ...) { va_list vargs; PyObject *tp, *v, *tb, *s; va_start(vargs, fmt); s = PyString_FromFormatV(fmt, vargs); va_end(vargs); if (!s) return; PyErr_Fetch(&tp, &v, &tb); PyString_ConcatAndDel(&s, v); PyErr_Restore(tp, s, tb); } and then you can: if (result == NULL) { Extend_Error_Info("I wasn't expecting %s", "the spanish inquisition"); } although I'm not sure what happens when PyString_FromFormatV() fails. Thomas From tuanglen at hotmail.com Tue Nov 18 20:23:19 2003 From: tuanglen at hotmail.com (Tuang) Date: 18 Nov 2003 17:23:19 -0800 Subject: syntax philosophy References: <3FB9F7C1.7CCF7985@hotmail.com> Message-ID: Alan Kennedy wrote [lots of good stuff...] > Welcome to the python community. Thanks. It looks like a pretty good community. The graciousness of this community in its response to expressions of concern or scepticism by newcomers stands in sharp contrast to the hostility with which similar questions are met by certain other language communities and definitely increases my interest in Python. From mike at nospam.com Thu Nov 13 13:04:35 2003 From: mike at nospam.com (Mike Rovner) Date: Thu, 13 Nov 2003 10:04:35 -0800 Subject: quest about telnetlib References: <005d01c3a9dc$0fd03b30$35c8c8c8@mcgsdev1.com> Message-ID: ??? wrote: >> print tn.open("162.105.31.222",23) Add some timeout here, >> print tn.read_eager() or repeat reading here. >> the host is avaiable,but my python program cannt connect to it ,why? You ARE connected 'cause open went all right, you just not reading all the data or in other words data are not yet available at the time of your read. HTH, Mike From skip at pobox.com Wed Nov 12 15:37:04 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 12 Nov 2003 14:37:04 -0600 Subject: Python binary for Mac System 6? In-Reply-To: References: Message-ID: <16306.39408.794512.432895@montanaro.dyndns.org> Jon> I just bought a retro Mac IIsi (5MB memory, 500MB HD), and I would Jon> be thrilled if I could run Python on it (MacOS 6) -- does anyone Jon> have an old binary for it? Not here. You might have better success with your request on the PythonMac-Sig: pythonmac-sig at python.org. At the very least someone there might be able to tell you want you'd need to build it yourself. Skip From python-url at phaseit.net Mon Nov 24 12:19:16 2003 From: python-url at phaseit.net (Emile van Sebille) Date: Mon, 24 Nov 2003 17:19:16 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Nov 24) Message-ID: QOTW: "Oddly enough it is in Python that I have had the most fun programming. It is in Python that I find myself not only the most expressive but the most elegant in my programming. In Python my code is the clearest and most concise. I don't for one instant feel constrained by Python. I feel liberated by it." -- Steve Lamb "After a few hours with Python, I was already better at object-oriented Python than I ever was at object-oriented Perl." -- Tuang Alex Panayotopoulos stumbles over 'one of the most popular FAQs' when initializing instance variables. http://groups.google.com/groups?threadm=Pine.LNX.4.44.0311211202450.12175-100000 at jaws.inf.ed.ac.uk Derek Fountain gets help from Erik Max Francis understanding the except clause. http://groups.google.com/groups?threadm=3fbdb857$0$1727$5a62ac22 at freenews.iinet.net.au Chris Gray seeks info on proxy servers written in Python. http://groups.google.com/groups?threadm=Pine.GSO.4.58.0311181001040.21147 at library.uwaterloo.ca Thomas Weholt asks if it is at all possible to use python on cellular/mobile phones and Mark Hahn says yes. http://groups.google.com/groups?threadm=rCsvb.294$n31.5237 at news2.e.nsc.no Neal Norwitz updates PyChecker to Version 0.8.13, a tool for finding bugs in Python source code similar to lint. http://groups.google.com/groups?selm=mailman.862.1069211336.702.python-list at python.org Ian Bicking announces NPyLogo 0.1, the first public release. PyLogo interprets the Logo language, an education Lisp-like language best known for its turtle graphics. http://groups.google.com/groups?selm=mailman.855.1069193794.702.python-list at python.org Bryan J Gudorf releases Python Database Objects (PDO) 1.2.0. PDO provides an object oriented API, similar to that of ADO or JDBC, to python developers. http://groups.google.com/groups?selm=mailman.781.1069052156.702.python-list at python.org Robin Becker asks if there will be an alternative to rotor now that it is being deprecated, leading to a spirited discussion of encryption versus obfustication. http://groups.google.com/groups?threadm=b2BHKIAKJiu$Ew0g at jessikat.fsnet.co.uk Bob van der Poel is looking for internal data structure advice prompting Rony Steelandt to ask if Bob is writing an open source Band in a Box or Jammer product. http://groups.google.com/groups?threadm=3fbe4e63_1 at dns.sd54.bc.ca Tom Verbeure wants to examine sample code or existing open source projects that make heavy use of unit testing. http://groups.google.com/groups?threadm=e4804e26.0311170910.5ab9c208 at posting.google.com Pierre Denis releases Unum 4.0 beta, a Python module which allows you to work with units like volts, hours, meter-per-second or dollars-per-spam allowing you can play with true quantities instead of simple numbers. http://groups.google.com/groups?selm=3fb7dbfd$0$241$4d4efb8e at news.be.uu.net Tim Churches asks to verify a GPL licensing question. As always, it's easier asked than answered. http://groups.google.com/groups?threadm=mailman.981.1069465429.702.python-list at python.org Tim Peters follows up to Jeff Davis' puzzler on exponentiation algorithms. http://groups.google.com/groups?threadm=pan.2003.11.23.11.39.26.29737 at nospam.com MetalOne asks about functional style techniques in Python. http://groups.google.com/groups?threadm=92c59a2c.0311171648.6360213d at posting.google.com Newbie Andy Koch gets links to websites that have code of programs written in Python. http://groups.google.com/groups?threadm=VZvub.13922$Kb3.975852 at twister.southeast.rr.com Hung Jung wants to know the origin of the term "First-class object". http://groups.google.com/groups?threadm=8ef9bea6.0311171335.356a7af6 at posting.google.com Brian Lloyd announces the release of Zope 2.7.0 beta 3. http://groups.google.com/groups?selm=mailman.1069184229.22119.clpa-moderators at python.org Prabhu Ramachandran announces MayaVi Data Visualizer version 1.3, a scientific data visualizer written in Python and using the Visualization Toolkit (VTK) for graphics. http://groups.google.com/groups?selm=mailman.1069184226.21996.clpa-moderators at python.org The martellibot appears to have been off-line most of the week, and therefore perhaps missed this... or is this the explanation... :) http://www.greatbridgelinks.com/GBLArchives/YankeesWin.html ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least 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 The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ 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. *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 jimmy at retzlaff.com Mon Nov 17 15:01:51 2003 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Mon, 17 Nov 2003 12:01:51 -0800 Subject: True inconsistency in Python Message-ID: KefX wrote: ... > I'm not so sure about that. In most languages (including Python), 'false' > is guaranteed to be only one value (usually zero), therefore comparing > against it poses no problem. I assume you're saying that doing so isn't > problematic in any way, it's just pointless. In Python the singleton False has exactly one value (as does the singleton True), but there are many values that are treated as false when used as an expression being evaluated by "if" including 0, None, and empty containers ([], {}, "", sets.Set([]), etc.). Comparing a value directly to False in Python is not a good idea. So, for example, the following two "if" statements are not equivalent for all possible values of x: if not x: ... if x == False: ... The first will execute the body if x == [], the second will not. ... > But if whatever goes in "blah" is really long (and often it is), you very > quickly see what is being compared: it's a straight boolean comparison, > whereas with the second you have to look at the whole thing, find no > comparison operator, and go, "oh, there's no explicit comparison so it's > obviously an implicit straight boolean comparison". This is especially > valuable in really long 'if' statements ... I agree with Michael Geary that skipping the comparison to True/False reads much more cleanly. If the expression is too long to be clear, then you can (should?) encapsulate it in a function or variable that gives the expression a short descriptive name: if mouseClickPosition.InRectangle(self.left, self.top, self.right, self.bottom) == False: ... would probably be more clear like this: mouseClickInBoundingBox = mouseClickPosition.InRectangle( self.left, self.top, self.right, self.bottom) if mouseClickInBoundingBox: ... ... > Although, as a last thought, it should be relatively easy to make it so > that True returns '1' in any comparison except against 0. A class would be > able to do this easily by overriding __cmp__: > > def true_class(bool): > def __cmp__(self, other): > if other: > return 1 > else: > return 0 > > True = true_class() ... Similar functionality is already in recent versions of Python: >>> bool([]) False >>> bool([1, 2, 3]) True So, as I believe was pointed out earlier in this thread, if you're really eager to compare to True and/or False you can do the following safely: if bool(x) == True: ... if bool(x) == False: ... Jimmy From gumuz*NOSP at M*looze.net Thu Nov 27 18:25:11 2003 From: gumuz*NOSP at M*looze.net (Guyon Morée) Date: Fri, 28 Nov 2003 00:25:11 +0100 Subject: python gem Message-ID: <3fc687d4$0$164$1b62eedf@news.wanadoo.nl> i just found something which made me so happy :) while checking out the spambayes package i found a little module called: 'Dibbler'. I don't know if it's being offered somewhere seperate, but anyway I love it. it provides a very easy to create a standalone webserver and hosting dynamic pages. this way the spambayes web-interface is created. well, anyway i liked sharing this. cheers, Guyon From haris.bogdanovic at zg.htnet.hr Sun Nov 2 04:15:45 2003 From: haris.bogdanovic at zg.htnet.hr (Haris Bogdanovic) Date: Sun, 02 Nov 2003 10:15:45 +0100 Subject: simple echo server In-Reply-To: <3fa4395a$0$58698$e4fe514c@news.xs4all.nl> References: <3fa3fab9$0$58702$e4fe514c@news.xs4all.nl> <3FA4284A.6010701@zg.htnet.hr> <3fa4395a$0$58698$e4fe514c@news.xs4all.nl> Message-ID: <3FA4CB41.8080306@zg.htnet.hr> Irmen de Jong wrote: > Haris Bogdanovic wrote: > >> Irmen de Jong wrote: >> >>> Haris Bogdanovic wrote: >>> >>>> When client is trying to connect to the server everything works fine >>>> but when server tries to echo what it receieved from client I get >>>> access denied error. >>>> Why is that happening ? >>> >>> >>> >>> >>> Because the server has no access? >>> > > This was *important*: > >>> No really-- you have to give much more detailed information. >>> Preferrably the exact code fragment and exact error message >>> that you're getting. >>> >>> --Irmen > > > Now, where is this extra information? > >>> >> It's the example from python docs (socket section). If you have >> somewhere your personal user account you can try it aswell. >> Tell me what you managed to do. > > > I managed to get it to work just fine. > > And what do you mean with 'have your personal user account' ???? > > --Irmen > I ment telnet account. Is that the place where people normally put their server part of the application or can I put somewhere else (is there a common way to do this) ? Haris From and-google at doxdesk.com Sat Nov 29 13:51:54 2003 From: and-google at doxdesk.com (Andrew Clover) Date: 29 Nov 2003 10:51:54 -0800 Subject: python xml dom help please References: <2c60a528.0311240720.1db7f90d@posting.google.com> <87isl89shv.fsf@pobox.com> <2c60a528.0311261642.5478397d@posting.google.com> Message-ID: <2c60a528.0311291051.33b7d789@posting.google.com> spam.meplease at ntlworld.com (deglog) wrote: > actually i'm trying to change the relationship 'is next sibling of' to > 'is child of' throughout a document Well, the snippet in the posting above should do that well enough. What happens to any existing nested children is not defined. > How come the current node is back at the start atfter the loop has finished? Bug. I've just submitted a patch to the PyXML tracker to address this issue. (Note: earlier versions of TreeWalker - certainly 0.8.0 - have more significant bugs, that can lead to infinite recursion.) That said, I'm not sure how using a TreeWalker or walking backwards actually helps you here! If you are just using it to filter out non-element children, remember that moving the current node takes the position of the TreeWalker with it. It's not like NodeIterator. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From george.trojan at noaa.gov Mon Nov 3 18:24:58 2003 From: george.trojan at noaa.gov (George Trojan) Date: Mon, 03 Nov 2003 23:24:58 +0000 Subject: strptime performance Message-ID: Is time.strptime() intrinsically slow and should be avoided whenever possible? I have the following code in my application: def string2time(s): # Converts string %y%m%d%H%M to Unix time y = int(s[:2])+2000 m = int(s[2:4]) d = int(s[4:6]) H = int(s[6:8]) M = int(s[8:10]) return time.mktime((y, m, d, H, M, 0, 0, 0, 0)) # return time.mktime(time.strptime(s[:10], '%y%m%d%H%M')) Output from pstats is: ncalls tottime percall cumtime percall filename:lineno(function) 2215 0.030 0.000 0.030 0.000 /awips/adapt/avnfps/CE/py/Avn.py:41(string2time) When I use the commented out line instead, the code is about 60 times slower: 1456 0.080 0.000 1.270 0.001 /awips/adapt/avnfps/CE/py/Avn.py:41(string2time) ... 1456 0.020 0.000 0.770 0.001 /usr/local/python2.3/lib/python2.3/_strptime.py:396(compile) 1456 0.360 0.000 0.720 0.000 /usr/local/python2.3/lib/python2.3/_strptime.py:374(pattern) George From sombDELETE at pobox.ru Mon Nov 24 19:18:08 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Tue, 25 Nov 2003 03:18:08 +0300 Subject: 'from __future__ import ...' overview References: Message-ID: "Logan" wrote in message news:pan.2003.11.25.00.09.09.285370 at phreaker.nospam... > Is there a list with all 'from __future__ import ...' statements > (which lists all the statements, in which version of Python the > feature was introduced and in which version of Python it will become > the default behavior)? import __future__ print __future__.all_feature_names print __future__.division -- Serge From nospam at nospam.com Mon Nov 24 01:35:23 2003 From: nospam at nospam.com (Jeff Davis) Date: Mon, 24 Nov 2003 06:35:23 GMT Subject: strange exponentiation performance References: Message-ID: > I'm taking the liberty of rewriting your functions to stop trying to squash > as much as they can on each line. It's important to do that if you want to > modify the code quickly when experimenting. Fair enough. > > First you rediscovered the "left to right" binary exponentiation algorithm: > Interesting. > When you tried to remove recursion from it, you rediscovered the "right to > left" binary exponentiation algorithm: Interesting. I suspected it wasn't a perfect unwrapping of the recursion, because I didn't take the time to examine it carefully. Classic case of a wonderful idea I had at 3:30 in the morning :) > That's close to what Python's builtin ** does, but is missing an important > speed trick (explained later). Note that h and f aren't really the *same* > algorithm! f squares the current value of b on every trip through the loop. > h does not. If you print out all the inputs to all the multiplications, > you'll see that they're not at all the same. > Also interesting. > > Your box is faster than mine. Here under 2.3.2 on Windows: > That means I win, right ;) > exponentiation is a very hard problem; Knuth Volume 2 has an extensive > discussion of this ("Evaluation of Powers"); another algorithm based on > first factoring the exponent (expressing it as a product of primes) is > better "on average" than either binary method, but sometimes loses to > them. Ahh... I'm on vol. 1. I saw that it would be a while before I made it to page 100, so I actually loaned out vol. 2. I'll be getting that back now I guess :) > > def q(b, e): > if e == 0: > return 1 > if e == 1: > return b > e2, numbits = e, 0 > while e2: > e2 >>= 1 > numbits += 1 > assert numbits >= 2 > result = b > mask = 1L << (numbits - 2) > for dummy in range(numbits - 1): > result *= result > if e & mask: > result *= b > mask >>= 1 > return result > Now I understand what you mean about the right-left and left-right versions. I only had a vague understanding before. > That's bound to be a little faster than h on most inputs, because it > also optimizes away multiplications by 1 (well, unless b happens to be > 1). Let's see: Might as well eliminate the multiplication by 1, for some reason I assumed that could be optimized out somehow by the computer. > Yup, those matter, but not a whale of a lot. The savings in skipping > multiplications by 1 is proportional to the number of 0 bits in the > exponent. What *didn't* matter is whether it's recursive or iterative. Yeah, I guess it's always the case: algorithm first, then optimize. I know the rule, and I follow it when being paid (so as not to waste anyone's money). When doing something more academic I always feel like I need to break it down to the most simple operations so I understand what's going on. To me, recursion hides what's going on to an extent, and I felt like I didn't entirely understand the algorithm. >> If my algorithm h() is better, why can't ** use a quick test to change >> algorithms based on inputs? Or is mine better in all cases? > > See Knuth . > Uh-oh, another problem that's more difficult than meets the eye. I'll be back with more questions in a few years I guess ;) Thanks, Jeff From cbrown at metservice.com Tue Nov 11 20:50:24 2003 From: cbrown at metservice.com (Colin Brown) Date: Wed, 12 Nov 2003 14:50:24 +1300 Subject: Qn: Socket performance under Windows Message-ID: <3fb190df$1@news.iconz.co.nz> Python2.3.2: Running the following receiver and sender code in separate windows under Win2K does not work properly (missed & very delayed transmissions). Under Redhat Linux 9 (where I will be using it) it works fine (with up to 250 sending threads; I hit the thread limit at 255!) Any idea why do I not get any errors reported under Windows? Colin Brown PyNZ --[Sender.py]-------------------------------------------------------- # Send 50 'simultaneous' tcp transmissions to receiver import os,socket,sys,time,thread,traceback def error(): tb = traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info( )[2]) return tb[len(tb)-1].replace('\n','') class client: def __init__(self,nodeport): self.nodeport = nodeport self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.cli.settimeout(60.0) def connect(self): self.cli.connect((self.nodeport)) def write(self,data): self.cli.sendall(data) def close(self): self.cli.close() def send(v,data): cli = client(('localhost',20031)) for cnt in range(5): try: cli.connect() break except: if cnt == 4: print v,'Connect failure: ',error() else: time.sleep(0.3) try: cli.write(data) except: print v,'Send failure: ',error() cli.close() print v def action(data,number): for ii in range(1,1+number): thread.start_new_thread(send,(str(ii),data)) if __name__ == '__main__': action(''.join(['00001000',chr(32)*1000]),50) time.sleep(75.0) --[Receiver.py]------------------------------------------------------ import select,socket,thread, time COUNTER = 0 TIME0 = 0.0 class rx: def __init__(self,LocPort=20031,NumConn=100): self.svr = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.svr.bind (('', LocPort)) self.svr.listen(NumConn) def nextConnAddr(self): if select.select([self.svr], [], [], None)[0]: return self.svr.accept() else: raise 'SocketReceiver.rx.nextConnAddr','connection lost' def rxThread(self,recvr): thread.start_new_thread(newSession,(recvr,)) def close(self): self.svr.close() def newSession(conn): sess = session(conn) sess.run() class session: def __init__(self,conn,timeout=180.0): self.conn = conn self.conn.settimeout(timeout) def recvblock(self,length): block = [] size = length while size > 0: chunk = self.conn.recv(size) if chunk: block.append(chunk) size = size - len(chunk) else: raise 'Session.recvblock','connection lost' return ''.join(block) def getsize(self): length = self.recvblock(8) return int(length) def getdata(self,size): return self.recvblock(size) def run(self): global COUNTER, TIME0 data = self.getdata(self.getsize()) if len(data) != 1000: print 'Transmission error' else: COUNTER = COUNTER + 1 if TIME0 == 0.0: TIME0 = time.time() print '%i%s%0.3f' % (COUNTER,'\t',time.time()-TIME0) rcvr = rx() while 1: rcvr.rxThread(rcvr.nextConnAddr()[0]) ---------------------------------------------------------------------- From gh at ghaering.de Tue Nov 25 07:25:40 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 25 Nov 2003 13:25:40 +0100 Subject: Web Authentication to AD In-Reply-To: <3FC34866.40607@ghaering.de> References: <04875CB4331F0240A0AD66F970978651011376C8@paul> <3FC34866.40607@ghaering.de> Message-ID: <3FC34A44.9000200@ghaering.de> Gerhard H?ring wrote: > Jason Tesser wrote: > >> Has nobody tried to do this kind of thing? [...] > > Not me. However, the easiest solution probably to use the integrated > Windows authentication of IIS on win32. If it must run on Unix, you could probably let your web service run under Apache and use mod_ntlm for authentication. A freshmeat.net search for ntlm might also provide useful software for your task. I haven't tried any of these yet, though. -- Gerhard From johan at weknowthewayout.com Fri Nov 21 07:14:35 2003 From: johan at weknowthewayout.com (Johan Holst Nielsen) Date: Fri, 21 Nov 2003 13:14:35 +0100 Subject: Analyse of PDF (or EPS?) In-Reply-To: References: <3fbcc67e$0$9836$edfadb0f@dread14.news.tele.dk> Message-ID: <3fbe01cf$0$95037$edfadb0f@dread11.news.tele.dk> Grzegorz Makarewicz wrote: > Johan Holst Nielsen wrote: >> Is there any Python packages to analyse or get some information out of >> an PDF document... >> >> Like where the text are placed - what text are placed - fonts, >> embedded PDFs/fonts/images etc. >> >> Please let me know :) > > http://www.trisoft.com.pl/~mak/wxpdf.zip > > My first attempt to decode PDF-s with SWIG-ged xpdf, requires sources of > python and wxPython - binaries for python22 (windows) are included. Not Found The requested URL /~mak/wxpdf.zip was not found on this server. :( Can you please try to upload it again? Regards, Johan From administrators at sterling2000.co.uk Thu Nov 20 03:26:24 2003 From: administrators at sterling2000.co.uk (administrators at sterling2000.co.uk) Date: 20 Nov 2003 08:26:24 UT Subject: ADO Message-ID: Does anybody know anything about ADO disconnected recordsets. I have been searching the net for two weeks now but can find nothing on disconnected recordsets. I have been programming in VB6 for two years and have had quit a success with disconnected resordsets with the following code:- Dim acUpdateable As Connection Set acUpdateable = New Connection acUpdateable.Open gBRDataBase Set rsUpdateable = New ADODB.Recordset rsUpdateable.CursorLocation = adUseClient rsUpdateable.LockType = adLockBatchOptimistic rsUpdateable.CursorType = adOpenForwardOnly rsUpdateable.Open sSQL, acUpdateable rsUpdateable.MarshalOptions = adMarshalModifiedOnly Set rsUpdateable.ActiveConnection = Nothing acUpdateable.Close Set acUpdateable = Nothing I can implement most of this within Python but not the bit after Marshalling. I can read and write to the database but as soon as I try to disconnect the recordset Python cannot see the cursor. Is it possible to use disconnected recordsets with Python and if so where can I find information on the subject. Any help you can offer would be gratefully received. Martin -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Nov 14 13:17:36 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Nov 2003 13:17:36 -0500 Subject: Python's simplicity philosophy References: <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: "Douglas Alan" wrote in message news:lcvfpn46f6.fsf at gaffa.mit.edu... > > Even without any algebra, any kid can tell you that 1 + 2 is the same > > as 2 + 1. Replace 1 and 2 by a and b and you get the same result. > > Yes, but they are still two *different* ways to to get to that result. > Starting with a and adding b to it, is not the same thing as starting > with b and adding a to it. I disagree. Number addition (like several other functions) is a bag (multiset) reduction operator that reduces a (possibly empty) collection of similar items to one of the same type. Abstractly, the reduction is simultaneous. One appropriate notation for such operators is a simple labelled loop (in 2D) containing the items to be collected together. In linear text, such loops can be represented by matched symbols, such as ( ), [ ], { }, which then represent the intersection of a closed loop with a 'too-narrow' text band (which thereby chops off the top and bottom of the loop). When operands scattered in the loop interior are projected down to a 1+D band for text representation, they gain an ordering that is an artifact of that limited representation. (+ item item ...) and sum(item, item, ...) are both labelled loops with items arbitrarily but necessarily ordered for linear text representation. > It is only the commutative law of arithmetic, > as any good second grade student can tell you, > that guarantees that the result will be the same. Well, second graders are mislead by the representation of an n-ary bag operation with infix notation that implies binarity and order relevance. Learning about reduce should help one unlearn these implications ;-). Even with infix notation, there is a choice between making the default interpretation be order relevance or order irrelavance. If mathematicians had made the second choice, therr would be no need for a 'commutative law' One would say that a+b == b+a because that is the way it normally is, while a-b != b-a because of the OrderRelevance Law of subtraction. < On the other hand, not all mathematical groups are albelian, < and consequently, a + b != b + a for all mathematical groups. Yes, there are order-relevant binary-only operations. Number addition is not one of them. [Having written the above, I am less enthralled with the overloading of '+' and operator.add to also mean ordered concatenation of sequences. The fact that operator.add becomes O(n**2) (usually unnecessarily) instead of O(n) for such overloadings, to the point that sum() specially excludes such overloadings for strings, reinforces this doubt. Perhaps there should be at least be an operator.cat that would generalize ''.join(strseq)] Terry J. Reedy From john_bradbury at skipthistalk21.com Thu Nov 13 12:08:58 2003 From: john_bradbury at skipthistalk21.com (John Bradbury) Date: Thu, 13 Nov 2003 17:08:58 +0000 (UTC) Subject: GUI - Qt Designer References: Message-ID: Phil Thompson wrote: > On Wednesday 12 November 2003 6:04 pm, John Bradbury wrote: >> Is there any way to take the output produced by Qt designer (or any other >> GUI designer) and use it in Python to create a screen? There must be a >> better way of creating screens than having to use the TkInter routnes and >> add every widget one by one in the program. > > Use the pyuic utility that comes with PyQt. > > Phil Thanks everyone for the very helpful repsonses. It seems to be a topic whch is not covered fully in the books ( at least the ones I have). John From John_Dutcher at urmc.rochester.edu Wed Nov 19 13:41:02 2003 From: John_Dutcher at urmc.rochester.edu (John F Dutcher) Date: 19 Nov 2003 10:41:02 -0800 Subject: Using 'string.ljust' to try and hold a fixed width....... References: <2c82369d.0311190538.3789f2a1@posting.google.com> Message-ID: <2c82369d.0311191041.e5b1fa6@posting.google.com> There seems to be a difference between using IDLE to test the code and using the same code in my CGI script as follows: (I'm using Python 2.3.1) In the IDLE command shell this works exactly as expected, that is ending spaces are preserved when joined to the 'rec' string: ten = 'xxxxxxxxxx' recd = [] recd.append(string.ljust(ten,15)) recd.append(string.ljust(ten,15)) recd.append(string.ljust(ten,15)) rec = string.join(recd,'') print rec -----------------> ending spaces preserved ************************************************************* In my CGI script where I retrieve 'form' data nothing works.. The use of a string to receive the form field first, and then appending to 'recd'...or appending to 'recd' directly, both fail to preserve the spaces....(which are preserved very well in the IDLE mode using a string literal to start with, rather than 'form' data). recd = [] lname = string.ljust(form.getfirst("lname",' '),15) fname = string.ljust(form.getfirst("fname",' '),15) recd.append(lname) recd.append(fname) recstr = string.join(recd,'') print recstr ------------------> no ending spaces "Fredrik Lundh" wrote in message news:... > John F Dutcher wrote: > > > The spaces expected are 'NOT' being provided with 'string.ljust'.... > > > > If I simply print the field immediately as in: > > print string.ljust(form.getfirst("lname",' '),15) > > > > they are not present; they are not present when assigned to the list, > > and, of course, they are not present in the final string. > > are you sure they're not there, or is the problem just that print > doesn't show them to you? try using "repr" or "len": > > >>> import string > >>> print repr(string.ljust("field", 15)) > 'field ' > >>> print len(string.ljust("field", 15)) > 15 > > also note that ljust doesn't do anything if the input string is > longer than the field width: > > >>> print len(string.ljust("fieldfieldfieldfield", 15)) > 20 > > From fredrik at pythonware.com Wed Nov 19 17:24:05 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 19 Nov 2003 23:24:05 +0100 Subject: PIL, PNG and MIDP References: <971323274247EB44B9A01D0A3B424C8503662191@FTWMLVEM02.e2k.ad.ge.com> Message-ID: "Raaijmakers, Vincent (IndSys,GE Interlogix)" wrote: > MIDP ImageLoader is complaining right now about an invalid > CRC of the PNG?! Well, the image conversion is very basic, > Image.open('foo.jpg').save('foo.png', ''PNG') PIL has supported PNG since 1996; if PIL's PNG writer doesn't work, I'm pretty sure someone would have noticed that by now... it sounds like you 1) have a broken PIL build (a broken zlib, most likely) 2) are doing something with the data on the way out (binary/text mangling, or truncation) can PIL read images created by other PNG tools (e.g. imagemagick, pngtopnm, etc) on your box? can other tools than MIDP read PNG files created by PIL? From peter at engcorp.com Thu Nov 20 09:19:37 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Nov 2003 09:19:37 -0500 Subject: win32com with netscape References: Message-ID: <3FBCCD79.6B099DDD@engcorp.com> jeff wrote: > > does anyone know how to dispatch netscape with > win32com.client or using make.py? > I search every place I can include microsoft and > netscape and find nothing about it. > I tried to search ID from vc++, and couldn't find it > neither. > I am trying to open netscape browser with > win32com.client and navigate it. > can anyone help? Do you mean Mozilla? Or an older Netscape (e.g. 4.7)? From tjreedy at udel.edu Tue Nov 18 19:26:43 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Nov 2003 19:26:43 -0500 Subject: True inconsistency in Python References: <3FB8847F.6CB1BECA@alcyone.com> <83bjrvcm92o6l2gte1nbehrpvofm0r5i88@4ax.com> Message-ID: <67ydnRDIrq5ZJSeiRVn-vw@comcast.com> "Ron Adam" wrote in message news:83bjrvcm92o6l2gte1nbehrpvofm0r5i88 at 4ax.com... > I believe the words 'True' and 'False' need to be treated the same as > the digits 1, 2, 3, ... The values of the digits do not change. We > depend on them not changing. > True should always evaluate to True also. > So we can depend on it as well. > This is my opinion, you don't have to agree with it. Others have also proposed that None, True, and False be made keywords. We'll see how far Guido goes in 3.0. I do not think even he really knows. > >> It looks to me that 'True' in python is a combination of the boolean > >> binary logic of 1 or 0, and as an "exists" test of 0 or not 0. [me] > >I do not understand this. If you have a reference to 0, then 0 > >exists. If you do not, then the 'existence' or not of an int with > >value 0 is irrelevant. > if x: is a test to see if the value 0 does not exist in x. Aha. Got it. Above, you are using 'exist' at a different level of abstraction than I understood. I was thinking of object or binding existence, whereas you were speaking of value connotation. Yes, if c is a count of something, then 'if c:' tests for the positive existence of at least one counted something. Similarly for list L of somethings, 'if L:' tests for the existence of at least one listed something. I consider this 'overloading' of conditional expressions to be one of the great features of Python. I now take it for granted. > >> if x exists: > >> 'do something' > > > >Do you mean > >if bound_to_something('x'): > >? > > > > Yes, you understand. Whoops, now you are agreeing with 'exist' as 'binding existence'. Yes, this is a 'divergence' from your other sense of exist. > Yes, I noticed. The reason I bring this up is in situations where > you want to initialize a variable if it has not been defined yet, but > do not want to re initialize it if it's already been defined. For just one variable, I might use try: x except NameError: x = 'value' Terry J. Reedy From jjlee at lbl.gov Fri Nov 21 14:14:12 2003 From: jjlee at lbl.gov (John J. Lee) Date: Fri, 21 Nov 2003 11:14:12 -0800 Subject: pythoncom.connect() Message-ID: Dear, I have problems when I get the IDispatch with pythoncom.connect(). When I called the 'Excel.Application' with it, it worked. (At least I can see the pythoncom.connect() is working for the well-designed COM like Excel.) When I called my COM module which was derived from IDispatch interface, the pythoncom.connect() issued error like com_error: (-2147221021, 'Operation unavailable', None, None). Was my COM module badly desinged? This COM worked well with VB. Is there anybody who solved this kind of problems? I alse tried using the gencache.EnsureModule() after I generate a static COM file with makepy. In this way, I got the member function not available errors. Thank you. - john From __peter__ at web.de Fri Nov 28 07:43:12 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Nov 2003 13:43:12 +0100 Subject: math.pow vs pow References: <87k75lmlru.fsf@pobox.com> Message-ID: Georgy Pruss wrote: > > "John J. Lee" wrote in message > news:87k75lmlru.fsf at pobox.com... > | For some applications, getting a complex result means you've made a > | mistake. And some people don't know what a complex number is, and > | would rather have their teeth drilled than find out. > > Can you provide an example when pow with real arguments gives a complex > result, please? He could, if Python were not so reluctant: >>> pow(-5,.5) Traceback (most recent call last): File "", line 1, in ? ValueError: negative number cannot be raised to a fractional power Sad day for the dentist:-) But: >>> pow(complex(-5), .5) (1.3691515264124976e-16+2.2360679774997898j) >>> pow(-5, complex(.5)) (1.3691515264124976e-16+2.2360679774997898j) as you might expect. Peter From ianb at colorstudy.com Tue Nov 18 17:16:21 2003 From: ianb at colorstudy.com (Ian Bicking) Date: Tue, 18 Nov 2003 16:16:21 -0600 Subject: ANN: PyLogo 0.1 Message-ID: PyLogo 0.1 ========== This is the first public release of the still rough (but I think functional) PyLogo interpreter. PyLogo interprets the Logo language, an education Lisp-like language best known for its turtle graphics. Found at: http://pylogo.org Who Is This For? ================ This release is primarily targeted at other developers. Though PyLogo is a fairly complete Logo implementation, the programming environment is still rough. Because PyLogo is written in Python, this is a very easy interpreter to work with -- the code is small, it's easy to create new primitives using Python code, and there's already a wide array of interesting and useful Python libraries which are easily made accessible to Logo programs. It also inherits Python's rich object model (though it needs more work to make Python objects easier to work with), which makes it possible to avoid some of the more crude features of some Logo dialects with respect to properties (dictionaries), files, etc. What Does It Do Now? ==================== PyLogo implements all of the core Logo features (as far as I know), generally trying to match UCBLogo (the de facto standard Logo implementation). Like traditional Logo, it uses dynamic scoping and a global namespace. Unlike many young language implementation, the existence of bugs is given consideration -- errors produce tracebacks, and room exists for even more helpful error diagnostics. Turtle graphics are available, including multiple turtles. You can use multiple, concurrent threads in your Logo programs. (You can't use threads and turtles together -- yet) -- Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org From amk at amk.ca Sat Nov 15 17:30:04 2003 From: amk at amk.ca (A.M. Kuchling) Date: Sat, 15 Nov 2003 16:30:04 -0600 Subject: Gadfly DB in python standard library? References: <3fe406f0.0311141353.3aec780f@posting.google.com> Message-ID: On Sun, 16 Nov 2003 03:38:08 +1100, Anthony Baxter wrote: > I believe there is still merit to including an SQL database being in > the standard distribution of python - personally I could live with > sqlite being included. +1 from me. In retrospect, it probably would have been more useful to add sqlite than BerkeleyDB support to Python 2.3. --amk From johnk at aurema.commercial Thu Nov 27 18:55:04 2003 From: johnk at aurema.commercial (John Ky) Date: Fri, 28 Nov 2003 10:55:04 +1100 Subject: Conflicting gethostname function definition on Solaris 9 Message-ID: <1069977306.415163@cousin.sw.oz.au> Hello: Building Python works fine. Now I am trying to build my own python module on Solaris 9, but I'm getting the following conflict: In file included from /wrk/src/test/tools/local/include/python2.2/Python.h:62, from elxml.cpp:20: /wrk/src/test/tools/local/include/python2.2/pyport.h:333: declaration of C function `int gethostname(char*, int)' conflicts with /usr/include/unistd.h:274: previous declaration `int gethostname(char*, long unsigned int)' here Did I do something wrong? Thanks -John From mwh at python.net Fri Nov 7 08:07:40 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 7 Nov 2003 13:07:40 GMT Subject: try...finally is more powerful than I thought. References: <3faab4e8$0$559$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <7h38ymsfhzf.fsf@pc150.maths.bris.ac.uk> Brian Kelley writes: > def res(): > try: > a = 1 > return > finally: > print "do I get here?" > > res() > > outputs "do I get here?" > > I can't say why I didn't really expect this, the control flow is a > little wierd as the function isn't really returning at the "return" > statement but executing the bit in the finally: block and then > returning. I think :) > > That being said, I like it a lot. How is this working internally? > Does the finally get executed when try code block goes out of scope? > This would happen during a return or an exception which could explain > the magic. Internally, and locally to one function, leaving via returning a value and raising an exception is pretty similar. Cheers, mwh -- I'm not sure that the ability to create routing diagrams similar to pretzels with mad cow disease is actually a marketable skill. -- Steve Levin -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From don.romero at verizon.net Thu Nov 20 01:45:57 2003 From: don.romero at verizon.net (Don Romero) Date: Thu, 20 Nov 2003 06:45:57 GMT Subject: Matrix - Metaphors, Analogies and the REAL References: <3fb10a9e.42064405@news.cybermesa.com> Message-ID: > From: joconnor at cybermesa.com (Jay O'Connor) >> On Tue, 11 Nov 2003 12:20:58 GMT, "RaYzor" >> People who think the Matrix series of films are real in any way are amongst >> the saddest people on Earth. > Imagine if it was "Dark City" "The OMEN" From andy at wild-flower.co.uk Tue Nov 11 13:07:24 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Tue, 11 Nov 2003 18:07:24 +0000 Subject: screensaver In-Reply-To: <2259b0e2.0311060704.754a4b6e@posting.google.com> References: <2259b0e2.0311060704.754a4b6e@posting.google.com> Message-ID: <200311111807.24274.andy@wild-flower.co.uk> On Thursday 06 Nov 2003 3:04 pm, Michele Simionato wrote: > I would like to disable/enable the screensaver on a Win98 box with a > Python script. Any suggestion? Thanks, > > Michele Michele, there's probably a switch in the registy... check the MS site for details. i'm sure you know how to use the _winreg module ;-) good luck ps. sorry for the previous blank e-mail - twitchy mouse-finger ;-) -andyj From http Sun Nov 30 20:04:51 2003 From: http (Paul Rubin) Date: 30 Nov 2003 17:04:51 -0800 Subject: speed of spambayes? References: <7xznedqxyx.fsf_-_@ruckus.brouhaha.com> <87n0ad9xil.fsf@pobox.com> Message-ID: <7xn0adfivg.fsf@ruckus.brouhaha.com> jjl at pobox.com (John J. Lee) writes: > > Spamassassin right now but it takes around 1.5 seconds to process a > > message on a 2 ghz Athlon. I believe part of that time is spent doing > > network lookups to check the source addresses against various spam > > blacklists. I want to crunch through several gigabytes of spam > > folders to see if any legitimate messages got trapped, so need a fast > > Well, that's only a couple of days even if it's mostly CPU :-) No it's much more than a few days. My spamassassin-based classifier seems to process my mail files at about 20 MB per hour (maybe less), so 50 hours per GB (maybe more). I have about 5 GB of spam that I want to process, so that's at least 1.5 weeks of nonstop despamming. > > classifier with a low false negative rate (it's ok if the false > > positive rate isn't so low, since almost all the messages in these > > folders are already spam). > > You might want to tune it a bit first, then. Hmm, good point, spam filters are usually set up the other way. Thanks. From kylotan at hotmail.com Fri Nov 21 23:57:57 2003 From: kylotan at hotmail.com (Kylotan) Date: 21 Nov 2003 20:57:57 -0800 Subject: Frustration with Boa Constructor References: <7T02VNBM37943.8988541667@Gilgamesh-frog.org> Message-ID: <153fa67.0311212057.108a1119@posting.google.com> Bob Gailer wrote in message news:... > This is the 3rd time I've downloaded, installed and tried Boa. Each time I > meet with one frustration or another. This time I'm trying to go thru the > Getting Started, and find numerous places that the tutorial does not agree > with the reality or I try something and it does not work. I too found that the tutorial was inaccurate (perhaps just out of date), but I was able to guess what to do instead. Do you have any specific examples of problems that maybe myself or others could help with? > Has anyone had success with Boa Constructor? If so how did you learn it? > The tutorial clearly is not the way I can learn it. To be honest with you I gave up on Boa, the main reason being that it doesn't support wxSizers, which are useful - and with which the visual designer becomes less important anyway. But I can sympathise with your frustration. I think that one downside of Python having such great centralised documentation is that the other projects seem to be very poorly documented by comparison! Tutorials tend to be out of date, and a lot of the help I can find on various subjects seems to stop at 'hello world' and then jump directly to the tricks of the trade. I am attempting to learn how to use wxPython from their mailing list, from the demos that come with the package, and from the Wiki (http://wiki.wxpython.org/index.cgi/FrontPage). However, expect to have to do a lot of cross-referencing, as I couldn't find anything that could stand alone as a comprehensive guide. -- Ben Sizer From timr at probo.com Wed Nov 19 18:10:07 2003 From: timr at probo.com (Tim Roberts) Date: Wed, 19 Nov 2003 15:10:07 -0800 Subject: MS Access with VB for applications and python References: Message-ID: Uggen Kristin T wrote: > >For the first time, I am trying to program python in a windows-environment, >and now I am having some trouble with combining python and MS Access... > >This is what I want to do: >A MS Access database is started, this database has numerous VB-forms, and >one of those forms calls my python-program, so far so good. But before my >python-program quits, I want to call one of the VB-forms in the database. >This I haven't been able to find out how to do. Do you mean you need to DISPLAY an Access form, or do you mean you need to call a function in the associated code module? The first can be done, by using the Access object model. The second is more difficult. Access code modules are not COM objects, so you cannot call directly into them from outside of Access. However, through the object model, you should be able to use DoCmd, and that lets you call a macro or a public function. The Access object model is discussed on Microsoft's web site. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From adalke at mindspring.com Fri Nov 14 18:06:02 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 14 Nov 2003 23:06:02 GMT Subject: Python's simplicity philosophy References: <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> <%N8tb.28277$hV.1041253@news2.tin.it> Message-ID: Alex Martelli: > "added"? 'max' worked that way since well before I met Python. But > to be consistent with your other arguments, no doubt you'd argue for > a .sort() followed by [-1] as "more general" than max... Even better (tongue-in-cheek) would be a function to get the t largest (or s largest to t largest) without necessarily comparing between elements whose values are guaranteed out of range Just looked through Knuth for that. There are various ways listed, but no neat name to use for that function. :) Look under 'select k largest' and 'select kth largest'. Most of the hits are in the exercises. First one is for Hoare, and there's a reference to Dodgson (Carroll) and lawn tennis. Andrew dalke at dalkescientific.com From bokr at oz.net Mon Nov 17 14:43:48 2003 From: bokr at oz.net (Bengt Richter) Date: 17 Nov 2003 19:43:48 GMT Subject: Making a maze.... References: <1PSsb.44675$jy.34613@clgrps13> <221e7b06.0311170946.3baaa2ca@posting.google.com> Message-ID: On 17 Nov 2003 09:46:28 -0800, phil_nospam_schmidt at yahoo.com (Phil Schmidt) wrote: >I couldn't resist... >-------------------------------------------------- very pretty ;-) BTW, did you mean to prefix your code with something like from Tkinter import Canvas? [...] Regards, Bengt Richter From nessus at mit.edu Tue Nov 11 13:04:55 2003 From: nessus at mit.edu (Douglas Alan) Date: Tue, 11 Nov 2003 13:04:55 -0500 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: <7N6dnUz1P9CKZTOiRVn-hQ@comcast.com> Message-ID: "Terry Reedy" writes: > "Edward K. Ream" wrote in message >> > Such a request is *NOT* a legitimate 'anti-junk-mail' measure. >> Yes, it is. > Your request is unnecessary to the purported purpose and, to at least > three people, obnoxious. Furthermore, I believe universal > implementation of that system would be terrible, both socially and > technically. Although I agree with you that requiring people to fire up a browser to get yourself on their whitelist is a bit annoying, I also think you make much ado about nothing. Even if you had to spend 30 seconds authorizing yourself to everyone you ever needed to contact, it could hardly take all that much time. For now, the technique of just asking people to reply to a message is sufficient as an anti-spam filter, but you have to realize that such a convenience won't last forever. The spammers will eventually get smart enough to auto-reply to such messages. In the long run, the sorts of techniques that Yahoo, and other web sites, where you have to look at a distorted image and identify it (a task that cannot easily be automated), in order to put yourself on the list, will be required, so you should probably get used to it now. |>oug From simon at uggs.demon.co.uk Thu Nov 6 17:06:45 2003 From: simon at uggs.demon.co.uk (Simon Foster) Date: Thu, 06 Nov 2003 22:06:45 GMT Subject: Assembler Parser/Lexer in Python Message-ID: <3fabc59e.42407448@news.dsl.pipex.com> Anyone have any experience or pointers to how to go about creating a parser lexer for assemble in Python. I was thinking of using PLY but wonder whether it's too heavyweight for what I want. Anyone have any thoughts? -- Simon Foster Somewhere in the West of England From sfbell09 at yahoo.com Sat Nov 1 07:31:08 2003 From: sfbell09 at yahoo.com (sfbell09) Date: Sat, 01 Nov 2003 12:31:08 -0000 Subject: Py2exe and logging module Message-ID: Hi, My question is about the logging module and py2exe. When my code is in natural python, all of the logging works perfectly. I have two logging functions, one is a File Handler, the other is a SMTP handler. Once I build the code using py2exe, the File Handler still works, but the SMTP does not send any messages. 1. Any thoughts on why this might be happening. 2. Is there any way for the executable to return debugging information? It's a wxPython gui app. Thanks. From jcb at iteris.com Wed Nov 19 18:12:59 2003 From: jcb at iteris.com (MetalOne) Date: 19 Nov 2003 15:12:59 -0800 Subject: pros and cons of Tkinter in comparison with other GUI toolboxes, please? References: Message-ID: <92c59a2c.0311191512.194b201a@posting.google.com> GUI's come in two flavors. 1) Sometimes called heavyweight or native. This is a thin layer of code that wraps the underlying OS Native API. It provides for perfect native look and feel. Tk and wxWindows are of this type. The thin layer of code can actually become quite large due to differences between platforms. It is difficult to create an API that works well for all platforms. Linux platforms don't really have a standard native GUI API so the model breaks down a little here. wxWindows wraps GTK on Linux. 2) Sometimes called lightweight or emulation. This model just wraps basic raster operations, line, polygon, bitblit, etc. The widgets are created by the GUI toolkit. GTK, FOX, FLTK are of this type. This makes porting a toolkit easier. The widgets work the same on all platforms. The application can have the same look on all platforms or can be skinned to look like a native application. Usually the native look is off a little in some places. It is difficult to keep a native look and feel as MS and Apple change it all the time. The widgets can usually be extended by the programmer using inheritance. This is something that can't be done as well with heavyweight widgets. I only have experience with wxWindows so I can't comment on the others. I like the native look and feel of wxWindows on Windows. I don't like that Tk places a Tk icon in the control menu box. Maybe this can be changed? wxWindows has more widgets than Tk. However, I just bought "Learning Perl/Tk" from O'Reily. It was on the discount rack at Barnes and Noble for $5.00. From scott.b.drummonds.nospam at intel.com Mon Nov 10 16:45:44 2003 From: scott.b.drummonds.nospam at intel.com (Scott Brady Drummonds) Date: Mon, 10 Nov 2003 13:45:44 -0800 Subject: Blocking readline() Call? References: Message-ID: "Scott Brady Drummonds" wrote in message news:booqnf$ioc$1 at news01.intel.com... > Hi, everyone, > > I'm just figuring Python out but have become stalled with the following > snippit of code: [code deleted] JP said: > I think you mean "break" here, not "continue". Peter said: > Correct this: you want "break", not continue Mel said: > 'continue' doesn't mean what you think it means. Try 'break'. So, what is it that you people are trying to tell me? Please don't beat around the bush. Scott P.S. Sarcasm aside, thanks to all three of you for pointing out my very basic mistake. :) From mak at trisoft.com.pl Fri Nov 21 08:46:26 2003 From: mak at trisoft.com.pl (Grzegorz Makarewicz) Date: Fri, 21 Nov 2003 14:46:26 +0100 Subject: Analyse of PDF (or EPS?) In-Reply-To: <3fbe01cf$0$95037$edfadb0f@dread11.news.tele.dk> References: <3fbcc67e$0$9836$edfadb0f@dread14.news.tele.dk> <3fbe01cf$0$95037$edfadb0f@dread11.news.tele.dk> Message-ID: <3FBE1732.2080407@trisoft.com.pl> Johan Holst Nielsen wrote: [...] > Not Found > The requested URL /~mak/wxpdf.zip was not found on this server. > > Can you please try to upload it again? > > Johan > Sorry for the missing link, this one works: http://www.trisoft.com.pl/mak/wxpdf.zip Regards, Grzegorz Makarewicz From fpetermaas at netscape.net Thu Nov 27 03:56:45 2003 From: fpetermaas at netscape.net (Peter Maas) Date: Thu, 27 Nov 2003 09:56:45 +0100 Subject: Choosing the right framework In-Reply-To: References: Message-ID: David McNab schrieb: > I've been working on an HTML generation framework called 'pyWeb'. Just > posted to this ng yesterday, calling for testers. looks good. But the online documentation links are broken. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From jjl at pobox.com Sun Nov 30 10:30:28 2003 From: jjl at pobox.com (John J. Lee) Date: 30 Nov 2003 15:30:28 +0000 Subject: Standard way of documenting python code ? References: Message-ID: <87u14lq3fv.fsf@pobox.com> Rony writes: > A question on python source documentation. > Does there exist a standard for documenting code ? > I've included here an example generated by pydoc of one of my modules. > Is this the right way or is it overkill ? > Comments are appreciated [...] http://www.python.org/peps/pep-0008.html There are some good guidelines about docstrings in there. If you're writing in English, error is spelled "error", not "erreur". :-) John From sfbell09 at yahoo.com Sun Nov 2 09:04:29 2003 From: sfbell09 at yahoo.com (sfbell09) Date: Sun, 02 Nov 2003 14:04:29 -0000 Subject: Py2exe and logging module In-Reply-To: Message-ID: I found the solution to the problem using Joe's advice. I built the application using the --console option. This let me see that the smtp logger was failing because of an encoding issue with IDNA. So, using the py2exe flag --packages encodings and also encoding the server name as a string solved the problem. --- In python-list at yahoogroups.com, Joe Francia wrote: > sfbell09 wrote: > > Hi, > > > > My question is about the logging module and py2exe. When my code is in > > natural python, all of the logging works perfectly. I have two logging > > functions, one is a File Handler, the other is a SMTP handler. Once I > > build the code using py2exe, the File Handler still works, but the > > SMTP does not send any messages. > > > > 1. Any thoughts on why this might be happening. > > 2. Is there any way for the executable to return debugging > > information? It's a wxPython gui app. > > > > Thanks. > > > A quick & dirty way is to build with py2exe's --console option, and > traceback will print in the DOS window (which will close if your app > quits - so handle those exceptions). > > Other suggestions: run in a debugger, or log activities to a file or to > a separate wxPython frame|statusbar|text control. > > Peace, > Joe > > -- > http://mail.python.org/mailman/listinfo/python-list From bignose-hates-spam at and-benfinney-does-too.id.au Fri Nov 7 16:41:01 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 8 Nov 2003 08:31:01 +1050 Subject: Request for simple a customisable Python editor References: Message-ID: On Fri, 7 Nov 2003 11:43:54 +0000, stephenlee at exe-coll.ac.uk wrote: > I want to develop a simple Python program to edit source code that is > persisted in a database (memo fields). > The code to be edited is iHTML and SQL and I want syntax colouring and > good basic features including tabs for multiple 'files' and searching. > It will be a Win32 deployment. Much better would be to allow the editor used to be chosen by the user, and supply a reasonable default. Editors are powerful beasts, and forcing someone familiar with one to use a different one for your application is not a user-friendly design choice. Pick an editor that you think is a good default, but invoke it with a command-line only, *don't* build it into your application. That way, you can provide a customisation option to change the editor command line, and the user can substitute their favourite editor if they choose. -- \ "One thing vampire children have to be taught early on is, | `\ don't run with a wooden stake." -- Jack Handey | _o__) | Ben Finney From aahz at pythoncraft.com Wed Nov 12 23:25:58 2003 From: aahz at pythoncraft.com (Aahz) Date: 12 Nov 2003 23:25:58 -0500 Subject: looking for a name for a python SIP phone References: Message-ID: In article , Anthony Baxter wrote: > > [...] All right, did anyone else translate "SIP" as "Strangers in Paradise"? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From bkelley at wi.mit.edu Thu Nov 6 15:55:09 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 06 Nov 2003 15:55:09 -0500 Subject: try...finally is more powerful than I thought. Message-ID: <3faab4e8$0$559$b45e6eb0@senator-bedfellow.mit.edu> def res(): try: a = 1 return finally: print "do I get here?" res() outputs "do I get here?" I can't say why I didn't really expect this, the control flow is a little wierd as the function isn't really returning at the "return" statement but executing the bit in the finally: block and then returning. I think :) That being said, I like it a lot. How is this working internally? Does the finally get executed when try code block goes out of scope? This would happen during a return or an exception which could explain the magic. Brian From dave_member at newsguy.com Thu Nov 13 15:15:16 2003 From: dave_member at newsguy.com (dave) Date: 13 Nov 2003 12:15:16 -0800 Subject: python-2.3.2 and pth Message-ID: Hi all: did anyone have problem with "--with-pth" when compiling python-2.3.2 on solaris2.9? tia From peter at engcorp.com Mon Nov 3 15:21:04 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Nov 2003 15:21:04 -0500 Subject: Does python always need to compile ENTIRE program before it canstart to run it??? References: Message-ID: <3FA6B8B0.A2449A19@engcorp.com> "Michael T. Babcock" wrote: > > > > make ; myprogram > > > > > >I am trying to think of an advantage Python has over this hack.... > > > >Is it true that unlike C/C++ that Python programs can start executing > >before compilation is COMPLETELY done??? I think so but I'm not sure. > > > > Yes. You can have Python code that wouldn't "compile" but still runs. > As long as the paths the interpreter takes have no errors, you're fine > (minor exception of syntax errors). > > class a: > def __init__(self): > help # syntax error if we initialize an instance of a() > > print "hello world" > > ... that'll still run 'fine' because you don't use "a" > > That said, the "compilation" time of a Python program is almost > nonexistant in most cases. Most of the work is runtime; load a class, > wait for the class to compile, and so on.. That's not *exactly* true, I'm afraid. The above example would actually raise a NameError, since the name "help" is not defined at the time of execution, if you tried constructing an a(). SyntaxErrors for the most part come during compilation only (I'm not sure if there are any exceptions to that, but I'm not aware of any), and compilation is done on a module *prior* to execution, unlike some other languages where the source itself is interpreted and there is not really a compilation phase. Therefore I believe your first statement is actually not true, and in fact Python code that "wouldn't compile" actually cannot be run, because it has to be compiled prior to running. -Peter From jbublitzno at spamnwinternet.com Sun Nov 9 21:15:03 2003 From: jbublitzno at spamnwinternet.com (Jim Bublitz) Date: Mon, 10 Nov 2003 02:15:03 GMT Subject: PyQt and DCOP Documentation References: Message-ID: <1xCrb.3888$5b1.1118845065@twister2.starband.net> Eric Williams wrote: > Is there any reasonable documentation (i.e., with full examples > and/or code > snippets or argument lists or anything) to be found for using > python with > Qt/DCOP? "Fully Implemented." does not constitute complete > documentation when you're c++ illiterate. > > I'm actually just trying to get the volume level out of noatun > in a python script, if anyone can help me with an example. > What, exactly, does one DO with a QByteArray in python? >>> from qt import QByteArray >>> qb = QByteArray () >>> qb.duplicate ("Hello") >>> qb.data() 'Hello' But you should be able to use a Python string anywhere you need a QByteArray, so the above shouldn't be necessary. I'll check out the rest, but I'll have to see if I have noatun working first - may take a little while to get to it (dinnertime). PyQt is supported on the PyKDE list: PyKDE at mats.imk.fraunhofer.de http://mats.imk.fraunhofer.de/mailman/listinfo/pykde Jim > class Noatun(dcop.DCOPClient): > def __init__(self): > dcop.DCOPClient.__init__(self) > self.appname="NoatunPeeker" > self.attach() > self.registerAs(self.appname) > if self.isAttached(): > self.rc = > dcop.DCOPRef("noatun","Noatun") > else: > print "Couldn't attach!" > sys.exit(1) > > def getvol(self): > res = self.rc.call("volume()") > if res.isValid(): > return str(res.data) > #returns '(' why? > else: > return "Couldn't call" > > def gettitle(self): > res = self.rc.call("title()") > if res.isValid(): > return str(res.data) > #works as expected > else: > return "Couldn't call" > > if __name__=="__main__": > n = Noatun() > print n.getvol() > print n.gettitle() From stillcreek at chartermi.nojnk.net Sun Nov 9 09:09:26 2003 From: stillcreek at chartermi.nojnk.net (Kathy Poniatowski) Date: Sun, 9 Nov 2003 09:09:26 -0500 Subject: running a script like a daemon References: <3fad23ea$0$235$636a55ce@news.free.fr> Message-ID: In most flavors of Unix, you can append the '&' character to the command, which causes it to execute as a background process, and prepend 'nohup' to it, which I think makes it continue even if you log off. I'm not a Unix expert, so my explanation may be flawed, but this is what works for me: nohup command & Jp "ivan le magnifique" wrote in message news:3fad23ea$0$235$636a55ce at news.free.fr... > Hi there. > I would like to know how to launch a script from the command line (like via > telnet) with the ability to exit the command line without stopping the > thead. > Afterwards I would like to be able to retrieve the id of the thread to kill > it. > I know this is not really Python related since I have had the problem with > Java already ( before my conversion to Python)... but, any idea would be > appreciated. > > Thanks :) > > > From mwilson at the-wire.com Tue Nov 18 10:07:10 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 18 Nov 2003 10:07:10 -0500 Subject: Origin of the term "first-class object" References: <8ef9bea6.0311171335.356a7af6@posting.google.com> Message-ID: In article , Ben Finney wrote: >On Tue, 18 Nov 2003 03:01:35 GMT, Rainer Deyke wrote: >> John Roth wrote: >>> I can't think of anything I can't do with a name that I might want >>> to. >> >> One would be passing a name as an argument >> to a function. > >To accomplish what? What would you be doing with the name that you >can't do just as easily by passing the object (by reference, as always >happens in Python)? That's rather beside the point, isn't it? People continually come to c.l.p asking how to get the names of function parameters. Some are trying to write diagnostic routines. Some people want to know how to make data names out of user input strings; we tell them to for heaven's sake use a dictionary. It's not unreasonable to give names as an example of second-class objects in Python. And a good thing, as you and I think. Names are first-class in natural human languages, and look what happens: "...The name of the song is called 'Haddocks' Eyes'." "Oh, that's the name of the song, is it?" Alice said, trying to feel interested. "No, you don't understand," the Knight said, looking a little vexed. "That's what the name is _called_. The name really is 'The Aged Aged Man'." "Then I ought to have said 'That's what the song is called'?" Alice corrected herself. "No, you oughtn't! That's quite another thing! The song is called 'Ways and Means': but that's only what it's called, you know." "Well, what is the song then?" said Alice, who was by this time completely bewildered. "I was coming to that," the Knight said. "The song really is 'A-sitting on a Gate', and the tune's my own invention." _Through the Looking Glass_, of course Lewis Carroll Regards. Mel. From tim.jarman at lineone.net Wed Nov 12 16:51:51 2003 From: tim.jarman at lineone.net (Tim Jarman) Date: Wed, 12 Nov 2003 21:51:51 +0000 Subject: Am I the only one who would love these extentions? - Python 3.0proposals (long) In-Reply-To: <04e601c3a943$ac9dc6b0$891e140a@YODA> References: <04e601c3a943$ac9dc6b0$891e140a@YODA> Message-ID: <200311122151.51959.tim.jarman@lineone.net> On Wednesday 12 Nov 2003 5:37 pm, Dave Brueck wrote: > > I like some of your suggestions, like enum. > > I wouldn't mind having a standard module include something like this: > > class Enumerate(object): > def __init__(self, names): > for number, name in enumerate(names.split()): > setattr(self, name, number) > > WORK = Enumerate('NONE WRITE READ SENDFILE CONNECT ACCEPT') > > I like it better than C-style enums because it's clear that the element > comes from a particular enumeration, e.g.: > > workFlags = WORK.WRITE > > -Dave I knocked this up when I was after something similar: # Utility class to manage a set of named integer constants within a namespace. class Enum(object): """Class to manage a set of named integer constants within a namespace. Examples: Enum("RED", "GREEN", "BLUE") creates constants RED=1, GREEN=2, BLUE=3. Enum(RED=1, GREEN=2, BLUE=4) creates constants RED=1, GREEN=2, BLUE=4. Enum("RED", "GREEN", "BLUE", BLACK=0) creates BLACK=0, RED=1, GREEN=2, BLUE=3. These values are created as attributes of the Enum instance, thus: constants = Enum("RED", "GREEN", "BLUE") constants.RED # -> 1 """ def __init__(self, *names, **pairs): """Create an attribute for each name. Positional arguments are assigned a sequential integer value starting from 1. Named arguments are assigned the supplied value. """ self._lookup = {} value = 1 for name in names: setattr(self, name, value) self._lookup[value] = name value += 1 for name, value in pairs.items(): if hasattr(self, name): raise ValueError("Name %s specified more than once." % name) setattr(self, name, value) self._lookup[value] = name value += 1 def lookup(self, value): """Return the name corresponding to a given value. Example: constants = Enum("RED", "GREEN", "BLUE") constants.lookup(1) # returns "RED" """ return self._lookup[value] def isValid(self, value): """Return True if value is a valid constant, False otherwise. Example: constants = Enum("RED", "GREEN", "BLUE") constants.isValid(1) # returns True constants.isValid(42) # returns False """ return self._lookup.has_key(value) def __repr__(self): """Make a nice description of enum contents.""" desc = ["") return "".join(desc) I don't claim that this is the One True Answer but it works for me. It has the advantage of going both ways - it can be handy for debugging if you can map the value 42 to the name SPAM. regards, Tim J (an ex-Delphi programmer :) From newsgroup_mail at net.aristoweb Tue Nov 18 01:14:07 2003 From: newsgroup_mail at net.aristoweb (Corey Lubin) Date: Tue, 18 Nov 2003 06:14:07 GMT Subject: Overriding variables used by base classes References: Message-ID: bokr at oz.net (Bengt Richter) wrote in news:bp3o7o$dh6$0 at 216.39.172.122: > Still not 100% sure what you're doing, but suppose that you wanted to > get the effect of modifying HTMLParser.py without modifying the > original file, and be able to proceed as if your modified file were > "myHTMLParser.py". Basically, yes. I want to effectively make a copy of a module and then make adjustments to [the behaviour of] the copy, not to the original. > I think you could make a small actual myHTMLParser.py that starts by > _executing_ (not importing) the code of the original HTMLParser, and > then just modfies the result of that as desired. E.g., (untested > beyond what you see below ;-) This could achieve what I want. However, I mentioned exec/eval in my question and even then that was only in an attempt to state what I hope I need not do. This approach strays even further down that road of by exec'ing the entire file, getting even more complex and scary. In short, this is not where I want to go. > Maybe this gives some ideas? It's not a subclass/base class thing, but > maybe it will do what you need. Of course, you could subclass or > rebind or whatever in the mod code (which only executes when you > import myHTMLParser, BTW). No, it wasn't a sub/base class thing, but that wasn't a significant requirement and you solved the real issue; I was just hoping for a solution that is supported more directly by the language. > Regards, > Bengt Richter Thanks for the time you put into the suggestion. The concept of this approach might be useful in the future. - Corey Lubin From tchur at optushome.com.au Sun Nov 9 00:30:34 2003 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 09 Nov 2003 16:30:34 +1100 Subject: Status of JPE (Java-Python Extension)? Message-ID: <200311090530.hA95UZl27134@mail010.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From radam2 at tampabay.rr.com Mon Nov 10 16:39:55 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Mon, 10 Nov 2003 21:39:55 GMT Subject: True, False, None (was re. Pruss's manifesto) References: <20031110065915.07735.00000461@mb-m07.aol.com> Message-ID: <6h00rv40ro8sg29kbf7n22o62j6739t5e6@4ax.com> On Mon, 10 Nov 2003 13:41:59 GMT, Alex Martelli wrote: > >[alex at lancelot test]$ timeit.py -c -s'import itertools as it' 'c=it.count()' >'while True:' ' if c.next()>99: break' >10000 loops, best of 3: 91 usec per loop > >[alex at lancelot test]$ timeit.py -c -s'import itertools as it' 'c=it.count()' >'while 1:' ' if c.next()>99: break' >10000 loops, best of 3: 76 usec per loop > >...it still seems silly to slow things down by 20% w/o good reason... > Is it possible to make the argument optional for while? That may allow for an even faster time? while: It would be the equivalent as making the default argument for while equal to 1 or True. Could it optimize to single cpu instruction when that format is used? No checks or look ups at all? _Ron Adam From newsgroups at jhrothjr.com Sat Nov 1 11:40:36 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 1 Nov 2003 11:40:36 -0500 Subject: prePEP: Decimal data type References: <3cd884n4.fsf@yahoo.co.uk> Message-ID: "Paul Moore" wrote in message news:3cd884n4.fsf at yahoo.co.uk... > "John Roth" writes: > > >> The idea is to have a Decimal data type, for every use where decimals are > >> needed but floating point is too inexact. > >> > >> The Decimal data type should support the Python standard functions and > >> operations and must comply the decimal arithmetic ANSI standard > >> X3.274-1996. > > > > Why is ANSI 274 significant? The reason I ask this is that this is > > a ***floating point*** standard, and I don't think that we particularly > > care for decimal floating point. > > To be honest, I have little if any practical experience with numeric > representation issues, but it seems sensible to me to implement a > pre-existing, and presumably well thought out, standard, rather than > inventing something ad-hoc. > > Of course, if the need is for something other than what ANSI 274 > standardises, which seems to be what you are implying, then fair > enough. But what do you require? Infinite-precision decimal > arithmetic? If so, can you explain how you'd handle something like > 1/3? As I said in the response to Alex, division is the one place where fixed decimal gets into trouble. To repeat what I said to him, I'd eliminate the division operators completely, and replace them with a div(dividend, divisor, [resultplaces], [roundingpolicy]) operator. The division operators make a hidden assumption that they know what you want. That's ok for floating point, and it's inherent for rationals, but it doesn't really work for integers or fixed decimal. In the spirit of explicit is better than implicit, I'd rather have the control inherent in a div() operator. > > (I'm not being deliberately awkward here - my impression is that > representation issues are *hard*, and there are a lot of traps you can > fall into by oversimplifying. That's why I prefer the idea of a > pre-existing standard: it implies that *someone* has thought about the > hard stuff). > > > Floating point presumes limited precision. In other words, if the actual > > number (exclusive of the location of the decimal point) gets too large, > > the least significant part is ... thrown away. I don't want that. > > > > Since we've got infinite precision integer arithmetic, going to > > limited precision decimal arithmetic is, IMNSHO, a step backwards. > > Even infinite precision integers throw away information, in some > sense. Witness: > > >>> 1L//3L > 0L Same comment. Integer division, as it's currently implemented, is simply wrong. However, we had that discussion and decided to take one of the several different approaches, flying in the face of the evidence that any choice was not going to be useable in some context. When you try to simplify an inherently complex situation by putting a pretty face on it, all you do is confuse the issue more. > > >> When passing floating point to the constructor, what should happen? > >> > >> j. ``Decimal(1.1) == Decimal('1.1')`` > >> k. ``Decimal(1.1) == > >> Decimal('110000000000000008881784197001252...e-51')`` > > > > Clearly, j is the correct answer. It's not all that hard to do, either. > > No way. Consider: > > >>> 1.1 > 1.1000000000000001 > >>> 1.1==1.1000000000000001 > True > > So what should Decimal(1.1000000000000001) evaluate to? It can't be > Decimal('1.1'), as that contradicts your statement that j "clearly" > applies. But it *also* can't be Decimal('1.1000000000000001'), as then > we have the *same number* converting to two *different* Decimal > values. > > As I say, it's hard. Not that hard. It's not at all difficult to find where the actual number ends and where the fuzz begins. You can do it visually, and the algorithms to do it are quite well known. That's how printing libraries handle the issue, after all. You can also special case that with some lightweight compiler magic. All that really has to happen is that the lexer has to pass the 1.1 to the compiler without converting it to a float first, then the parser can apply a special rule when it sees that token in the context of decimal(1.1). > I'd probably support Decimal(float) giving an exception, on the basis > that if you're doing this, you probably don't know what you're getting > into :-) Having a special method, say Decimal.round_float(f, digits), > is probably OK, though... I think someone earlier suggested (in the context of the Money type) having the number of digits be an optional arguement to the constructor. That is: decimal(1.1, 1) showing one place after the decimal point. However, I prefer having the compiler take care of it. John Roth > > Paul. > -- > This signature intentionally left blank From bdelmee at advalvas.REMOVEME.be Mon Nov 17 18:22:32 2003 From: bdelmee at advalvas.REMOVEME.be (=?ISO-8859-1?Q?Bernard_Delm=E9e?=) Date: Tue, 18 Nov 2003 00:22:32 +0100 Subject: ActivePython Installation problem on win95 In-Reply-To: References: Message-ID: <3fb957fe$0$1125$6c56d894@feed0.news.be.easynet.net> > After installing (completes without error) I cannot start the PythonWin IDE; > get an error: "The application can not locate win32ui.pyd for Python (1157). Hi; did you reboot after installing? I suspect on Win9x the path will only include python after you've run the altered autoexec.bat HTH From for_usenet2000 at yahoo.de Sat Nov 1 15:48:54 2003 From: for_usenet2000 at yahoo.de (Daniel Schüle) Date: Sat, 1 Nov 2003 21:48:54 +0100 Subject: newbe questions References: Message-ID: [..] > your __init__ method lacks a second underscore. BTW: Why do you use inner > classes at all? The make sense in e.g. java, because they can overcome some > limitations in java itself. The only thing I ever used them in c++ was to > create a sort of namespace, which is also not neccessary because of > modules. What are your reasons for using them? thank you for your quick answear i dont really need them, i was just playing with python and possibilities of this language in C++ i use them to emphasis the logical relationsship of some classes to each other for example class list{/**/class node {/**/} }; class tree{/**/class node {/**/} }; or for the iterator implementation -- Daniel From see_signature__ at hotmail.com Sat Nov 29 23:30:09 2003 From: see_signature__ at hotmail.com (Georgy Pruss) Date: Sun, 30 Nov 2003 04:30:09 GMT Subject: Bug in glob.glob for files w/o extentions in Windows References: Message-ID: OK, you can call it not a bug, but different behavior. I've found that the fnmatch module is the reason for that. Here's other examples: C:\temp>dir /b *.* .eee aaa.aaa nnn C:\temp>dir /b * # it's by def synonym for *.* .eee aaa.aaa nnn C:\temp>dir /b .* .eee C:\temp>dir /b *. # it looks strange too .eee nnn C:\temp>python >>> import glob >>> glob.glob('*.*') ['aaa.aaa'] >>> glob.glob('*') ['aaa.aaa', 'nnn'] >>> glob.glob('.*') ['.eee'] >>> glob.glob('*.') [] It seems that in any case I'll have to extract 'nnn' by myself. Something like: if mask.endswith('.'): # no extention implies actually no dots in name at all list = glob.glob( mask[:-1] ) list = filter( lambda x: '.' not in x, list ) # or [x for x in list if '.' not in x] else: list = glob.glob( mask ) G-: From peter at engcorp.com Mon Nov 10 16:02:27 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Nov 2003 16:02:27 -0500 Subject: Matrix - Metaphors, Analogies and the REAL References: <3FAFE026.7EF6F2F5@engcorp.com> <3FAFF339.E499F960@engcorp.com> Message-ID: <3FAFFCE3.FF878E62@engcorp.com> 3seas wrote: > > Its in python code > > http://threeseas.net/vic/vic/ And this relates to your original post... how? From max at alcyone.com Sun Nov 2 23:32:33 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 02 Nov 2003 20:32:33 -0800 Subject: Weird asyncore behaviour References: <3fa58d78_1@news.adelaide.pipenetworks.com> Message-ID: <3FA5DA61.CC578F9B@alcyone.com> Freddie wrote: > class async_http(asyncore.dispatcher): > def __init__(self, parent, returnme, url, seen={}): ^^ This is your problem. Default arguments are only created once, so the default seen argument is the same physical object shared by all invocations of that method. That isn't what you want, as it will accumulate changes. Instead use the idiom: def f(dictArg=None): if dictArg is None: dictArg = {} # create a new one each time ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I never loved another person the way I loved myself. \__/ Mae West From bignose-hates-spam at and-benfinney-does-too.id.au Mon Nov 17 19:38:09 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 18 Nov 2003 11:28:09 +1050 Subject: Can this be written more concisely in a functional style References: <92c59a2c.0311171648.6360213d@posting.google.com> Message-ID: On 17 Nov 2003 16:48:36 -0800, MetalOne wrote: > 1) > def f(xs): > for x in xs: > if test(x): return True > return False Makes it obvious that there is a way for the iternation to end early. > 2) > return True in map(test,xs) Strongly implies ("foo in list", "map()") that the entire list will be iterated. Any other behaviour would be unexpected to the person reading the code. > I know that I can do (2), but it operates on the whole list and the > original may break out early. I want the efficiency of (1), but the > conciseness of (2). I think that in seeking to make it more concise, you're also seeking to make it less obvious. Anything that has the semantics of "loop over the whole list" in a single statement, isn't going to help people understand that a common case is for the iteration to end early. Which is probably a good reason for it not to appear. If you want to hide the algorithm, do so inside a helper function. Then you have consision in the places where you're actually using it, and explicit semantics where the algorithm is implemented. -- \ "A cynic is a man who, when he smells flowers, looks around for | `\ a coffin." -- Henry L. Mencken | _o__) | Ben Finney From nomail at hursley.ibm.com Fri Nov 21 02:41:30 2003 From: nomail at hursley.ibm.com (Derek Fountain) Date: Fri, 21 Nov 2003 15:41:30 +0800 Subject: Exceptions, assigning a tuple References: <3fbdb857$0$1727$5a62ac22@freenews.iinet.net.au> <3FBDBA3E.23D54A7C@alcyone.com> <3fbdbbdf$0$1739$5a62ac22@freenews.iinet.net.au> <3FBDBDED.D37C503F@alcyone.com> Message-ID: <3fbdc12f$0$1734$5a62ac22@freenews.iinet.net.au> > The "exception parameter" is an exception object, which knows how to > behave like a tuple. OK, and what gives it that ability? I tried tuple(f), where f was a file object. It gave me the contents of the file! I tried it again on an instance of one of my own objects and got a "TypeError: iteration over non-sequence" exception. It must be possible to give a class the ability to present itself as a tuple. How is that done? From edvard+news at majakari.net Tue Nov 4 09:13:22 2003 From: edvard+news at majakari.net (Edvard Majakari) Date: Tue, 04 Nov 2003 16:13:22 +0200 Subject: Using debug print routine inside assert References: <8765i072jh.fsf@titan.staselog.com> <3FA7AA9D.A2028E2D@engcorp.com> Message-ID: <87ism05iil.fsf@titan.staselog.com> Peter Hansen writes: Hi! > My solution has been to dispense completely with "debugging code" > except *during* debugging (when a print or two might appear temporarily, > or a call to pdb.set_trace()), and instead do all my development using > unit tests. Now, if I had to name a person for Father of All Unit Testing Advocates, I think I knew who'd I name... ;) > With adequate use of the "unittest" standard module, I haven't encountered > any reason to call one of those old debug() routines or have a global > "debug level" variable for eons... Personally, I think you're right. I've become fascinated with the idea of unit testing myself, but the problem is that a) you often have to find out bugs from somebody else's code b) you've developed system using testing, but the bug didn't appear in your tests and now you don't know what causes the problem c) you didn't do unit testing yet when you coded the module or d) you don't believe in unit testing to which we'd say d is the wrong answer, c is more likely and a and b just happen. -- #!/usr/bin/perl -w $h={23,69,28,'6e',2,64,3,76,7,20,13,61,8,'4d',24,73,10,'6a',12,'6b',21,68,14, 72,16,'2c',17,20,9,61,11,61,25,74,4,61,1,45,29,20,5,72,18,61,15,69,20,43,26, 69,19,20,6,64,27,61,22,72};$_=join'',map{chr hex $h->{$_}}sort{$a<=>$b} keys%$h;m/(\w).*\s(\w+)/x;$_.=uc substr(crypt(join('',60,28,14,49),join'', map{lc}($1,substr $2,4,1)),2,4)."\n"; print; From wade at lightlink.com Wed Nov 12 16:04:36 2003 From: wade at lightlink.com (Wade Leftwich) Date: 12 Nov 2003 13:04:36 -0800 Subject: A vote for re scanner References: <5b4785ee.0311100714.1445cdfb@posting.google.com> <698f09f8.0311101455.41f8706a@posting.google.com> Message-ID: <5b4785ee.0311121304.25e41857@posting.google.com> tweedgeezer at hotmail.com (Jeremy Fincher) wrote in message news:<698f09f8.0311101455.41f8706a at posting.google.com>... > wade at lightlink.com (Wade Leftwich) wrote in message news:<5b4785ee.0311100714.1445cdfb at posting.google.com>... > > Every couple of months I have a use for the experimental 'scanner' > > object in the re module, and when I do, as I did this morning, it's > > really handy. So if anyone is counting votes for making it a standard > > part of the module, here's my vote: > > While I don't think they're still accepting votes :), you've pointed > me to something I didn't know about until now. What kinds of things > have you been using re.Scanner for? > > Jeremy A scanner is constructed from a regex object and a string to be scanned. Each call to the scanner's search() method returns the next match object of the regex on the string. So to work on a string that has multiple matches, it's the bee's roller skates. From max at alcyone.com Mon Nov 17 14:09:58 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 17 Nov 2003 11:09:58 -0800 Subject: trouble with os.path.exists() and wildcards References: <3FB8A5B8.3D359C27@alcyone.com> <698f09f8.0311170717.23136927@posting.google.com> Message-ID: <3FB91D06.5DCB381@alcyone.com> Jeremy Fincher wrote: > Erik Max Francis wrote in message > news:<3FB8A5B8.3D359C27 at alcyone.com>... > > > Fernando Rodriguez wrote: > > > > > How can I check for the xistence of any file that matches a > > > wildcard? > > > > > > For example: ppis-*.iss > > > > > > os.path.exists() doesn't expand the wildcard... > > > > Use glob.glob and then os.path.exists in a loop. > > Wouldn't the glob.glob only return files that actually exist? Sure, but isn't that what he wants? He wrote, "the [existence] of any file that maches a wildcard." He's obviously talking about existing files. Besides, what else could expanding a wildcard mean except enumerating every possible match? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ Why don't you grow up for crying out loud? -- Capt. Benjamin "Hawkeye" Pierce From joconnor at cybermesa.com Fri Nov 7 01:01:45 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Fri, 07 Nov 2003 06:01:45 GMT Subject: Need help with OOP References: Message-ID: <3fab3167.41093382@news.cybermesa.com> On Fri, 7 Nov 2003 05:36:57 +0100, sinisam wrote: >Next part (even though I said I know *nothing* about OOP) is: > >"Make class for the IP address. It should be initialized from the >string. Later on, we can add functions to it." > >[1] What in the world I have to do here? >[1a] How to make class for the IP address? What does it mean? One feature you will often see in OOP is the idea of 'wrapping' more primitive concepts into objects and then giving those objects more functionality as a means of convenience. For example, while it is possible to trate a phone number as a simple string such as phoneNumber = '102.555.1234' You can also wrapper the simple string in a class and then give it extra functionality phoneNumber = PhoneNumber() phoneNumber._number = "102.555.1234" pre = phoneNumber.prefix() the function "prefix()" is defined by the PhoneNumber class as an easier way of dealing with the phone number. To create this wrapper class in Python is easy class PhoneNumber: def __init__(self): self._number = '' def prefix (self): return self._number[4:7] So the question being asked is to write a similar wrapper class that will do the same for IP addresses >[2] "Initialization from the string" means something like passing >arguments from the command line...? No, it means that when you create the object, you will provide some information that will set the default state of the new object person = Person ("O'Connor", "James") this is done by providing paramaters for your initialization function for the class class Person: def __init__(self, lastName, firstName): self._lastName = lastName self._firstName = firstName This sets the lastName and firstName of the person to whatever you tell it to be when you create the object >Of course, I don't expect you to do the job for me, but I would sure >appreciate help. I know this is easy, but as stated before, I don't >know how to handle objects... yet :) The above explanation and examples are sparse, but should be sufficient to move you in the right direction to solve your problem Take care, Jay From dsilva at ccs.neu.edu Mon Nov 3 23:56:30 2003 From: dsilva at ccs.neu.edu (Daniel P. M. Silva) Date: Mon, 03 Nov 2003 23:56:30 -0500 Subject: Does python always need to compile ENTIRE program before it c an start to run it??? References: Message-ID: On Mon, 03 Nov 2003 18:34:33 -0500, Ellinghaus, Lance wrote: > If I remember correctly, Yes. > Python will import each module, compile if necessary, and then execute it. > This might cause additional modules to be compiled, loaded, etc.. But Python > will not import a module more than one time. Each additional time the import > is called for the same module, Python just binds a new reference into the > namespace. > What about this? [/tmp] > cat > a.py import b print "module A loaded" [/tmp] > cat > b.py import a print "module B loaded" [/tmp] > python a.py module A loaded module B loaded module A loaded > -----Original Message----- > From: seberino at spawar.navy.mil [mailto:seberino at spawar.navy.mil] > Sent: Monday, November 03, 2003 3:28 PM > To: Ellinghaus, Lance > Cc: python-list at python.org > Subject: Re: Does python always need to compile ENTIRE program before it c > an start to run it??? > > > Lance > > Thanks for the info. I agree that the initial script you > run must be compiled completely before it can execute. > Does "completely" = all the imported modules too? > >> When Python loads a module (.py file) from an 'import' statement, it >> will see if there is an already compiled version in the same directory >> and named the same except for the '.pyc' or '.pyo' extension. If it >> finds this file AND it is newer than the corresponding source code >> (.py) then it will load the saved compilation and then run it. If the >> file is not found or it is older than the source, then Python will >> compile the source, attempt to save the compiled version, and then it >> will execute it. > > The first word of your comments above is "When". So if Python doesn't load > a module until 3 hours into the execution of a large Python program then > your recipe above (including compilation of module) won't get run until 3 > hours AFTER execution starts right? > > Chris From gh at ghaering.de Fri Nov 28 11:16:08 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 28 Nov 2003 17:16:08 +0100 Subject: Blinky Program In-Reply-To: References: Message-ID: Ryan Spencer wrote: > [..] I was recently informed by someone that I could help > free up some memory usage by alleviating the sys.stdout.flush's in the > code, [...] This decidedly sounds like somebody's brainfart. -- Gerhard From asdf at asdf.com Sat Nov 29 16:44:18 2003 From: asdf at asdf.com (John Smith) Date: Sat, 29 Nov 2003 16:44:18 -0500 Subject: sorting dictionary keys? Message-ID: Hi, what's the fastest way (least amount of typing) to sort dictionary objects by the key? What's the fastest way of iterating over sorted keys for a dictionary in terms of performance? Are the two equivalent? The way I have been doing it is: d = {} #populate d keys = d.keys() keys.sort() for k in keys: print k, d[k] but I would like to do: #error here for k in d.keys().sort(): print k, d[k] why doesn't the nested function call work? Thanks in advance. From ws-news at gmx.at Fri Nov 7 10:20:09 2003 From: ws-news at gmx.at (Werner Schiendl) Date: Fri, 07 Nov 2003 16:20:09 +0100 Subject: Writing an image In-Reply-To: References: Message-ID: <3fabb7fd@brateggebdc5.br-automation.co.at> Hi, Mr. Costington wrote: > > When I run this like "python pic.py > pic2.jpg" > The resulting pic2.jpg is not identical to the original. I looked at it in > a hex editor, and it seems to be identical with the original pic.jpg, except > for several 0D (carraige return) characters inserted throughout the file. > > I tried this with Python 2.2.1 and 2.3.2. What's going on? The sys.stdout is obviously open in text (not binary) mode. When you write "\n" (linefeed) you'll get "\r\n" (carriage return + linefeed) in the destination. hth Werner From __peter__ at web.de Sun Nov 16 08:11:39 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 16 Nov 2003 14:11:39 +0100 Subject: map, filter & reduce... References: Message-ID: Ben wrote: > Hi all, > > I'm trying to figure out how how complex map, filter and reduce work > based on the following piece of code from > http://www-106.ibm.com/developerworks/linux/library/l-prog.html : > > bigmuls = lambda xs,ys: filter(lambda (x,y):x*y > 25, combine(xs,ys)) > combine = lambda xs,ys: map(None, xs*len(ys), dupelms(ys,len(xs))) > dupelms = lambda lst,n: reduce(lambda s,t:s+t, map(lambda l,n=n: > [l]*n, lst)) > print bigmuls((1,2,3,4),(10,15,3,22)) > > The solution generated by the above code is: [(3, 10), (4, 10), (2, > 15), (3, 15), (4, 15), (2, 22), (3, 22), (4, 22)] > > I'm stuck on the second line in "map(None, xs*len(ys), > dupelms(ys,len(xs))"... Can someone explain me how the map function > evaluates?? > > Thanks > Ben Do yourself a favour and read on to the sane version that uses a list comprehension :-) By the way, David Mertz has deliberately obfuscated the traditional imperative approach by not preserving the block structure and inserting superfluous comments. map(None, seq1, seq2) returns a list of tuples (seq1[0], seq2[0]) etc. The sequence item is substituted with None, if a sequence is exhausted, e. g. >>> map(None, range(3), range(2)) [(0, 0), (1, 1), (2, None)] >>> but that doesn't occur here, making zip() instead of map() a better choice. Putting it all together: dupelms() takes a list and a length n creating a new list where each item of the original list is duplicated n times: >>> dupelms(range(3), 2) [0, 0, 1, 1, 2, 2] >>> This is then zipped (though by map()) with a list similar to >>> range(2)*3 [0, 1, 0, 1, 0, 1] >>> map(None, [0,0,1,1,2,2], [0,1,0,1,0,1]) [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)] >>> This last list is then filtered for items (the tuples), that meet the condition item[0]*item[1] > 25 To imagine how errorprone this code is and to check how well it scales with large lists is left as an exercise to the reader... Peter From simonb at webone.com.au Wed Nov 12 23:56:50 2003 From: simonb at webone.com.au (Simon Burton) Date: Thu, 13 Nov 2003 15:56:50 +1100 Subject: pickle complexity limit? References: Message-ID: On Sun, 09 Nov 2003 15:15:12 -0800, Mark Hahn wrote: > I have a heavily interlinked dom like tree structure of objects. A node > will link to many children redundantly and many children will reference > parents redundantly. So there are many cycles of references. > ... I am working on trying to flatten the data before it is pickled. Here is the code below: it searches all references and replaces them with dummy Ids (TankId) that key the original reference in a dict. eg. def fat_dump(nested): t=Tank() t.flatten(nested) # pickle.dump( t, ... ) # ... # t = pickle.load( ... ) nested = t.lift() Rather untested as i am about to take a short holiday. ( note that == doesn't work well on nested data either! ) ciao, Simon. #!/usr/bin/env python class TankId(int): id = 0 def __new__(self): TankId.id += 1 return int(TankId.id) class Tank: def __init__(self, root = None): self.items = {} self.ids = {} # XX use a list self.todo = [] if root is not None: self.flatten( root ) def __str__(self): return str( self.ids.values() ) ########################################### # before pickle def flat_list(self, item): for i in range(len(item)): item[i] = self.queue( item[i] ) def flat_dict(self, item): for key in item.keys(): item[key] = self.queue( item[key] ) def flat_attrs(self, item): for key in item.__dict__.keys(): item.__dict__[key] = self.queue( item.__dict__[key] ) def queue(self, item): assert not isinstance( item, TankId ) if not ( isinstance(item, list) or isinstance(item, dict) or hasattr(item, "__dict__") ): return item if id(item) not in self.items: self.todo.append(item) tankid = TankId() self.items[ id(item) ] = tankid # temporary self.ids[ tankid ] = item else: tankid = self.items[ id(item) ] return tankid def flatten(self, root): print "flaten()" self.root = root self.queue( self.root ) while self.todo: item = self.todo.pop(0) if isinstance(item, list): self.flat_list(item) if isinstance(item, dict): self.flat_dict(item) if hasattr(item, "__dict__"): self.flat_attrs(item) # tuple ? other immutables ? __set/getstate__ ? del self.items ########################################### # after pickle def lift_list(self, item): for i in range(len(item)): item[i] = self.recover( item[i] ) def lift_dict(self, item): for key in item.keys(): item[key] = self.recover( item[key] ) def lift_attrs(self, item): for key in item.__dict__.keys(): item.__dict__[key] = self.recover( item.__dict__[key] ) def recover(self, item): if isinstance( item, TankId ): item = self.ids[ item ] assert not isinstance( item, TankId ) return item def lift(self): print "lifting" for item in self.ids.values(): if isinstance(item, list): self.lift_list(item) if isinstance(item, dict): self.lift_dict(item) if hasattr(item, "__dict__"): self.lift_attrs(item) # tuple ? other immutables ? __set/getstate__ ? return self.root -- Simon Burton, B.Sc. Licensed PO Box A66 ANU Canberra 2601 Australia Ph. 02 6249 6940 http://arrowtheory.com From jjl at pobox.com Mon Nov 10 18:58:31 2003 From: jjl at pobox.com (John J. Lee) Date: 10 Nov 2003 23:58:31 +0000 Subject: Pruss Manifesto - Long numbers References: Message-ID: <87he1bdbdk.fsf@pobox.com> "John Roth" writes: [...] > However, if you do, I'd be much more inclined to support > the idea of writing them the way everyone else does: > with commas and periods. That, at least, has the advantage > of being familiar to people, and it can be supported with > string notation: e"6,882.56" could be implicitly converted > to a float by the compiler. Not everyone does write numbers like that. In Germany, IIUC, dots and commas are reversed: 6.882,56. > On balance, I doubt if I'd like to see that, though. It > just doesn't seem useful enough. Agreed. Michele is right -- it's easy to do this with a string. John From dman at dman13.dyndns.org Wed Nov 26 12:47:40 2003 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Wed, 26 Nov 2003 17:47:40 GMT Subject: Extracting email attachment when is_multipart() is False References: <87r7zw9ur6.fsf@pobox.com> Message-ID: On Wed, 26 Nov 2003 08:06:15 +0100, Davor Cengija wrote: > John J. Lee wrote: >> "Davor Cengija" writes: >>> This is a multi-part message in MIME format. >>> >>> ------=_NextPart_000_0026_01C3B347.DBEA9660 >>> Content-Type: text/plain; >> [...] >> >> You seem to be missing the RFC 822 headers (From, To, Subject, etc.). > > Yes, that's true. The question is if it's easier to write a parser for that > kind of messages or to force the message producing application to output the > headers as well. We'll see... You have a third option, which I would try if you can't get the message producer to do it correctly: slap some RFC822 headers on the beginning, and then ignore them in the parsed message object. After all, if the rest of the data is correctly formatted, use the existing tested MIME parser. Prepending some "bogus" RFC822 headers would be rather trivial to do. -D -- "Piracy is not a technological issue. It's a behavior issue." --Steve Jobs www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From a.schmolck at gmx.net Fri Nov 21 10:40:25 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 21 Nov 2003 15:40:25 +0000 Subject: Trouble with nested scopes when trying to rebind a variable References: <187srv08b4hbsckjje6s79dmipug8lcqlh@4ax.com> Message-ID: Fernando Rodriguez writes: > Hi, > > I have a parameter defined in a module, called PREVIEW. Many functions use > it's value to modify their behavior. > > A function called dispatch checks the user arguments in sys.argv and calls the > appropriate function. It should also modify the value of PREVIEW depending on > the user input. > > And here's where I get into trouble: if I write something like PREVIEW = None > inside the body of a function, it doesn't modify the value of the existing > PREVIEW variable, it creates a new variable in the function scope. > > How can I modify the external PREVIEW variable? Just as you'd modify any variable, really (provided you're actually using a *mutatable* datatype like a list), PREVIEW[:] = [] However, what you actual seem to be after is globally reassigning the name PREVIEW. so do: def some_fun(bla): global preview preview = None > In Lisp there are different operators to rebind an existing variable and to > create a new variable. How do you do this in python? You don't. 'as From usenet_spam at janc.invalid Thu Nov 6 22:43:32 2003 From: usenet_spam at janc.invalid (JanC) Date: Fri, 07 Nov 2003 03:43:32 GMT Subject: Please Help Explain References: Message-ID: Ben Finney schreef: > It's the subject of an ancient parable (of Arabic origin, I believe). Indian -> Persian -> Arabic And then it came to the barbaric Western world, together with the chess game itself... ;-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From scott_list at mischko.com Mon Nov 10 17:32:42 2003 From: scott_list at mischko.com (Scott Chapman) Date: Mon, 10 Nov 2003 14:32:42 -0800 Subject: Matrix - Metaphors, Analogies and the REAL In-Reply-To: References: Message-ID: <200311101432.42084.scott_list@mischko.com> On Monday 10 November 2003 14:10, 3seas wrote: > Scott Chapman wrote: > > ' Hoping you get smarter as you get older, not just older. > > > > Scott > > and all of that is supposed to justify acts of spaming not just one > but two of my email boxes.... in essence causing more unnecessary > traffic to go thru the net.....? > > hmmmm > > How many mesages go thur this newsgroup and of that many, how many do > you read, how many do you ignore? I will not contribute further to this off-topic thread on the list except to say that you still appear to be exhibiting similar attitudes to one in your original post. You're not getting smarter as you get older, just older. Therefore, telling you to grow up would do no good. I did not send my previous message as any kind of justification. Read it again and get smarter. Your post was off-topic and you have some serious attitude problems. If you don't get smarter as you get older then you can expect similar repercussions to future actions of the same sort. Someone once said, "It is a form of insanity to do things the way we've always done them and expect that we will get different results". Scott From francisgavila at yahoo.com Sun Nov 2 03:59:56 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 2 Nov 2003 03:59:56 -0500 Subject: flatten() time trial mystery. (or, 101 ways to flatten a nested list using generators) Message-ID: A few days ago (see the 'itertools.flatten()?' thread from October 28) I became obsessed with refactoring a recursive generator that yielded the leaves of nested iterables. When the dust settled, I had many flatten functions at hand. So I had to time them. Results below. History of the functions (from flattrial.py): # There are three basic features: # 1. Can specify a function that determines iterability. # 2. Can specify class-iterability. # 3. Can modify sequence before iterating. ##Function: Features Supported : Author ## ##flatten_fa: 1 : Francis Avila ##flatten_po: 1,2,3 : Peter Otten ##flatten_po2: None : Alex Martelli channeling Peter Otten ##flatten_am: None : Alex Martelli ##flatten_dict: 2 : Peter Otten ##flatten_fastcond: 1,2 : Francis Avila ##flatten_itercond: 1,2,3 : Francis Avila ##flatten_dictcond: 1,2,3 : Francis Avila ##flatten_dictdef: 1,2,3 : Francis Avila ##flatten_trydictdef: 1,2,3 : Francis Avila ##flatten_fastdictdef: 1,2,3 : Francis Avila Tree test flattens tree: subtree = ['foo']*18 + [1,2,3]*6 tree = [ subtree*10, [ subtree * 8 ] ] Node test flattens nodetree: class Node(object): def __init__(self, label=None, data=None, children=()): self.children = children self.label = label self.data = data def __iter__(self): return iter(self.children) leaves = [Node(chr(i+65),i) for i in range(10)] branches = [Node(chr(i+65), i, leaves) for i in range(10,30)] nodetree = [Node(chr(i+65), i, branches) for i in range(30,50)] Results (Python 2.2): ....>python flattrial.py C:\Docs>python flattrial.py Tree Tests (100 reps): 02.113544 fa 03.129147 po 02.845054 po2 02.587387 am 00.643718 dict 00.648371 fastcond 00.724689 itercond 00.791277 dictcond 01.006224 dictdef 00.833452 trydictdef 00.776937 fastdictdef Node Tests (10 reps): 02.877818 po 02.633231 itercond 00.878554 dictcond 01.040838 dictdef 00.897504 trydictdef 00.864411 fastdictdef I'd post flattrial.py, but it's about 500 lines and I don't have any web space to put it up. Besides, I'm not sure anyone is interested. :) A mystery, though. I did not expect dictdef (my magnum opus) to be as slow as it was, so I investigated. I went to the obvious first: using dict.get is quite a bit slower than using try: x = dict[key]; except KeyError: x = default. This is rather inexplicable.... It was still noticeably slower than dictcond. So, I made fastdict, which emulated dictcond more closely by not allowing the default handler to modify the sequence passed to it: def defaulthandler(seq): try: it = iter(seq) except TypeError: return False, seq else: return True, it def flatten_fastdictdef(iterable, get_iterbility=None): #Note defaulthandler is no longer an argument. if get_iterbility is None: get_iterbility = {''.__class__:False, u''.__class__:False} # In dictdef, the following try-except is: # iterbility = get_iterbility.get(iterable.__class__, defaulthandler) try: iterbility = get_iterbility[iterable.__class__] except KeyError: #Following added to avoid a function call #Was: # iterbility = defaulthandler # # if iterbility is defaulthandler: # iterbility, iterable = defaulthandler(iterable) # get_iterbility[iterable.__class__] = iterbility #Now: t = iterable.__class__ try: iterable = iter(iterable) except TypeError: iterbility = get_iterbility[t] = False else: iterbility = get_iterbility[t] = True if callable(iterbility): iterbility, iterable = iterbility(iterable) if not iterbility: yield iterable else: for elem in iterable: for subelem in flatten_fastdictdef(elem, get_iterbility): yield subelem This gave the results you see above: even faster than dictcond. The thing is, I don't have any idea why. The function call overhead doesn't seem to be enough to explain the difference between the try version of dictdef and fastdictdef. Nor the name rebinding (which is very fast). Anyone have any ideas? Second, is the speed gain of fastdictdef over trydictdef worth the loss of specifying a defaulthandler that can dictate what goes into the cache dictionary and modify sequences? (I know, "it depends", but in the general case, is that a feature anyone would ever *need*? I can't see how.) -- Francis Avila From andrew-pythonlist at puzzling.org Wed Nov 19 07:31:44 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 19 Nov 2003 23:31:44 +1100 Subject: smtp server In-Reply-To: <29jmrvc4s9blgmpusb3t70b9g2c8q3q3gf@4ax.com> References: <29jmrvc4s9blgmpusb3t70b9g2c8q3q3gf@4ax.com> Message-ID: <20031119123144.GI32299@frobozz> On Wed, Nov 19, 2003 at 12:00:29PM +0100, Fernando Rodriguez wrote: > Hi, > > Is there any python smtp server available with source? There's a server called Quotient which does SMTP (among other things): http://www.divmod.org/Quotient/index.html But as the README says: This release is aimed at developers and early adopters. Feel free to give it a try, but don't use it as your primary email system - yet! I haven't spent much time with it, but it looks interesting. It's a bit rough to get going, though -- the setup.py didn't quite install everything it needed to, and the documentation is sparse. Are you after a ready-made server, or an SMTP server library? If the latter, you might find Quotient and Twisted (the library Quotient is built upon) to be a handy starting point. -Andrew. From usenet at joefrancia.com Mon Nov 17 22:46:45 2003 From: usenet at joefrancia.com (Joe Francia) Date: Tue, 18 Nov 2003 03:46:45 GMT Subject: manipulating the Windows Device Manager In-Reply-To: <8de75d53.0311171056.407ab6f0@posting.google.com> References: <8de75d53.0311171056.407ab6f0@posting.google.com> Message-ID: Erick Bodine wrote: > I want to be able to disable/enable a hardware device on a Windoze box > for testing purposes through Python. Cursory searches of the the > win32all extensions, this group and google have not been too > fruitfull. There appears to be a route through WMI but I was > wondering if anyone had done this already before I plumb the depths of > MSDN. > > Thanks, > > ERick If you want to go the WMI route, I recommend Tim Golden's excellent WMI module: http://tgolden.sc.sabren.com/python/wmi.html Peace, Joe From jay at jaydorsey.com Sat Nov 1 16:38:21 2003 From: jay at jaydorsey.com (Jay Dorsey) Date: Sat, 01 Nov 2003 15:38:21 -0600 Subject: what is this? In-Reply-To: References: Message-ID: <3FA427CD.20905@jaydorsey.com> Herbert Fritsch wrote: >>>>a = 3 >>>>b = 4 >>>>b / 2 + a > > 5 > >>>>b / (2.0 + a) > > 0.80000000000000004 > > There must be something wrong. I' running the new Suse 9.0. Not really. Think of the order of operations in mathematics. Multiplication and division are ranked higher than addition. Using parentheses for grouping is higher (before) mulitplication and division. First example: 4 / 2 + 3 yields 2 + 3 yields 5 Second: 4 / (2.0 + 3) Python coerces the 3 into a floating point number, so lets write all these as floating points: 4.0 / (2.0 + 3.0) Order of operations says do the parentheses first: 4.0 / 5.0 yields 0.8000000000000004 Theres a listing of Pythons order of operations somewhere in the documentation on python.org (couldn't find it with a quick search). :) From keflimarcusx at aol.comNOSPAM Tue Nov 18 08:32:10 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 18 Nov 2003 13:32:10 GMT Subject: new guy References: Message-ID: <20031118083210.19942.00000470@mb-m02.aol.com> > if e>= 1 : > a=e > else : > a=0 >I keep getting a syntax error. You sure this causes it? It doesn't seem to be great style to me (should be no space before a colon, spaces around the equals sign, space before the >= operator), but that won't cause a syntax error. What is the exact error message you receive? Even better, post the whole traceback. - Kef From robin at jessikat.fsnet.co.uk Wed Nov 12 03:28:29 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 12 Nov 2003 08:28:29 +0000 Subject: Python's simplicity philosophy References: <2259b0e2.0311112248.3be2d304@posting.google.com> <17lsb.109042$fl1.4548960@twister.southeast.rr.com> Message-ID: In article <17lsb.109042$fl1.4548960 at twister.southeast.rr.com>, Georgy Pruss writes > >"Michele Simionato" wrote in message news:2259b0e2.0311112248.3b >e2d304 at posting.google.com... >| <...> >| in which the sequence goes *before* the operator. It is interesting to >| notice that somebody recently suggested in the Scheme newsgroup that >| >| (map function sequence) >| >| was a bad idea and that >| >| (map sequence function) >| >| would be better! >| >| <...> > >Yes, that's right. Some scientific studies proved that humans think and >express their thoughts in order subject/object-action. So OOP is very >"human" in this aspect, btw. > >G-: > > on oop in this thread nobody has pointed out that we could have sequence.sum() sequence.reduce(operator.add[,init]) or even sequence.filter(func) etc etc and similar. That would make these frighteningly incomprehensible ;) concepts seem less like functional programming. Personally I wouldn't like that to happen. -- Robin Becker From mbabcock at fibrespeed.net Wed Nov 26 10:49:55 2003 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Wed, 26 Nov 2003 10:49:55 -0500 Subject: problems with popen (linux7.3 python2.2.2) In-Reply-To: References: Message-ID: <3FC4CBA3.4010609@fibrespeed.net> > > >When I use: >os.popen('ssh -l root at something tomcat4 stop') >I find the command always hangs. > Try adding a "-t" to your SSH command-line; it forces it to request a TTY instead of being silent. SSH tries to do "the right thing" when not launched from a terminal prompt. -- Michael T. Babcock C.T.O., FibreSpeed Ltd. http://www.fibrespeed.net/~mbabcock From adalke at mindspring.com Sun Nov 2 03:36:09 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 02 Nov 2003 08:36:09 GMT Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <87he1vsopi.fsf@pobox.com> <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> <1589qvcdv9bni5fr8opactkgj9n5hecpj7@4ax.com> Message-ID: Stephen Horne: > We cannot percieve either quantum or relativistic effects directly, so > they could not be the earliest models. [In general I agree with your post. Just some comments.] What about superfluid helium? > And yes, even classical mechanics could not have been our first model > for simple commonsense reasons. How often, for instance, did ancient > Greeks get to observe objects moving through a frictionless > environment? Every clear night. > I just love the way that a guy who got rich selling software to do > fiddly maths jobs such as working with systems of differential > equations has suddenly decided that all that fiddly maths is > completely the wrong way to go ;-) Excepting that he spent 10 years on that book :) > But even if, at some level, the universe is a cellular automata, I > don't see that meaning that the fiddly maths can be abandoned. I liked the scene in one of Brin's novels (from the Brightness Rift trilogy). Alien civilizations are the result of a several billion years old lineage. Nearly all knowledge is found in the Library. Computer simulations are based on automata theory. But Earth isn't part of the culture ("wolflings") and developed this bizarre math using infinitesimals which was sophisticated enough to make pen&paper(&abacus) predictions of certain events which were hard to simulate. > I wouldn't go so far. No model (at least none we have yet) is perfect, > so different models are bound to contradict each other - particularly > when you push them beyond their limits. True. But some questions are meaningless. "Wave or particle?" "Where is the center of a black hole?" "What would happen if you were driving at the speed of light and turned the headlights on?" > Hmmm - I suppose this depends what you mean by center. If you mean > 'origin' in the graph-plotting sense, then you are right, of course. > > But my understanding is that the universe, so far as anyone can tell, > is either an infinite space or finite without bounds. In either case, > there is no such thing as a center. Michele is a better one for this topic. My point was just that many different answers doesn't necessarily imply a mystic explanation. > I find the 'infinite' theory dubious - if the expansion rate has > remained finite since the big bang, then how can space have grown to > become infinite? There's also the Oblers' paradox, but that also requires infinite time. I read a popular account of "branes", membrane theory, which was interesting. I don't know enough to describe it, other than that the universe was created from high-dimensional membranes hitting each other. Andrew dalke at dalkescientific.com From bokr at oz.net Fri Nov 28 16:35:21 2003 From: bokr at oz.net (Bengt Richter) Date: 28 Nov 2003 21:35:21 GMT Subject: How to GetClassName in Python References: Message-ID: On Fri, 28 Nov 2003 10:11:27 +0530, "bala" wrote: > >This is a multi-part message in MIME format. > >------=_NextPart_000_0009_01C3B597.FC516DF0 >Content-Type: text/plain; > charset="iso-8859-1" >Content-Transfer-Encoding: quoted-printable > >Hi, > I want to know how to getclassname of application from python..In = >python There is no method like GetClassName... Presumably you want to access this win32 API: ---- GetClassName The GetClassName function retrieves the name of the class to which the specified window belongs. int GetClassName( HWND hWnd, // handle of window LPTSTR lpClassName, // address of buffer for class name int nMaxCount // size of buffer, in characters ); ---- Most people here probably think of something different when you say "class" ;-) IOW, best to mention the windows connection, if it's not strictly a Python question. There are extension modules that will let you get at the win32 api. E.g., see Mark Hammond's win32all at http://starship.python.net/crew/mhammond/win32/Downloads.html or Thomas Heller's ctypes module at http://starship.python.net/crew/theller/ctypes/ >Is there any other Method ...I kindly give some example in python.. > If anyone answer to the above problem....I will be very = >thankfull to you... > >Note:- Using Python Application, I want to Get the ClassName of any = >Application. >------=_NextPart_000_0009_01C3B597.FC516DF0 >Content-Type: text/html; If you want to avoid annoying some people here (good strategy if you want help ;-) please try to avoid posting HTML to the newsgroup. Regards, Bengt Richter From FBatista at uniFON.com.ar Thu Nov 6 15:04:50 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 6 Nov 2003 17:04:50 -0300 Subject: return multiple values from fuction Message-ID: Lupe wrote: #- hi, if someone can help me I would be grateful #- #- when I do #- #- def function #- kjklj #- llkl? #- #- return variableA, variableB #- #- how can I assign the two return values to two distinct #- variables, as for ex. #- #- varC = variableA #- varD = variableB >>> def f(): return (1, 2) >>> (a, b) = f() >>> a 1 >>> b 2 >>> . Facundo From heejung73 at yahoo.com Wed Nov 5 13:47:58 2003 From: heejung73 at yahoo.com (hjl) Date: 5 Nov 2003 10:47:58 -0800 Subject: Open web page using IE cookie Message-ID: <7e61afbb.0311051047.23cb2733@posting.google.com> hi, i have a subscription to view "member only" pages on a website. when i subscribed, a cookies were set in IE. now, i'm interested in accessing some of the pages using python. so i need to do urlopen but somehow using the IE cookies. is this possible? thx for your help! -hj From 3seasA at Tthreeseas.DOT.not Fri Nov 14 23:11:41 2003 From: 3seasA at Tthreeseas.DOT.not (3seas) Date: Sat, 15 Nov 2003 04:11:41 GMT Subject: OT Re: Matrix - Metaphors, Analogies and the REAL References: <9447377298731260.NC-1.60.joobs@news.free-online.net> <944913851691266.NC-1.61.joobs@news.free-online.net> Message-ID: <1Ihtb.1378$Wy4.787@newsread2.news.atl.earthlink.net> John Burns wrote: > On Thu, 13 Nov 2003 12:09:28 +0000, Gon?alo Rodrigues wrote: > [snip] >> And I'm out of this thread. > > Bye I'll feed you pet troll John, I got plenty more where this came from: The metaphor of this attack on me is one of Agents/Smiths, And I have had plenty of them. And more than just such attacks, but at one point in time mindspring was receiving alot of complaint about me, so they investigated, then got in contact with me to tell me what was going on. They said "Apparently there are those who simply do not like you presence anywhere on the internet." In time more complaints happened, all false but this time someone hacked the mindspring ticketing bot to make it look like it was me complaining about me. Only the hacker didn't do a good enough job to keep Mindspring from determing it wasn't me, but only well enough to hide who they were. Mindspring then dropped their blue ribbon free speech support and ban me from posting to usenet. Not because of anything I did, but because they were spending more on investigating false complaints against me than I was paying them per month. And that is not all, there have been well known people outright lie about me, behind my back, to others and I even understand the CEO of Amiga has said in public untrue things about me. As to the links above they are statements made by others, what would be at best, hearsay, at worse libel. And anyone should be able to see thru the FAQ as the psychologist, if there really was one, could lose his license to practice in this case. Kirk S. no longer supports the FAQ that was fabricated, only usenet doesn't allow changing things, and that's actually ok because it established things. In this case what it establishes is that I am in fact , KNOWN and was know of at such a time line the Wachowskis would most certainly have had access to me, my posts on usenet and my web pages. So here it is..... the attacks some many have made on me.... How might the Wachowskis have written that in? It should be friggin obvious. At this point in time, and here, there is plenty to look into in the way of connections of myself and what I am about in regards to the movies. Attacking me here, all it really does is .... well to be point blank honest.... exposed the character of the attacker. for there are plenty enough documented usenet posts where the attacker was making claims about me that even often in their post, they show their own guilt of the very thing they claim of me. Certainly the whole mirror thing, the mercury, etc... all make perfect sense to me. Just search on may name and mirror in google groups and sort by date to see how far back that goes. And then there is "Toonces the Cat" .....Who was that, was it the wachowskis?? The Amiga with the Video Toaster was the first major breakthru in both video switcher and Animation tools (lightwave).... A lot of the video production and movie industry used it back then..... So its really not a supprise I was found...for I was in the Amiga newsgroups... There is alot more but sufice it to say.....the attacks I've deal with.... the attackers still all look the same. The VIC project... there have been those who said it can't be done, but can't tell me why, hell its not anything in the way of functionality that we haven't had for a long time. And then there are those who claim its already been done, but just can't seem to show me where it is. Then there is me, do it, proving it. What's the problem, why all the resistance and attacks? Its simple, autocoding obsoletes psuedo coders... The system failure message at the end of the first movie.... that was about what was projected to happen should ..... word get out about autocoding, to the public. The old system would fall. Now the system... well its clear, not just from the movies, but from reality that effort to being applied to either control it or to control it.... The system would rather stay the way it has been, but If I force it by finishing the vic in a manenr that is easy to use, you can bet you ass MS will be one to apply their marketing power to convince the world they did it.... just like they have done so many times before... I'm a nutter........ because I'm a user that wants to do more for myself, and worse, cause I know it is possible. I'm a real fucking lunitic.... because I'm tired of the attitude of an industry of "we are going to fuck you and if you don't like it we are going to fuck you." I believe anyone who searches google groups will find such a statement from me. And what was it that Trinity said to Neo when Neo decided to go save Morpheus? I believe you can go to hell, because you are not going anywhere else. Nobody has ever done this before........ Thats why its going to work...... Yeah, I was in the Government building, usenet, with its date time stamped archives... About what I do for a living, There are other Timothy Rues, one is a photographer. I was actually mistaken for this well established photographer..... Somebody saw my photographs of Europe and thought I must be that guy.. There is also my artwork, including an electric violin I made... much of which is availbale on via the internet........ Fuck modest,,,,, its good work! Yeah I'm a nutter.... one attacker clamed I hadn't a creative bone in my body.... They were looking in a mirror..... Interesting what some chose to focus on.... the attackers.... Choice.... -- 3 S.E.A.S -- Virtual Interaction Configuration (VIC) Changing how we preceive and use computers email @ translate not to net, remove capitol letters, one . web @ http://threeseas.net From gh at ghaering.de Sun Nov 16 13:50:57 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 16 Nov 2003 19:50:57 +0100 Subject: Gadfly DB in python standard library? In-Reply-To: References: <3fe406f0.0311141353.3aec780f@posting.google.com> Message-ID: <3FB7C711.3060909@ghaering.de> A.M. Kuchling wrote: > On Sun, 16 Nov 2003 03:38:08 +1100, > Anthony Baxter wrote: > >>I believe there is still merit to including an SQL database being in >>the standard distribution of python - personally I could live with >>sqlite being included. > > > +1 from me. In retrospect, it probably would have been more useful to add > sqlite than BerkeleyDB support to Python 2.3. Being the primary PySQLite maintainer, that's good to hear :) -0 from me for adding either Gadfly or PySQLite to the standard Python distribution. I can't see any merit in this. I also see the danger of PySQLite/Gadfly being used for purposes they're not appropriate if they're included in the standard distribution. -- Gerhard From jkrepsBEAR at FISHneb.rr.com Sat Nov 1 09:29:38 2003 From: jkrepsBEAR at FISHneb.rr.com (GrayGeek) Date: Sat, 01 Nov 2003 14:29:38 GMT Subject: Everybody likes python References: Message-ID: Noen wrote: > _____ > .-'` '. > __/ __ \ > / \ / \ | ___ > | /`\| /`\| | .-' /^\/^\ > | \(/| \(/| |/ |) |)| > .-\__/ \__/ | \_/\_/__..._ > _...---'-. / _ '. > /, , \ '| `\ \ > | )) )) /`| \ `. /) /) | > | ` ` .' | `-._ / > \ .' | ,_ `--....-' > `. __.' , | / /`'''` > `'-.____.-' / /, | / / > `. `-.-` .' \ / / | > `-.__.'| \ | | |-. > _.._| | / | | `'. > .-''`` | | | / | `-. > .'` / / / | | '. > /` / / | / |\ \ > / | | | | /\ | > || | / | / '. | > |\ \ | / | '. / > \ `. '. / | \ '---'/ > \ '. `-./ \ '. / > '. `'. `-._ '.__ '-._____.'--'''''--. > '-. `'--._ `.__ `';----` \ > `-. `-. `."'``` ; > `'-..,_ `-. `'-. / > '. '. '. .' > Python is your friend -- Copulating snakes? I thought Guido wanted Python associated with Monty Python? - GrayGeek From socraticquest at hotmail.com Mon Nov 3 16:11:16 2003 From: socraticquest at hotmail.com (socraticquest) Date: 3 Nov 2003 13:11:16 -0800 Subject: AI and cognitive psychology rant References: Message-ID: <8d667de1.0311031311.525ab29c@posting.google.com> Stephen Horne wrote in message news:... > On Sat, 25 Oct 2003 13:57:33 -0500, Arthur wrote: > > >If the machine is not at least potentially subject to fits of raging > >paranoia, its probably programmed wrong. If it is, what have we > >accomplished? > > From what I can see, the human set of emotions are an integrated > system 'designed' (in the evolutionary sense) to achieve a purpose. > Being intelligent does not imply being paranoid, jealous, etc etc. > > Of course when machines have to deal with conflicts of interest (and > when they have interests of their own to deal with) it might turn out > that emotions rather similar to the human ones work well (or at least > as well as the human ones do). > > After all, rage has a purpose. As us passive Asperger syndrome > sufferers know very well, a very delicate balance of anger is needed > to succeed in society. If you are not sufficiently angry when you > should be, you are an easy target for bullying and exploitation. And > of course when the last straw breaks the camels back, when that > expression "beware the wrath of a quiet man" suddenly becomes > relevant, you just end up looking like you get angry for no reason. MODERATE LENGTH RESPONSE: How are adults with Asperger Syndrome in this newsgroup managing career development agendas? As an adult with Asperger Syndrome (AS) (diagnosed in my early thirties), I'm highlighting my experience with "vocational development" programs, as well as how future agendas must be shaped. Adults with (AS) have naturally fallen into a "never-never land of sorts" of "not able enough, yet not disabled enough" of usually quite capable people; who find even a slight emphasis on disabilities quite inappropriate. As a result of high unemployment amongst the disabled, in addition to a weak-economy, many people with Asperger Syndrome (AS) feel overwhelmed, and discouraged. "Abilities first" agendas must encompass "novel" approaches to economic development. One example: If successful economic development programs succeed through applying creative approaches, and supporting entrepreneurial efforts (in addition to employment development) in economically depressed regions (that have even included good examples in developing countries), than why can't parallels be drawn to assisting disabled people? Adults with (AS) must benefit from progressive approaches; which can triumph over a "tired old" conservative status-quo; long the domains of rigid bureaucracies, ignorance, and even immediate family who naturally act more out of sentiment, and not enough out of reason! Simply put, the "status-quo" behind many "job-programs" fails to be in parity with the very complexities of economics, and economic development; which are behind jobs! "The worst things to do in a poor economy!" What has been your experience addressing conferences, and professional associations; whose audience consists of employment counselors? With budgetary-shortfalls, and a weak economy, are more and more employment-development programs convinced that they must undergo major changes? Too many clients of job-development programs realize that these programs are too elementary, and outdated in scope. As a result, people become frustrated and worn-down by "the system;" with little or no gain in employment prospects. Many "job-programs" refuse to take progressive-approaches to job-development, and instead "use some expedient as a crutch!!" For example, job counselors are quick to respond by pointing-out that, "such-and-such" "is not MY job, or is not THEIR job", or simply excuses regarding time-constraints e.g., "I don't have the time, THEY don't have the time." And oh yes, "a clear emphasis on caseloads that resembles a triage." I had confronted my "job developers" with these concerns, but to no avail. Furthermore, some of these programs deliberately prolong client cases in order to receive additional funds from the government; practices THAT MUST BE DISCOURAGED. Just to remain impartial, many people e.g., long-term unemployed, disabled have been successfully assisted by elementary job-development programs. JOB DEVELOPMENT THAT WORKS: For people who have the least-need for generic job-development; yet still need assistance, counselors must refer clients to vocational education programs; the best programs are supported through local, and regional initiatives e.g., public-private partnerships. Opportunities are developed through mentoring, apprenticeships, and excellent placement services. The purpose here is to keep people who have had industry-specific experience "in the loop!" After all, "Doesn't this constitute the best means toward employment (and entrepreneurial development)?" "For example, my certifications in digital publishing (graphic arts), and online research experience applies here!" BTW: I have interests in artifical-intelligence, and data visualization applications being extended to personal computers, and Internet media. Yet, again, too many programs are orientated around some outdated expedient. The 1973 Rehabilitation Act is one of many examples. The 1973 Act is too quick to view telecommuting as normalizing the very isolation that the 1973 law was intended to overcome. Isolation is not the intent of telecommuting, the reasons for considering work with distant employers are quite simple; opportunities in one's chosen vocations can be both limited, and competitive in their local regions. With more and more work being done through telecommuting, telecommuting experience may even help develop (physical-location) opportunities. "Isn't the Internet supposed to help people, and economies alike rise above those barriers known as limitations, and the status-quo?? While I was in these "job programs," I had expressed the need for career-development that was orientated around involvement from private industry! Again, these "job counselors" refused to show interest! One of the counselors even told me that "it scared them" to hear these concerns coming from a client! I had finally "given-up" with the California Dept. of Rehabilitation. Let's not waste taxpayer's money on programs that are also a waste of people's time and energy. Model vocational programs work best by overlooking any mention of disabilities! In other words, the time has come to challenge the "status-quo" and allow "out of the box" approaches to triumph! FUTURE AGENDAS Ironically, "well meaning" people like family were the very people who suggested these "vocational development" programs. As a result, I feel increased concerns regarding how future agendas e.g., estate-planning will be handled. In other words, how do I convey my concerns; without being misconstrued to immediate family? An advisor (a family friend) is willing to act on my behalf, after parents are deceased. My advisor (whose careers are in public education, and higher education) is located in a region that has a high concentration of adults with (AS); the Silicon Valley near San Jose, CA. Quite a few of the technical experts, who work in that region's tech industries, were found to have (AS). Since (AS) can be hereditary, I expect that my advisor will gain an increasing awareness of adults with (AS) through their kids' diagnoses of (AS). Can adults with AS expect to fully maintain independence; while getting assistance (on an as needed basis) that avoids being intrusive on the individual? Anybody in this newsgroup benefit from these progressive approaches that I advocate? Thank-you From phil at riverbankcomputing.co.uk Sun Nov 2 14:37:02 2003 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sun, 2 Nov 2003 19:37:02 +0000 Subject: PyQt, Qt, Windows and Linux In-Reply-To: References: Message-ID: <200311021937.02792.phil@riverbankcomputing.co.uk> On Sunday 02 November 2003 6:52 pm, Vamsi Mudrageda wrote: > I am kind of new to Python, and after trying and using wxPython, I found > it kind of lacking in easy-to-read documentation, speed at loading, and > GUI response-time. > > So I am looking for an another GUI toolkit that is cross-platform for > Python, and am leaning toward PyQt (PyGTK is kind of dull looking in > comparison). Unfortunately, although TrollTech says Qt is > cross-platform, its license strategy has me a bit confused. So here is > to hoping someone can help... > > Objective: > Develop/Write a program for personal use on my Linux using PyQt. Be > able to also run it on Windows. > > Questions: > 1) Is it legally possible to do that? Yes. > 2) Do I need to buy a license from TrollTech? Yes - and a license for PyQt. > 3) Can I create a .exe file for my windows on my Linux and copy it over? > (I would like to develop the program entirely on Linux, but make > executables for other platforms). That's a function of the different packaging packages available. Phil From danb_83 at yahoo.com Thu Nov 27 01:37:54 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 26 Nov 2003 22:37:54 -0800 Subject: if - else References: Message-ID: > -----Original Message----- > From: Jeff Wagner [mailto:JWagner at hotmail.com] > Sent: Wednesday, November 26, 2003 6:20 PM > To: python-list at python.org > Subject: if - else ...[attempt at rewriting an old VB program in Python]... > This is the old routine from VB which worked ... I know, it's > crappy code. It's the first program I > wrote many years ago. > > Public Sub MasterNumberRoutine() > On Error GoTo ErrorHandler > > 'This routine determines if the input is a master number and, if not, > 'adds the resultant > > Dim I2 As Integer > Dim F2 As Integer > > If SumOfNumbers = 11 Or SumOfNumbers = 22 Or SumOfNumbers = 33 > Then > GoTo Done > End If > > I2 = Int(SumOfNumbers / 10) > F2 = SumOfNumbers - (I2 * 10) > SumOfNumbers = I2 + F2 > > If SumOfNumbers = 10 Then > GoTo Check10 > ElseIf SumOfNumbers > 9 Then > MasterNumberRoutine > Else > GoTo Done > End If > > Check10: > 'If SumOfNumbers = 10, then set it's value to 1 > SumOfNumbers = 1 > > Done: > Exit Next: > Exit Sub > > ErrorHandler: > MsgBox "Error: " & Err.Number > & vbCrLf & Err.Description, > vbOKOnly, "Unexpected Error" > Call ErrLogger("MasterNumberRoutine") > Resume Exit Next > > End Sub Before translating that to Python, I'd try cleaning up the VB code. First, let's ignore the error-handling code (since it doesn't appear that you actually expect any errors. Public Sub MasterNumberRoutine() 'This routine determines if the input is a master number and, if not, 'adds the resultant Dim I2 As Integer Dim F2 As Integer If SumOfNumbers = 11 Or SumOfNumbers = 22 Or SumOfNumbers = 33 Then GoTo Done End If I2 = Int(SumOfNumbers / 10) F2 = SumOfNumbers - (I2 * 10) SumOfNumbers = I2 + F2 If SumOfNumbers = 10 Then GoTo Check10 ElseIf SumOfNumbers > 9 Then MasterNumberRoutine Else GoTo Done End If Check10: 'If SumOfNumbers = 10, then set it's value to 1 SumOfNumbers = 1 Done: End Sub The "Goto Check10" line can be eliminated by moving the Check10 block to each branch of the previous "If" that goes to Check10. Public Sub MasterNumberRoutine() 'This routine determines if the input is a master number and, if not, 'adds the resultant Dim I2 As Integer Dim F2 As Integer If SumOfNumbers = 11 Or SumOfNumbers = 22 Or SumOfNumbers = 33 Then GoTo Done End If I2 = Int(SumOfNumbers / 10) F2 = SumOfNumbers - (I2 * 10) SumOfNumbers = I2 + F2 If SumOfNumbers = 10 Then SumOfNumbers = 1 ElseIf SumOfNumbers > 9 Then MasterNumberRoutine SumOfNumbers = 1 ' Are you sure you wanted to do this? Else GoTo Done End If Done: End Sub The last "GoTo Done" is now redundant (because the next statement is at "Done" anyway). The first "GoTo Done" can also be eliminated by putting everything in an If block. Public Sub MasterNumberRoutine() 'This routine determines if the input is a master number and, if not, 'adds the resultant Dim I2 As Integer, F2 As Integer If not (SumOfNumbers = 11 Or SumOfNumbers = 22 Or SumOfNumbers = 33) Then I2 = Int(SumOfNumbers / 10) F2 = SumOfNumbers - (I2 * 10) SumOfNumbers = I2 + F2 If SumOfNumbers = 10 Then SumOfNumbers = 1 ElseIf SumOfNumbers > 9 Then MasterNumberRoutine SumOfNumbers = 1 ' Are you sure you wanted to do this? End If End If End Sub Notice that you now have no need to ask for Python's equivalent of "goto", because you didn't even need any goto's in VB! Furthermore, the "If SumOfNumbers = 10" branch is redundant, because if we rewrite the subroutine as Public Sub MasterNumberRoutine() 'This routine determines if the input is a master number and, if not, 'adds the resultant Dim I2 As Integer, F2 As Integer If not (SumOfNumbers = 11 Or SumOfNumbers = 22 Or SumOfNumbers = 33) Then I2 = Int(SumOfNumbers / 10) F2 = SumOfNumbers - (I2 * 10) SumOfNumbers = I2 + F2 If SumOfNumbers > 9 Then MasterNumberRoutine SumOfNumbers = 1 ' Are you sure you wanted to do this? End If End If End Sub then when SumOfNumbers is 10, the recursive call assigns I2 = 1 and F2 = 0, and then SumOfNumbers = 1, which is exactly what it did before. Translation to Python is now straightforward. def MasterNumberRoutine(): global SumOfNumbers if SumOfNumbers not in (11, 22, 33): I2, F2 = divmod(SumOfNumbers, 10) SumOfNumbers = I2 + F2 if SumOfNumbers > 9: MasterNumberRoutine() SumOfNumbers = 1 # Probably a bug. However, it would be better to make SumOfNumbers a parameter instead of a global variable. From goodger at python.org Mon Nov 3 20:11:33 2003 From: goodger at python.org (David Goodger) Date: Mon, 03 Nov 2003 20:11:33 -0500 Subject: Optparse and varible nargs In-Reply-To: References: Message-ID: <3FA6FCC5.8030203@python.org> John Goebel wrote: > I have a program that I want to pass a variable number of things > too. > > foo_prog -f one two three Are "one", "two", and "three" positional arguments or option arguments? Can you have a command line like this? foo_prog -f one two -g three If positional arguments, optparse doesn't process them. If option arguments, how would optparse know how many to process? Have you read "The Tao of Option Parsing"? If not, please do: . -- David Goodger From SEE_AT_THE_END at hotmail.com Thu Nov 13 00:35:32 2003 From: SEE_AT_THE_END at hotmail.com (Georgy Pruss) Date: Thu, 13 Nov 2003 05:35:32 GMT Subject: Palindrome References: <20031112223135.29045.00000109@mb-m12.aol.com> Message-ID: Knowing what your program should do, could also help. G-: "Runic911" wrote in message news:20031112223135.29045.00000109 at mb-m12.aol.com... | Does anyone know how i can fix my Palindrome program? | | s = raw_input('Enter a String: ') | punctuation = '%$!*.,-:? ;()\'\"\\' | i = 0 | h = 0 | t = 0 | p = '' | z = 0 | while s!= ' ': | while i <= len(s) - 1: | punct = s[i] | if punctuation.find(punct) == -1: | p = p + punct | i = i + 1 | t = p.lower() | t[h] == t[len(t)-1-h] -- Georgy Pruss E^mail: 'ZDAwMTEyMHQwMzMwQGhvdG1haWwuY29t\n'.decode('base64') From davidcfox at post.harvard.edu Fri Nov 14 13:47:47 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Fri, 14 Nov 2003 18:47:47 GMT Subject: for what are for/while else clauses In-Reply-To: References: Message-ID: Diez B. Roggisch wrote: > Hi, > > today I rummaged through the language spec to see whats in the for ... else: > for me. I was sort of disappointed to learn that the else clauses simply > gets executed after the loop-body - regardless of the loop beeing entered > or not. I didn't realize that for...else existed, but according to the language reference, the else clause gets executed unless the loop body exited due to a break statement. David From mweir at transres.com Tue Nov 11 12:44:31 2003 From: mweir at transres.com (Michael Weir) Date: Tue, 11 Nov 2003 12:44:31 -0500 Subject: Writing UTF-8 string to UNICODE file Message-ID: <4e9sb.154$s8.2312@news.on.tac.net> I'm sure this is a very simple thing to do, once you know how to do it, but I am having no fun at all trying to write utf-8 strings to a unicode file. Does anyone have a couple of lines of code that - opens a file appropriately for output - writes to this file Thanks very much. Michael Weir From CousinStanley at hotmail.com Thu Nov 27 10:58:45 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Thu, 27 Nov 2003 08:58:45 -0700 Subject: pymat and Matlab6.5 References: Message-ID: | The same prolem again. I found no binaries of Scipy for Python2.3 | under Windows Xp. To compile the source code you need many package | which really I do not want to install them in my computer, and also I | do not have enough experience to do complilation process. Is there | someone who already compiled Scipy to work for Pyhton2.3 for Win32 | patform???. Juntu .... The Enthought distribution of Python 2.3 for Windows includes SciPy .... http://www.enthought.com I don't know about WinXP, but the distribution works fine under Win98 .... -- Cousin Stanley Human Being Phoenix, Arizona From eric.wichterich at gmx.de Sun Nov 2 12:28:35 2003 From: eric.wichterich at gmx.de (Eric Wichterich) Date: Sun, 2 Nov 2003 18:28:35 +0100 Subject: Shelve operations are very slow and create huge files In-Reply-To: <1067758560.1188.16.camel@emilio> Message-ID: Hello Tim, thank you for your thoughts. I tried to use cPickle and gzip instead of shelve. But it ran much slower than before. So I used the profiler to check where the most time is needed. To read the data and convert it back to a dictionary needed around 9 seconds with shelve. With cPickle, it even needed 11 seconds. With gzip & cPickle, it also needed 11 seconds (the file was now around 250 kB instead of 1,7 MB). Using pickle instead of cPickle, it needed over 45 seconds. It seems that the file size doesn't matter at all. But 9 seconds just for converting data from a pickle back to a Python dictionary??? Thanks also for mentioning DMTools. Do you know whether it is useful for (fast) convertion from a pickle (or some file stored on the server) into a Python dictionary? I didn't find much real-life examples or further descriptions of these tools. Greetings, Eric Am Sonntag, 02.11.03 um 08:36 Uhr schrieb Tim Churches: > On Sun, 2003-11-02 at 03:38, Eric Wichterich wrote: >> One script searches the MySQL-database and stores the result, the next >> script reads the shelve again and processes the result. But there is a >> problem: if the second script is called too early, the error "(11, >> 'Resource temporarily unavailable') " occurs. > > The only reason to use shelves is if your query results are too large > (in total) to fit in memory, and thus have to be retrieved, stored and > processed row-by-row. > >> So I took a closer look at the file that is generated by the shelf: >> The >> result-list from MySQL-Query contains 14.600 rows with 7 columns. But, >> the saved file is over 3 MB large and contains over 230.000 lines (!), >> which seems way too much! > > But that doesn't seem to be the case - your query results can easily > fit > in memory. However, the query may still take a long time to execute, so > it may be reasonable to want to store or cache the results for further > processing later. However, it is much quicker to just pickle (cPickle) > the results to a gzipped file than to use shelve. The use of gzip > actually speeds things up, provided that your CPU is reasonably fast > and > your disc storage system is mundane (any CPU faster than about 500 Mhz > sees gains on most result sets). Also it saves disc space. > > Ole Nielsen and Peter Christen have written a neat set of Python > functions which will automatically handle the caching of query results > from an MySQL datadase in gzipped pickles - see > http://csl.anu.edu.au/ml/dm/dm_software.html - except the files don't > seem to be available from that page - Ole and Peter, please fix! > > -- > > Tim C > > PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere > or at http://members.optushome.com.au/tchur/pubkey.asc > Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 > > > From joconnor at cybermesa.com Thu Nov 6 15:03:23 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Thu, 06 Nov 2003 20:03:23 GMT Subject: return multiple values from fuction References: Message-ID: <3faaa8ad.6086141@news.cybermesa.com> On Thu, 06 Nov 2003 19:58:55 +0000, Lupe wrote: >hi, if someone can help me I would be grateful > >when I do > >def function > kjklj > llkl? > > return variableA, variableB > >how can I assign the two return values to two distinct variables, as for ex. > >varC = variableA >varD = variableB > >?? > > def test (): ... return variableA, variableN varC, vardD = test() varC will contain variableA varD ill contain variableB From aleax at aleax.it Mon Nov 17 05:22:35 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 17 Nov 2003 10:22:35 GMT Subject: for what are for/while else clauses References: <2259b0e2.0311142321.aba58d3@posting.google.com> Message-ID: Fredrik Lundh wrote: > Alex Martelli wrote: > >> (taking "else" to mean "no break was executed in the body" is hardly >> obvious or most particularly "the only obvious" interpretation). > > that's not what it means, of course. > > in every single case, it means "run once, if and only if the > controlling condition is false". > > I'm not sure what you mean by "the controlling condition" in this case. In a for/else or while/else construct, the only way to make your assertion true is to define "the controlling condition" as "a break [or return] interrupted the for or while loop [or an exception was propagated]" -- basically (quibbles on returns and exceptions apart) just what I said about "no break was executed". A reasonably-common newbie error is to code, for example: for purchase in purchases: print 'Purchased:', purchase else: print "Nothing was purchased" taking "the controlling condition" to be the obvious one, i.e., the sequence the 'for' is iterating on. Or, similarly: while current_value < threshold: process_high_value(current_value) current_value = compute_next_value() else: alert_no_high_values(threshold) taking "the controlling condition" to be the obvious one, i.e., the "current_value < threshold" conditions that controls the 'while'. Python could presumably help a little by warning about an 'else' on a for or while loop that contains no 'break' statements. But the reason Python's for/else and while/else statements are not intuitive to most people can be boiled down to identifying that "controlling condition" -- the fact that the 'controlling condition' is "a break statement has executed" is """hardly obvious or most particularly "the only obvious" interpretation""", to repeat myself:-). Alex From emile at fenx.com Sun Nov 9 21:46:41 2003 From: emile at fenx.com (Emile van Sebille) Date: Sun, 9 Nov 2003 18:46:41 -0800 Subject: Help with Apache 2.0.47 and CGI References: Message-ID: Fausto Arinos de A. Barbuto asks > I have Apache 2.0.47 installed for a single user on port 8080, Python > 2.3.2 on C:\Python23 and ActiveState's Perl on C:\Perl. Everything seems > to work fine after the changes I made in httpd.conf, but I can't for some > reason run Python scripts that sit on this computer's cgi-bin directory http://www.modpython.org/ http://www.modpython.org/live/mod_python-3.1.2b/doc-html/inst-apacheconfig.html LoadModule python_module libexec/mod_python.so SetHandler python-program PythonHandler mod_python.cgihandler But there was also a problem reported with 2.3: http://groups.google.com/groups?threadm=3ef52138%241 at usenet.per.paradox.net.au HTH, -- Emile van Sebille emile at fenx.com From aahz at pythoncraft.com Tue Nov 25 14:09:09 2003 From: aahz at pythoncraft.com (Aahz) Date: 25 Nov 2003 14:09:09 -0500 Subject: another candidate for deprecation (was: Why shouldinput(prompt="hello:") fail?) References: <37ba82ff.0311240831.6e0dfba7@posting.google.com> <2259b0e2.0311242208.6f74e99e@posting.google.com> <3FC388F2.8FB1B8D2@engcorp.com> Message-ID: In article <3FC388F2.8FB1B8D2 at engcorp.com>, Peter Hansen wrote: >Skip Montanaro wrote: >> >> Even better, deprecate input() and rename raw_input() to input()... > >If you mean do those two things at the same time, you've just >deprecated the use of "input" and then provided only a routine named >"input"... > >And if you mean to separate them with one release to give time for the >deprecation notice to spread around, you'll just confuse people when >you then add "input" back in, but with different functionality. > >(I agree with the idea of reusing the name input() for the One True >Input Routine, but not with deprecating anything as it will just >confuse the issue.) Yeah, what would make more sense would be to rename input() to eval_input() and rename raw_input() to input(), and immediately deprecate eval_input(). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From s-rube at uselessbastard.net Wed Nov 12 13:59:43 2003 From: s-rube at uselessbastard.net (Eric Williams) Date: Wed, 12 Nov 2003 19:59:43 +0100 Subject: GUI - Qt Designer References: Message-ID: John Bradbury wrote: > Is there any way to take the output produced by Qt designer (or any other > GUI designer) and use it in Python to create a screen? There must be a > better way of creating screens than having to use the TkInter routnes and > add every widget one by one in the program. > > John Bradbury You need PyQt and/or PyKDE. You can use pyuic DialogWhatever.ui > DialogWhatever.py to convert the QtDesigner *.ui file to a python file. Then you can import it into a PyQt app and use it like any other python Qt class. One warning, however: It's not as easily portable as Tkinter. On windows, especially, it's pretty much only usable if you've bought the full Qt Commercial verson. The free version of Qt/Win only goes up to version 2.3. Boa-constructor is alpha still, but usable to make wxPython apps in a RAD environment. PythonCard was another alternative, but I'm not sure if it's still being maintained. Hope that helps! cya, Eric -- --- s- should be removed to contact me... From francisgavila at yahoo.com Wed Nov 19 17:55:00 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Wed, 19 Nov 2003 17:55:00 -0500 Subject: Using 'string.ljust' to try and hold a fixed width....... References: <2c82369d.0311190538.3789f2a1@posting.google.com> <2c82369d.0311191044.476a5a69@posting.google.com> Message-ID: John F Dutcher wrote in message <2c82369d.0311191044.476a5a69 at posting.google.com>... I have nothing to add to help you with your problem (aside from what Peter already said), but just a tip: >(If I don't import and use 'string.ljust), and use just 'ljust' I get >a "Namerror'(Python 2.3.1) You probably learned Python out of an old book, back when Python didn't have string methods. What I mean is, don't use the string module (it's slated for depreciation), but just use ljust as a method of your string: >>> ''.join(['a','b','c']) 'abc' >>> 'a'.ljust(5) 'a ' >>> '1234'.isdigit() True >>> dir('') ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] I'm sure you recognise many of those methods? To learn more, try help('') in an interactive session. -- Francis Avila From cedmunds at spamless.rochester.rr.com Fri Nov 14 20:11:47 2003 From: cedmunds at spamless.rochester.rr.com (Cy Edmunds) Date: Sat, 15 Nov 2003 01:11:47 GMT Subject: python STL? References: <0latb.95267$ri.14418352@twister.nyc.rr.com> Message-ID: "Maxim Khesin" wrote in message news:0latb.95267$ri.14418352 at twister.nyc.rr.com... > Hi, > being recently introduced to the joys of programming in a powerful > dynamic language (go snake!) I periodically rethink which parts of C++ I > still miss. One thing I really enjoy is the generics of C++ - i think > they are the single strong benefit of a strongly typed system. I was > wondering about the possibility of implementing STL-like algorithms in > Python and the one thing that I cannot think of doing without a kludge > is the object comparsion that so much of STL relies on, which in turn > relies on types and function(<) overloading. Is there a way to implement > something similar in python (short of multimethods?). How does the > python dictionary object allow arbitrary key types? Is in internally > using the references' addresses to impose the tree ordering? > thanks, > max. > The STL (now part of the standard library) does with considerable complexity* that which Python does very simply. That's because C++ templates attempt to do generic programming without breaking the type system. Python has no type system to break so generic program comes naturally. -- Cy http://home.rochester.rr.com/cyhome/ *if you don't agree with that, I will whack you one with my copy of Josuttis :) From mis6 at pitt.edu Sat Nov 15 05:11:00 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 15 Nov 2003 02:11:00 -0800 Subject: for what are for/while else clauses References: <2259b0e2.0311142321.aba58d3@posting.google.com> <3FB5D88B.6FEA580B@alcyone.com> Message-ID: <2259b0e2.0311150211.1b1f1a0a@posting.google.com> Erik Max Francis wrote in message news:<3FB5D88B.6FEA580B at alcyone.com>... > I do think it is highly ironic that a unified try...except...finally > construct was removed because it was allegedly not intuitive enough, but > for...else, while...else, and even try...except...else (!) stayed with > no such complaint. It is strange that I do feel try...except...else very natural and I use the construct all the time... mah! My complaint is only against else in while and for. Michele From fjh at cs.mu.oz.au Sat Nov 1 08:44:10 2003 From: fjh at cs.mu.oz.au (Fergus Henderson) Date: Sat, 01 Nov 2003 13:44:10 GMT Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> <3f9d556c$1@news.unimelb.edu.au> <3f9f8f49$1@news.unimelb.edu.au> <3f9fe9b1$1@news.unimelb.edu.au> <3fa26092$1@news.unimelb.edu.au> Message-ID: <3fa3b8a4$1@news.unimelb.edu.au> prunesquallor at comcast.net writes: >Fergus Henderson writes: > >> But the difference between dynamically typed languages and >> statically typed languages is that in dynamically typed languages, *every* >> data access (other than just copying data around) involves a dynamic dispatch. >> Sure, implementations can optimize a lot of them away. But generally you're >> still left lots that your implementation can't optimize away, but which >> would not be present in a statically typed language, such as the O(N) >> dynamic type checks in the example above. > >That's what the type-checking hardware is for. Did you forget a smiley? In case not: type-checking hardware has been tried already, and failed. (Anyway, type-checking hardware would only solve part of the problem, I think. Dynamic type checking imposes two costs: one is the time cost of performing the checks, and the other is the locality cost due to the code size increase. Type-checking hardware avoids the code size increases, but I don't think it helps with the time cost of performing the checks.) -- Fergus Henderson | "I have always known that the pursuit The University of Melbourne | of excellence is a lethal habit" WWW: | -- the last words of T. S. Garp. From javier_ruere at HotPOP.com Sat Nov 22 09:30:05 2003 From: javier_ruere at HotPOP.com (Javier Ruere) Date: Sat, 22 Nov 2003 11:30:05 -0300 Subject: Frustration with Boa Constructor In-Reply-To: <6.0.0.22.0.20031121163428.0203f0d8@mail.mric.net> References: <7T02VNBM37943.8988541667@Gilgamesh-frog.org> <6.0.0.22.0.20031121163428.0203f0d8@mail.mric.net> Message-ID: <3FBF72ED.6040504@HotPOP.com> Bob Gailer wrote: > Has anyone had success with Boa Constructor? If so how did you learn it? > The tutorial clearly is not the way I can learn it. I've never tried the tutorial. I just explored the program making some bogus projects testing all the main features. Then, as I used it, kept learning the rest of it. Javier From mis6 at pitt.edu Wed Nov 12 02:19:33 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 11 Nov 2003 23:19:33 -0800 Subject: True, False, None References: <20031110065915.07735.00000461@mb-m07.aol.com> Message-ID: <2259b0e2.0311112319.8eba857@posting.google.com> "Andrew Dalke" wrote in message news:... > Douglas Alan: > > Can someone remind me as to why [None, True, False] are > > capitalized? They clash annoyingly with the common coding > > convention that capitalizes only classes. > > Here's a conjecture -- those are singletons, and note that classes > are singletons too. > > Andrew > dalke at dalkescientific.com Better to say: singletons are classes. But True and False are not classes (no '__base__' attribute, for instance) so they are not singletons. I think using smallcaps would have been more consistent. BTW, I would have been favorable to "Staticmethod", "Classmethod", "Super", etc. since they are all classes. But it is useless to protest now :-( Michele Simionato From warlock at eskimo.com Wed Nov 5 21:26:49 2003 From: warlock at eskimo.com (Jim Richardson) Date: Wed, 5 Nov 2003 18:26:49 -0800 Subject: nearest neighbor in 2D References: Message-ID: <94oo71-49n.ln1@grendel.myth> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Wed, 05 Nov 2003 09:40:23 +0100, Peter Otten <__peter__ at web.de> wrote: > Jim Richardson wrote: > >> I am new to timeit.py, but this is odd. >> >> jim at grendel:~$ /usr/lib/python2.3/timeit.py -c ' p=1.6+2.5j;np=2.4+1.3j; >> d=abs(p-np)' 100000 loops, best of 3: 3.1 usec per loop > > The above is actually timed. > >> jim at grendel:~$ /usr/lib/python2.3/timeit.py -c -s'import math; >> p=1.6+2.5j;np=2.4+1.3j; d=abs(p-np)' 10000000 loops, best of 3: 0.141 usec >> per loop > > Here you put everything in the setup parameter. As the timed statement > defaults to pass, you are essentially timing an empty loop :-( > Ah! that explains it, thanks. breaking the import off, gets the loop to 3.2 usec per loop, which makes more sense. >> Is it because the builtin math functions are much slower? > > You should have used math.abs() or from math import abs to really get the > abs() function in the math module. But > >>>> "abs" in dir(math) > False > > Not there, so we cannot compare. Actually, I just cut'n'pasted, with a tiny alteration (timeit.py isn't in my path) I like the idea of using the complex number there, it's a tad easier that the other method for me to visualize. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/qbFpd90bcYOAWPYRArgzAKDiNBXw3tIpooWqglmxoqn2GebyxgCcDEKV u60SPPopUrkJ1Kak0t4eias= =+Guh -----END PGP SIGNATURE----- -- Jim Richardson http://www.eskimo.com/~warlock "Man invented language to satisfy his deep need to complain." -- Lily Tomlin From adalke at mindspring.com Tue Nov 18 18:13:54 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 18 Nov 2003 23:13:54 GMT Subject: syntax philosophy References: Message-ID: Dave Benjamin > I agree with everything else you said here, but want to caution against your > claim that it's "impossible for Python to know" what to supply as a default. The full quote is 'This is because it's impossible for Python to know which value you want for the default'. Note that "what you want". I later said: Whatever choice you make [should have said "Python makes"], it will be wrong for most cases. > irb(main):002:0> d['a'] > => nil In most cases, this is the wrong return value, yes? > irb(main):003:0> d.default = 0 > => 0 And there's where you tell Ruby what you want. > d.get('a', 0) d.default = 0; d['a'] > > I prefer the Python way because the lazier syntax ([]) is fail-fast. And because it's thread-safe. I do see your point that 'get' does provide a default value of None if the item doesn't exist, but the behaviour, given that the default is passed as part of the function parameter, means that that value isn't really associated with the dictionary. Andrew dalke at dalkescientific.com From nessus at mit.edu Tue Nov 11 19:06:13 2003 From: nessus at mit.edu (Douglas Alan) Date: Tue, 11 Nov 2003 19:06:13 -0500 Subject: Python's simplicity philosophy References: <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: "Dave Brueck" writes: > And I disagree that that's necessarily a Good Thing. Good language > design is about finding that balance between general and > specific. It's why I'm not a language designer and it's also why I'm > a Python user. It's surely the case that there's a balance, but if you assume that your audience is too stupid to be able to be able to cope with reduce(add, seq) instead of sum(seq) then you are not finding the proper balance. >> reduce() is more general and powerful than sum(), and would thus >> clearly be preferred by my mantra. > Yes, and eval() would clearly be preferred over them all. And, damned right, eval() should stay in the language! >> The mantra "there should be only one obvious way to do it" apparently >> implies that one should remove powerful, general features like >> reduce() from the language, and clutter it up instead with lots of >> specific, tailored features like overloaded sum() and max(). > I completely disagree - I see no evidence of that. We're looking at > the same data but drawing very different conclusions from it. Well, that's the argument you seem to be making -- that reduce() is superfluous because a sum() and max() that work on sequences were added to the language. >> I can already see what's going to happen with sum(): Ultimately, >> people will realize that they may want to perform more general types >> of sums, using alternate addition operations. > Not gonna happen - this _might_ happen if Python was a design-by-committee > language, but it's not. According to Alex Martelli, max() and min() are likely to be extended in this fashion. Why not sum() next? >> All of this falls out of "clean", "simple", and "elegant". > Not at all - I cut my teeth on 6502 assembly and there is plenty > that I still find clean, simple, and elegant about it, but it's > horrible to program in. I think we can both agree that not all of programming language design can be crammed into a little mantra! >> C'mon -- all reduce() is is a generalized sum or product. What's >> there to think about? It's as intuitive as can be. > To you, perhaps. Not me, and not a lot of other people. Well, perhaps you can explain your confusion to me? What could possibly be unintuitive about a function that is just like sum(), yet it allows you to specify the addition operation that you want to use? Of course, you can get the same effect by defining a class with your own special __add__ operator, and then encapsulating all the objects you want to add in this new class, and then using sum(), but that's a rather high overhead way to accomplish the same thing that reduce() lets you do very easily. > I *like* the fact that there is someone making subjective > judgement calls, even if it means I sometimes don't get my every wish. Likewise. > A good programming language is not the natural by-product of a series of > purely objective tests. >> And taught in every CS curiculum. > Doubtful, and if it were universally true, it would weaken your point > because many people still find it a foreign or awkward concept. I doubt that anyone who has put any thought into it finds it a foreign concept. If they do, it's just because they have a knee-jerk reaction and *want* to find it a foreign concept. If you can cope with modular arithmetic, you can cope with the idea of allowing people to sum numbers with their own addition operation! > Besides, whether or not something is taught in a CS program is a > really poor reason for doing anything. No, it isn't. CS is there for a reason, and one should not ignore the knowledge it contains. That doesn't mean that one should feel compelled to repeat the mistakes of history. But fear of that is no reason not to accept its successes. Those who don't, end up inventing languages like Perl. |>oug From aleax at aleax.it Mon Nov 10 15:20:42 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 10 Nov 2003 20:20:42 GMT Subject: web guru advise needed. References: Message-ID: Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: ... > that java will kill the performance + development time here. But how to > make the link between my JSP and python business logic. Jython is still at > the python 2.1 level. Looking at the libraries, the use of Python 2.3 > seems for me more a must. Python and Java may be able to intercommunicate, as an altenrative to Jython, with JPE, http://sourceforge.net/projects/jpe -- I don't know much about it, but perhaps it fits your needs. > What technology gives me the best performance? Probably Twisted, but it doesn't meet your requirements (it's a separate stand-alone webserver, not running on top of Apache). > I'm so afraid that adapters like WebKit kills my performance but because Why are you afraid of that? Have you run some benchmarks? In my (admittedly limited) experience, Webkit's performance has been quite good. If you need or want to run closer to the bare metal, you can try mod_python, but you may end up coding more "adapters" and infrastructure yourself. I surely wouldn't want to make a performance-critical choice without some kind of benchmarking among plausible alternatives to support me!!! > of my jsp experience, psp seems the best option. I've often found that templating (e.g., Cheetah, CherryPy, and so on and so forth) can be more satisfactory in many situations, because it allows graphical designers who aren't programmers to prepare and change the "looks" of things, while programmers are allowed to do what they do best (that it, _program_, rather than improvising themselves as the graphics artists that, in most cases, they aren't...:-). Alex From tchur at optushome.com.au Sun Nov 9 15:42:49 2003 From: tchur at optushome.com.au (Tim Churches) Date: 10 Nov 2003 07:42:49 +1100 Subject: Rekall and associated software go 100% GPL In-Reply-To: <3fae9c76$0$12714$fa0fcedb@lovejoy.zen.co.uk> References: <3fae9c76$0$12714$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <1068410569.1204.103.camel@emilio> On Mon, 2003-11-10 at 06:59, John Dean wrote: > Hi > > It gives me great pleasure to inform you that Rekall, the cross-platform > alternative to MS Access, is now totally GPL. So please visit > http://www.totalrekall.co.uk and download download a copy for yourself. This is most welcome news, but in the light of the recent, often confusing (or confused) discussion on this list over Rekall and the Kompany, could Shawn Gordon please comment on this announcement? -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From martin at v.loewis.de Sun Nov 2 13:56:31 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 02 Nov 2003 19:56:31 +0100 Subject: Python on Itanium Windows 64: available or planned? References: Message-ID: Trent Mick writes: > There are no free binary packages kicking around out there that I know > of but a number of people do compile it themselves for Win64. However, there are free binary packages out there that you don't know of :-) http://www.dcl.hpi.uni-potsdam.de/home/loewis/python23.msi See http://groups.google.com/groups?selm=mailman.1060265944.15612.clpa-moderators%40python.org for the original announcement. > There was some discussion on this list recently about how to do that > seeing as there is no DevStudio for Win64 (at least, that is my > understanding). Again, it depends: With sf.net/projects/vsextcomp, VS 7.1 is very well capable of invoking the Itanium platform SDK compiler (AMD64 coming soon). > > Windows 64 is a bit unusual in that "long" is not large enough to hold > > an address. > > Yup. Though I would use a stronger word than "unusual". :) That may even be a source of bugs. I'm in the process of putting size_t in every place Python currently uses "int" or "long" to store a number of bytes. In some cases, exceeding 4GB (sometimes 2GB) will cause crashes in Python 2.3 (in other cases, this is somewhat overkill - eg. when the compiler complains that strlen(some_file_name) may not fit into 4 bytes). Regards, Martin From summerpusselovin12 at yahoo.com Thu Nov 13 05:52:38 2003 From: summerpusselovin12 at yahoo.com (summerpusselovin12) Date: Thu, 13 Nov 2003 10:52:38 -0000 Subject: im coming over to fuck you Message-ID: in a black skirt with a see thru thong on. you promised you'd let me stand in front of you while your sitting down and i'll bend over so you can lift my skirt up revealing my wet slit. you promised you'd take 1 finger and slightly pull my thong to one side and slide your tongue up and down my slit while my legs shaked and i moaned loudly telling you to lick deeper inside. you then promised you'd tease me with your cock by rubbing it on slit barley entering me. please dont tease too long. just bend me over your table and furiously rip my skirt off to where i'm just wearing that thong. please rip that off too so my pussy is exposed and you'll be able to see my swollen, wet lips which will make you want to thrust your cock right in with your might as I scream your name to fuck harder and faster. you get so winded by my slippery pussy so you asked to lay on the table.Look me up on my casual sex finder site. http://www.hotpersonalad.com/landing.asp?afl=MYHO From jjl at pobox.com Mon Nov 10 17:35:08 2003 From: jjl at pobox.com (John J. Lee) Date: 10 Nov 2003 22:35:08 +0000 Subject: response time References: <1jSrb.2419$9_.105379@news1.tin.it> Message-ID: <87d6bzetsz.fsf@pobox.com> Alex Martelli writes: > Jos? wrote: > > > I'm programming a simple script to calculate response time from one > > server to another server. [...] > > I can only calculate it in seconds, is there a way to do it in > > miliseconds? > > After "import time", time.time() returns the time (elapsed since an > arbitrary epoch) with the unit of measure being the second, but the > precision being as high as the platform on which you're running will > allow. The difference between two results of calling time.time() is [...] Also note that Windows' time(), in particular, has a precision of only around 50 milliseconds (according to Tim Peters, so I haven't bothered to test it myself ;-). Pretty strange. John From jon+usenet at unequivocal.co.uk Mon Nov 24 13:30:33 2003 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 24 Nov 2003 18:30:33 GMT Subject: Question regarding thread atomicity References: <3FC24C35.E5742B6F@engcorp.com> Message-ID: In article <3FC24C35.E5742B6F at engcorp.com>, Peter Hansen wrote: > The basic failure mode would be that two threads both retrieve > the same current value for "bar" and add one to it "INPLACE", then > store it back again: the result is that although two attempts to > add have been made, the value increases by only one. Python won't > crash, which is why this all depends on your definition of "thread-safe", > but it likely won't do what you probably want it to do. Ah. This violates my definition of "thread-safe" ;-) If it doesn't go up by exactly one every time that line is executed, it isn't doing what I want it to do. I guess I'll have to go and add a load of manual locking :-( From bafairbank at sbcglobal.net Sat Nov 22 00:32:11 2003 From: bafairbank at sbcglobal.net (Ben Fairbank) Date: Sat, 22 Nov 2003 05:32:11 GMT Subject: Difficulty Sending email from Python Message-ID: <3fbef2c3.2580550@news.houston.sbcglobal.net> The Python Library Reference Section 12.2.13 gives an example of how to send a simple text message. When I try that, my program seems to start and run OK, my firewall asks for permission for PythonWin to access the internet, then it gets to the line s.connect() and I get an error message whose last two lines are raise SMTPServerDisconnected("Connection unexpectedly closed") SMTPServerDisconnected: Connection unexpectedly closed Now, the odd thing is that when I use my newserver (Free Agent 1.21/32) and try to send email in response to an article I have read, I get the same error message: Connection unexpectedly closed. Obviously the problem is not in Python, but in something in my system. I would welcome suggestions to help untangle it. I have a DSL connection to SBCglobal.net. I usually get and send my email through an address at texas.net, not SBCglobal. Any ideas? Thanks, Ben Fairbank From usenet_spam at janc.invalid Mon Nov 10 01:54:26 2003 From: usenet_spam at janc.invalid (JanC) Date: Mon, 10 Nov 2003 06:54:26 GMT Subject: os.path.vnormpath References: Message-ID: "Ben Allfree" schreef: > Virtual root - C:\foo\baz\wwwroot > URL - > > Should resolve to C:\foo\baz\wwwroot\baz\wwwroot\grop.html According to RFC-2396 this should resolve to: C:\foo\baz\wwwroot\..\..\baz\wwwroot\grop.html The ".." above are real path segments/directory names and don't have the special "go up 1 level" meaning. IMHO for web servers that map URL path segments to local paths this should result in an HTTP error (when ".." is not allowed on the local filesystem). They also mention that in practice your solution is in use by some parsers, so people might not be too surprised by its functioning... ;-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From jjl at pobox.com Thu Nov 20 19:21:28 2003 From: jjl at pobox.com (John J. Lee) Date: 21 Nov 2003 00:21:28 +0000 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <3FBB805D.40A8DA75@engcorp.com> <3FBBA68A.6D819C5C@engcorp.com> <7x8ymcp2eh.fsf@ruckus.brouhaha.com> <87y8ubw5lm.fsf@pobox.com> Message-ID: <87wu9utvuf.fsf@pobox.com> Jorge Godoy writes: > jjl at pobox.com (John J. Lee) writes: [...] > Sorry for my ignorance, but how do you get to decrypt the code to run? What code? > Use any kind of wrapper? Is such a wrapper written in C? Do you store > the key inside such a wrapper? > > The same problem would happen with AES or any other crypt method: > where and how to store the key in a way that's easy for the user. Gee, I guess so ;-) John From jjl at pobox.com Fri Nov 7 09:29:11 2003 From: jjl at pobox.com (John J. Lee) Date: 07 Nov 2003 14:29:11 +0000 Subject: PEP 289: universal and existential operators References: <5d83790c.0310231158.65595858@posting.google.com> <9f76ee00.0311051257.45461381@posting.google.com> <2259b0e2.0311061047.4c53948e@posting.google.com> Message-ID: <87brro9rrc.fsf@pobox.com> mis6 at pitt.edu (Michele Simionato) writes: > austin at smartobject.biz (Jess Austin) wrote in message news:... > > It seems like the consensus is "all" and "any". > > Not necessarely. I prefer "alltrue" and "anytrue", for instance. +1 John From costanza at web.de Mon Nov 3 13:39:54 2003 From: costanza at web.de (Pascal Costanza) Date: Mon, 03 Nov 2003 19:39:54 +0100 Subject: Explanation of macros; Haskell macros In-Reply-To: References: <87brs2tjut.fsf@memetrics.com> Message-ID: Joachim Durchholz wrote: >> This becomes especially useful as soon as your protocols become more >> sophisticated, and you need to insert instructions at arbitrary places >> in the code being passed to a macro, or need to control evaluation of >> the code being passed in some other details. > > Inserting "at arbitrary places" seems rather unmodular to me. > Either the macro would have to know about the code that it's being used > in, so that it can identify the places where to insert the code. > Or the code using the macro will have to pass information to the macro - > which, in a HOF context, means that the code using the HOF approach will > have to pass the code for "before the insertion point" and "after the > insertion point" as separate parameters, and the HOF would do the > necessary linkage between the two codes. > I'm not sure that macros offer a significant gain here. a) "insert instructions at arbitrary places in the code being passed to a macro" means that the macro modifies the code that is being passed to it - not the code that surrounds the use site of a macro. b) For macros, you don't have to partition the information the macro needs to do its job into several parameters. A macro just analyzes the code that is being passed to it, and automagically does the right thing. ;) (This is part of the reason why macros allow you to build abstractions that don't leak: you don't have to arrange the parameters for the macro according to the implementation details of the macro, but in more or less completely arbitrary ways.) c) The significant gain of macros is this: Macros rewrite syntax trees, and you can implement any language feature, domain-specific or not, via syntax tree rewriting. This means that, no matter what happens during software development, you can always find a way to express things in a convenient way. This is mainly a psychological effect: macros greatly reduce the need to plan ahead and allow for experimenting with program designs: Just write down the code as you imagine to be suitable for the concrete problem at hand, and then start to implement it from there. It's very likely that you will find out how to implement the machinery beneath in that process and then write a bunch of macros that translate your original ideas on top of that machinery. You don't have to plan ahead what the "right" design is for you problem. Switch from FP to OOP later on? No problem: rewrite the machinery, reimplement your macros, don't change the high-level code. Oops, your field should have been methods, or externally stored in a database? No problem: rewrite the machinery, reimplement your macros, don't change the high-level code. Without macros, it's very likely that in these cases, when you have to change the design of your libraries, you also have to change client code. With macros, you don't have to. At least not in 99% of the cases. ;-P >> Because of this high level of expressive power that macros provide, >> Common Lispers use them regularly even for simple things. You can >> effectively write domain-specific abstractions that don't leak, and >> therefore it is justified to use them even for simple protocols. > > OK, but the same can be said for HOFs. > The question is: in what ways are macros superior to HOFs to accomplish > this? Most importantly: HOFs as such are rarely domain-specific. So whenever your library requires you to express a piece of code with an anonymous function, you give away details about the implementation of a specific feature. > See it this way: Macros are a way to create blocks of code. HOFs that > return functions do the same: they take a few functions (and possibly > some value arguments), stick them together, and return the result. If > the HOF is evaluated at compile time (something that I'd expect if both > functions and values submitted to the HOF are constant), then you too > have a mechanism that creates a block of code. I don't care about blocks of code or compile-time evaluation, at least not most of the time. When I see this... (with-open-file (stream filename :direction :output :if-does-not-exist :create) (format stream "some output")) ...I see a piece of code that tells the machine to open a file in a specified way, write some output to it and then closes it gracefully. I don't care whether this is achieved by means of OOP abstraction, HOFs, or whatever. Such code "talks" only about the necessary details and nothing else. >>> Does anybody have a keyword-style list of useful applications of the >>> macro facilities? >> >> >> Do you have a keyword-style list of useful applications of functions? > > > I think you forgot a smiley - at least, that question is entirely silly. > If you have a real point to make, please make it explicit; I have too > little time to devote to decoding your intents. (And if you don't want > to spend time on trivialities, then please understand that I don't, too.) Your question is as silly as mine. ;) If you want to get an idea what you can do with macros, Paul Graham provides an excellent overview in his book "On Lisp" that you can download for free at http://www.paulgraham.com/onlisp.html Pascal From peter at engcorp.com Wed Nov 5 15:59:00 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 05 Nov 2003 15:59:00 -0500 Subject: Why no try-except-finally ? References: <3FA8F1F8.62A0D382@engcorp.com> <20031105153219.28640.00000271@mb-m15.aol.com> Message-ID: <3FA96494.643C3594@engcorp.com> KefX wrote: > > >Somewhat better style, generally, IMHO, would be to replace "err_code = 1" > >with "raise" in the above. Consider returning error codes to be a > >parallel (and somewhat obsolescent) way of communicating failures to > >calling code. Raising an exception should be generally preferred. > > I agree with you in general, but this code is in my main() function, and > returning an error code one way or another is the only way to report the error > status to the OS. :) > > Instead of this: > > if __name__ == '__main__': > main() > > my code does this: > > if __name == '__main__': > sys.exit(main()) > > I believe Guido suggested that idiom in his blog. Ah, then I would suggest moving the code that requires proper cleanup (the finally part) down a level, and simplify the top level so that all it does is catch all exceptions and convert to an error value which it then returns. Works out to about the same thing as saying "nest the try clauses" but at least it has the advantage of higher cohesion in the two separate code areas. -Peter From cristian at canarias.org Sat Nov 22 20:49:15 2003 From: cristian at canarias.org (hernandez) Date: Sun, 23 Nov 2003 01:49:15 -0000 Subject: newbie - where can i view a python application? References: <3fbfec4f_1@themost.net> Message-ID: yes... but java is appropiated for applets, internet applications.. perl CGI...etc... i mean.. python is multipurpose? "Paul Watson" escribi? en el mensaje news:3fbfec4f_1 at themost.net... > Python is a programming language. > > What can I do with C++? > What can I do with Java? > What can I do with Perl? > What can I do with Python? > > > "hernandez" wrote in message > news:bpojoa$1rlknr$1 at ID-212245.news.uni-berlin.de... > > hello all. > > is python specific for an especific area? > > > > what can i do with python? > > > > thanks for answer 'this kind of questions' !! > > > > > > > > From dgallion at yahoo.com Thu Nov 27 11:31:41 2003 From: dgallion at yahoo.com (darrell) Date: Thu, 27 Nov 2003 16:31:41 GMT Subject: Suggestion for a new regular expression extension In-Reply-To: <3fbce8a0$0$25040$afc38c87@news.easynet.fr> References: <3fbce8a0$0$25040$afc38c87@news.easynet.fr> Message-ID: If you can make re.sub work for you... import re pat="B(?:D|LD|VD|OUL(?:EVARD)?)" input="BD, BLD, BVD, BOUL, BOULEVARD.".split() for i in input: print i, "::", re.sub(pat, "BD", i) BD, :: BD, BLD, :: BD, BVD, :: BD, BOUL, :: BD, BOULEVARD. :: BD. For more complex cases you can pass a function instead of the replacement string. --Darrell From eppstein at ics.uci.edu Sun Nov 9 14:27:21 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 09 Nov 2003 11:27:21 -0800 Subject: Help for unicode References: <3fad6fb5$0$58715$e4fe514c@news.xs4all.nl> <2perb.101236$vO5.3965040@twister1.libero.it> Message-ID: In article <2perb.101236$vO5.3965040 at twister1.libero.it>, "Noixe" wrote: > If I write: > > print u'\u2205' > > I have this error: UnicodeError: ASCII encoding error: ordinal not in > range(128) > > > Why? I must include some module? You have to specify which encoding you want to print it in. E.g. >>> print u'\u2205'.encode('utf8') Of course this will only work if the output stream you print to is set up to use that encoding... -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From francis at francisbarnhart.com Fri Nov 21 10:03:07 2003 From: francis at francisbarnhart.com (Francis Barnhart) Date: Fri, 21 Nov 2003 10:03:07 -0500 Subject: Question about Objects - repost with correct email account In-Reply-To: References: Message-ID: <20031121150307.GA90460@francisbarnhart.com> Because getSomething is a method you need to use: >>> x.getSomething() -- Francis Barnhart francis at francisbarnhart.com http://francisbarnhart.com AIM: FrAniMaL "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -- Benjamin Franklin, Historical Review of Pennsylvania, 1759 From newsgroups at jhrothjr.com Tue Nov 18 07:50:51 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 18 Nov 2003 07:50:51 -0500 Subject: PEP 321: Date/Time Parsing and Formatting References: <20031117161752.GA17615@nl.linux.org> Message-ID: "Bengt Richter" wrote in message news:bpc05s$3kp$0 at 216.39.172.122... > On Mon, 17 Nov 2003 20:19:12 -0500, "John Roth" wrote: > > > Any order other than y-m-d is brain dead if you are going to sort on the text. I certainly agree, although I remember one project I worked on as a contractor where the code woodenly went through two compares on every date because they insisted on storing it the same way it was displayed: mmddyy. (European conventional order (ddmmyy) requires three tests, which may be why the ISO format is more popular in Europe. I think.) Of course, having a date object eliminates all of those issues... John Roth > > Regards, > Bengt Richter From missive at frontiernet.net Thu Nov 13 19:52:44 2003 From: missive at frontiernet.net (Lee Harr) Date: Fri, 14 Nov 2003 00:52:44 GMT Subject: Making a maze.... References: <1PSsb.44675$jy.34613@clgrps13> Message-ID: On 2003-11-13, Bernard Fields wrote: > Greets, all. > > > As the title suggests, I'm trying to make a maze. Specifically, it's a > top-down, 2-d maze, preferably randomly generated, though I'm willing to > forego that particular aspect as this point. > > I've done many, many web-searches, but nothing that I've found so far has > provided any clues.... > > How about xscreensaver? http://www.jwz.org/xscreensaver/ The code is all C, but you could probably translate the algorithm to python without too much trouble. Looks like maze.c has at least 3 different methods. From tzot at sil-tec.gr Wed Nov 5 13:31:25 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 05 Nov 2003 20:31:25 +0200 Subject: auto-upgradable application References: <18e22d94.0311050900.41faab5d@posting.google.com> Message-ID: On 5 Nov 2003 09:00:44 -0800, rumours say that reneaguirre at yahoo.com (Rene Aguirre) might have written: >So, I was thinking about adding an auto update feature to my app, if >anybody knows about any package for these purpose would be great. I don't know if that really would help, but you might like to check the file 'mhautupd.py' in the following directory: http://www.sil-tec.gr/~tzot/manhang/nt/ which downloads newer versions of the other modules of the program over HTTP. I believe it won't be hard to suit it to your needs. Basically, you will need only the first for loop in the do_updownloads function. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From olivier.hoarau at mortauxspams.bz Thu Nov 13 08:38:33 2003 From: olivier.hoarau at mortauxspams.bz (Olivier Hoarau) Date: Thu, 13 Nov 2003 14:38:33 +0100 Subject: Validate XML with RELAX NG Message-ID: <3FB38959.CE275465@mortauxspams.bz> Hello, I have to validate a xml file, for that I use libxml and its function xmllint which needs the RELAX NG "full" schema of the file. I have only its RelaxNG compact schema, I have to transform it first in Relax NG "full". To transform RelaxNG compact to RelaxNG "full", I use rnc2rng written in Python. I have some difficulties, the file I obtain from a RELAXNG compact file is not conform. Is there someone in this newsgroup who knows this tools ? Olivier PS: Excuse for my poor english From hwlgw at hotmail.com Fri Nov 7 16:00:01 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 7 Nov 2003 13:00:01 -0800 Subject: ANN: vb2py online code conversion References: <1RMib.25623$X66.10435@twister.austin.rr.com> Message-ID: Paul Paterson managed to use a modern Python version for CGI, on sourceforge. Since sourceforge is about the only free hosting for Python CGI (if you get a project registered there) I would think it is in the interest of Python to have a better way than this! Because, if people can not serve their CGI script, or only with much difficulty, then they will maybe give up on Python. We could lose good people that way. Don't just blindly send them to "twisted". Not everybody has a free or cheap permanent internet connection. Not everybody wants to check forever if their webapplication is still running. CGI is the way to go for many. Could one of the Python-Unix-Solaris-CGI gurus please improve the situation on sourceforge? I tried but I can't. Something like "everybody on sourceforge can use #!../../blah/lib/python" would do :-) Paul: congratulations on getting things to work...you must have been very determined; I would not have that much patience (gave up on *compiling* Python there after all the weird errors %-). > [Paul Paterson] > > The Shell is now at 2.2 but cgi is still using 1.5.2, which was rather > puzzling for a while as things appeared to be working but weren't. > > I had to install my own copy of Python.... > ... ... > Now there has to be a better way than this but ... > > 7. Add the following lines to your script: > > import sys > sys.path.append("path to your python folder") > sys.path.append("path to your lib-dynload") > sys.path.append("path to where your other 'site-packages' will live") > > Anyway, this worked for my application which uses library and > non-library packages. From peter at engcorp.com Mon Nov 10 13:57:50 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Nov 2003 13:57:50 -0500 Subject: make order of function definitions irrelevant References: Message-ID: <3FAFDFAE.514DC8EB@engcorp.com> Joerg Schuster wrote: > > according to > > http://mail.python.org/pipermail/tutor/2001-July/007246.html > > the order of function definitions does matter in python. Does anyone > know a trick to avoid this? No. > Is there a way to "declare" functions without defining them? No. > (Making the order of function definitions irrelevant would be useful > for automatically generated python scripts.) No, it would not. Basically, the problem you believe is here is not a problem in actual practice. You could add declarations to Python-the-language, but they're irrelevant until the function is actually called. When the function is called, it has to have been defined (not just declared) and so the declaration would be completely redundant. -Peter From __peter__ at web.de Wed Nov 26 14:27:07 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Nov 2003 20:27:07 +0100 Subject: Is there a .tolower() for a string?? References: <7b1fa3cb.0311261057.ecb7325@posting.google.com> Message-ID: Amy wrote: > I have a string say > > a = "Hello how are YOU" > > I want to end up with > > a = "hello how are you' > > Isn't there a built in method for changing a string to lowercase? dir("") will give you all str attributes. The most promising is lower, so let's try: >>> a = "LOWER" >>> a.lower() 'lower' >>> a 'LOWER' You might not have expected the last outcome. This is because the lower() method does not change the original string but creates a new one that is all lowercase. Strings are "immutable", i. e. cannot be changed once they are created. To get the desired effect, you need to "rebind" a: >>> a = a.lower() >>> a 'lower' Peter From ville.spammehardvainio at spamtut.fi Wed Nov 5 02:40:43 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 05 Nov 2003 09:40:43 +0200 Subject: bash Vs python ?? References: Message-ID: William Park writes: > It depends. My guess is Bash would be more suitable for "automated > testing scripts", since you'll be calling lots of utilities. os.system, os.popen family, pexpect... In python it's much easier to process the output and produce the input of the utilities. Bash is good for throwaway one liners, Python is good for scripts that you *gasp* save to a file and might also execute later. You never know, you might want to extend the testing system later on, perhaps developy advanced logging facilities etc. The shell has one advantage over Python, though: it can be executed in the environment of current shell (i.e. '. myscript.sh'), so you can change the environment variables in the surrounding environment. In python you would have to do export MYENVVAR = $(python calcvalforvar.py) If that is what you need, you might want to use bash. Otherwise, use python. And even if you need that, you might want to generate the bash script in a python script. A good rule of thumb is: The less non-python stuff you have around, the better. Non-python parts of any given system are invariably the ones causing most of the problems :-). -- Ville Vainio http://www.students.tut.fi/~vainio24 From tzot at sil-tec.gr Wed Nov 19 06:24:29 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 19 Nov 2003 13:24:29 +0200 Subject: Suggestion for two additions to the Python FAQ Message-ID: I propose the following two links to aid frequently asked questions: 1. "Help me, my program is failing" and no other data http://groups.google.com/groups?selm=ahbou%3D8crskm%24sf1%241%40oravannahka.helsinki.fi 2. "Help me, I want to: {homework assignment}" http://groups.google.com/groups?selm=ahbou%3D15o24vgel5u8k8go1gff3lum1cf715f0gn%404ax.com ;-) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From francisgavila at yahoo.com Tue Nov 25 19:10:48 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Tue, 25 Nov 2003 19:10:48 -0500 Subject: Python docs in Info format? References: <7x3ccc87ki.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message <7x3ccc87ki.fsf at ruckus.brouhaha.com>... >Has anyone got a script to convert the Python docs (particularly the >library reference) to Info format, so they can be browsed with the >Emacs Info browser? That would be much more convenient than having >to fire up a web browser all the time. Thanks. Um, no need to convert: http://www.python.org/doc/2.3.2/download.html -- Francis Avila From aleax at aleax.it Thu Nov 6 03:22:15 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 06 Nov 2003 08:22:15 GMT Subject: prePEP: Decimal data type References: Message-ID: Tim Peters wrote: ... > You do need to explicitly round (if desired) after * and /. Because of > the high value attached to 100% conformance to imposed standards in > accounting apps, I think it's a good thing that you're forced to round > explicitly when the result of a calculation can't be represented exactly > in the mandated format -- those are exactly the places where your app will > fail to meet the requirements, so it's good to be aware of them. European Union directives (adopted as laws by member states) mandate the rounding procedure to be used in computations involving Euros (round to closest Eurocent, always round up on half-Eurocent results); they very explicitly mention that this may give a 1-Eurocent discrepancy compared to "exact" arithmetic, and give examples; they establish that such a 1-cent discrepancy that comes from following exactly the prescribed rules is NOT legal cause for any lawsuit whatsoever; they earnestly recommend that all computing equipment and programs follow these same rules to avoid the huge headaches that would result in trying to reconcile accounts otherwise. Thus, for most accounting programs intended to run within the EU (not just in Euros: these provisions also apply to the other non-Euro currencies, as far as EU law is concerned), I do NOT think it would be a good thing for the programmer to have to remember to round explicitly -- the legal mandate is about rounding rules and it's quite easy to avoid the "fail to meet the requirements", as they seem designed to be easy to meet. Whether Decimal itself allows an optional rounding-policy (including of course "no rounding" as a possibility) is one issue (I guess that might violate some ANSI or IEEE standard...?) but I most surely do want to be able to use such policies in whatever arithmetic type underlies Money -- so I hope Decimal is at least designed so that _subclasses_ can easily provide such customized rounding (e.g., feature-testing for a __round__ specialmethod, not defined in the baseclass Decimal if need be, but offering the needed hook for subclasses to add the functionality). Alex From grey at despair.dmiyu.org Mon Nov 17 18:57:36 2003 From: grey at despair.dmiyu.org (Steve Lamb) Date: Mon, 17 Nov 2003 23:57:36 -0000 Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: On 2003-11-11, Robin Becker wrote: > This whole thread is reminiscent of vi vs emacs or an os war or similar. > It's a pity that people with a preferred style should be so dogmatic > that they want to remove language features to prevent others using them. The difference there is clear. vi vs. emacs, OS A vs. OS B are two completely different entities. We're talking about the same one here. That one has a basic philosophy. > The whole 'only one way to do it' concept is almost certainly wrong. Erm, no. > There should be maximal freedom to express algorithms. As others have > stated min, max,... sum et al are useful specialisations, but because > they cover 99% of the space doesn't mean that reduce is redundant. > -Eliminate reducespeak and control the future-ly yrs- You have quite a few languages you can do that in. 5+ years in Perl and I'm done with TIMTOWTDI, thank-you-very-much. I'm glad that in Python I don't have to learn several different ways to do the same basic thing. I lament every time I have to step into another language which has several ways to do the same thing and if at any time Python fits the problem space that language occupies perfectly (as in the case of Perl) then I advocate the hell out of it. I'm glad I no longer have to deal with 4 ways of doing a simple if statement. I'm glad that there are only two loop constructs; one for iterating over a sequence and one that runs until a condition is met. It means that at the core level I can read the code and immediately see what is going on instead of having to memorize a dozen or so specilized ways of doing things. Oddly enough it is in Python that I have had the most fun programming. It is in Python that I find myself not only the most expressive but the most elegant in my programming. In Python my code is the clearest and most concise. I don't for one instant feel constrained by Python. I feel liberated by it. Because as much as it helps when reading the code to only have to learn a minimal set of controls the same applies to writing code as well. When I approach a problem I don't have to agonize over "well, should I do a do...until(), a for(;;), a while(), or something else?" It breaks down to this. Is it a sequence? For. Is it a condition to be met? While. There, done, move along. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From bokr at oz.net Mon Nov 17 21:29:16 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Nov 2003 02:29:16 GMT Subject: PEP 321: Date/Time Parsing and Formatting References: <20031117161752.GA17615@nl.linux.org> Message-ID: On Mon, 17 Nov 2003 20:19:12 -0500, "John Roth" wrote: > >"Bengt Richter" wrote in message >news:bpbq7h$nf2$0 at 216.39.172.122... >> On Mon, 17 Nov 2003 17:59:24 -0500, "John Roth" >wrote: >> >> > >> >"Gerrit Holl" wrote in message >> >news:mailman.803.1069091744.702.python-list at python.org... >> >> Hi, >> >> >> >> PEP 321 reads: >> >> > Python 2.3 added a number of simple date and time types in the >> >> > ``datetime`` module. There's no support for parsing strings in >various >> >> > formats and returning a corresponding instance of one of the types. >> >> > This PEP proposes adding a family of predefined parsing function for >> >> > several commonly used date and time formats, and a facility for >generic >> >> > parsing. >> >> >> >> I was recently surprised by this fact. I don't know why there isn't >> >> such a function/method. In my opinion, it isn't a question of whether >> >> to add them or not, but how. >> >> >> >> > Input Formats >> >> > ======================= >> >> > >> >> > Useful formats to support include: >> >> > >> >> > * `ISO8601`_ >> >> > * ARPA/`RFC2822`_ >> >> > * `ctime`_ >> >> > * Formats commonly written by humans such as the American >> >> > "MM/DD/YYYY", the European "YYYY/MM/DD", and variants such as >> >> > "DD-Month-YYYY". >> > >> >I didn't notice this going past the first time: YYYY/MM/DD is the >> ^--UIAM, >NOT! >> >ISO standard format, DD/MM/YYYY is the European variant to >> >the American MM/DD/YYYY. >> >> I thought '-' delimiters were standard, and the yyyy-mm-dd ordering >standard, >> and anything else a variant. > >I usually don't worry about the delimiters, but you're probably right. The >ISO >standard is yyyy-mm-dd, however, the *customary* usage in most of the >world is dd-mm-yyyy, and in the US it's mm-dd-yyyy. In fact, you'd have >difficulty finding anyone around these parts who knows that year first >is a standard, let alone *the* international standard. And I very seldom >see it on the web sites I visit, regardless of country of origin. > Well, I have long had my NT4 set up to do thus: [18:15] C:\pywk\clp>dir d:\python23\*exe Volume in drive D is MS Tools Volume Serial Number is 14B9-2636 Directory of d:\python23 03-10-02 20:03 20,538 python.exe 03-10-02 20:04 20,539 pythonw.exe 01-09-28 18:00 164,864 UNWISE.EXE 03-10-02 20:03 16,384 w9xpopen.exe 4 File(s) 222,325 bytes 170,338,304 bytes free And a utility takes that as a stream and uses directories to make full paths, and filters it with a regex ('.' here): [18:17] C:\pywk\clp>dirf . d:\python23\*exe 03-10-02 20:03 20,538 d:\python23\python.exe 03-10-02 20:04 20,539 d:\python23\pythonw.exe 01-09-28 18:00 164,864 d:\python23\UNWISE.EXE 03-10-02 20:03 16,384 d:\python23\w9xpopen.exe But the real reason is [18:17] C:\pywk\clp>dirf . d:\python23\*exe |sort 01-09-28 18:00 164,864 d:\python23\UNWISE.EXE 03-10-02 20:03 16,384 d:\python23\w9xpopen.exe 03-10-02 20:03 20,538 d:\python23\python.exe 03-10-02 20:04 20,539 d:\python23\pythonw.exe Any order other than y-m-d is brain dead if you are going to sort on the text. My dirf thing can go into nested dirs, so dirf . what*ever/s/od doesn't make an overall sort, but piping it to sort does. Of course, pre-2000 comes out at the wrong end of the sort, but I couldn't convince windows to give me yyyy-mm-dd at the time ;-/ It is often very handy to be able to sort a full directory with full paths, to see things that happened in time sequence around some event time. BTW, maybe we could make an msys-style version of the above a platform-independent os.listdir format? (I.e., d:\python23\python.exe => /d/python23/python.exe on windows). >John Roth >> >> See >> http://www.w3.org/TR/NOTE-datetime >> or >> http://www.iso.ch/iso/en/prods-services/popstds/datesandtime.html >> >> [...] >> >> Regards, >> Bengt Richter > > Regards, Bengt Richter From ramen at lackingtalent.com Wed Nov 12 01:32:15 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 12 Nov 2003 06:32:15 -0000 Subject: True, False, None References: <20031110065915.07735.00000461@mb-m07.aol.com> Message-ID: In article , Andrew Dalke wrote: > Dave Benjamin: >> And so are modules... ;) > > True. But there's only rough consistancy on how those are > capitalized. I thought the old rule of thumb was that if its main purpose was to expose a class, name it after that class (and capitalize), otherwise, name it after the concept it represents, in lower case. If you were to use a module as a singleton value or namespace, would you capitalize it? Just curious, Dave -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From ulope at gmx.de Sat Nov 8 07:29:54 2003 From: ulope at gmx.de (Ulrich Petri) Date: Sat, 8 Nov 2003 13:29:54 +0100 Subject: __slots__ References: <9d5f9ae4.0311070836.7503de86@posting.google.com> Message-ID: "flori" schrieb im Newsbeitrag news:9d5f9ae4.0311070836.7503de86 at posting.google.com... > i try to greate somthing like this > > class ca(object): __slots__ = ("a",) > class cb(ca): __slots__ = ("a","b") > class cc(ca): __slots__ = ("a","c") > class cd(cb,cc): __slots__ = ("a","b","c","d") > > but i didn't find a simple solution > so i'm using a metaclass that generate a __slots__-free and a > __slots__-version > the __slots__ -free is returned > the __new__ of the base class look for the sloted verion > the classes defines a (class)-attribute __object_slots__ with their > new attribute names. > > killer? someone a good idea? > > my soure (something not important i'm cutting away) > What exactly are you trying to accomplish? Ciao Ulrich From amk at amk.ca Wed Nov 12 15:11:29 2003 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 12 Nov 2003 14:11:29 -0600 Subject: Reversing an iterator with older version of Python References: Message-ID: On 12 Nov 2003 10:22:12 -0800, Aki Niimura wrote: > I need to reverse an iterator in my program. Convert it to a list and then reverse the list: L = list(iterator) L.reverse() This means that the contents must fit in memory, but that's probably OK; if you want to read the lines of a 2-gigabyte file in reverse order, you're better off writing some custom code for reading the file. --amk From max at alcyone.com Wed Nov 5 17:58:41 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 05 Nov 2003 14:58:41 -0800 Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> Message-ID: <3FA980A1.4C86AED0@alcyone.com> Francis Avila wrote: > Just out of curiosity, for what kind of problems do we find reduce to > just > be the Right Way? I mean, summing a big list of numbers is fun and > all, but > I never find any use for it otherwise. I *often* try to think if > reduce > would be useful when I come across some collection-of-values > manipulation > task, but usually one wants to repeat an operation on a whole set of > values, > not reduce the set to one value. I don't use reduce extremely routinely, but I certainly do find myself using it. Grepping through my Python sources, the most common uses I find are summing together lists of numeric values and joining together (flattening) a list of lists (though only when the contained lists themselves do not contain any sequences as elements). > So, are there any *non-trivial* and *unabusive* uses of reduce, where > any > other way would be tedious, repetitive, slow, unclear, etc.? I'm very > curious to see them. My cellular automaton engine CAGE uses reduce several times, although admittedly this use is academic (obviously a good way to implement a ReductionRule is almost by definition with a reduce operation :-). Even then, there are times when, say, you want to get the sum of the states of the cells in the neighborhood, and "neighborhood" is defined in a sufficiently generic way that the states of the neighborhood are just a list of state values. My Solar System calculator BOTEC has a similar application; when plotting courses, you can have an arbitrary number of transfers, and those transfers can each have an arbitrary number of burns. So it's quite convenient to do a reduce on the list of burns (a sequence of sequences), and then a reduce on the list of deltavees for the transfers (a sequence of numerics). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Thousands have lived without love, not one without water. \__/ W.H. Auden From aleax at aleax.it Fri Nov 14 07:37:24 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Nov 2003 12:37:24 GMT Subject: How sum() should really be done References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <653b7547.0311121826.65b6b2d4@posting.google.com> <3FB40AD4.9428C78A@alcyone.com> Message-ID: <804tb.20364$9_.724659@news1.tin.it> Douglas Alan wrote: > Erik Max Francis writes: > >> Douglas Alan wrote: > >>> Ah, that reminds me -- both sum() and reduce() can be removed from >>> Python by extending operator.add so that it will take any number of >>> arguments. > >> reduce can't, since reduce doesn't require the function passed to be >> operator.add. > > Well, as I said, for this to be true, *all* binary operators (that it > makes sense to) would have to be upgraded to take an arbitrary number > of arguments, like they do in Lisp. Your definition of "operator" appears to be widely at variance with the normally used one; I've also noticed that in your comparisons of reduce with APL's / , which DOES require specifically an OPERATOR (of the binary persuasion) on its left. reduce has no such helpful constraints: not only does it allow any (callable-as-binary) FUNCTION as its first argument, but any other CALLABLE at all. Many of the craziest, most obscure, and worst-performing examples of use of reduce are indeed based on passing as the first argument some callable whose behaviour is anything but "operator-like" except with respect to the detail that it IS callable with two arguments and returns something that may be passed back in again as the first argument on the next call. [see note later]. Anyway, to remove 'reduce' by the trick of "upgrading to take an arbitrary number of arguments", that "upgrade" should be applied to EVERY callable that's currently subsceptible to being called with exactly two arguments, AND the semantics of "calling with N arguments" for N != 2 would have to be patterned on what 'reduce' would do them -- this may be totally incompatible with what the callable does now when called with N != 2 arguments, of course. For example, pow(2, 10, 100) now returns 24, equal to (2**10) % 100; would you like it to return 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376 instead...?-) I doubt there would be any objection to upgrading the functions in module operator in the way you request -- offer a patch, or make a PEP for it first, I would hope it would be taken well (I can't speak for Guido, of course). But I don't think it would make much more of a dent in the tiny set of reduce's current use cases. [note on often-seen abuses of FP built-ins in Python] Such a typical abuse, for example, is connected with the common idiom: for item in seq: acc.umul(item) which simply calls the same one-argument callable on each item of seq. Clearly the idiom must rely on some side effect, since it ignores the return values, and therefore it's totally unsuitable for shoehorning into "functional-programming" idioms -- functional programming is based on an ABSENCE of side effects. Of course, that something is totally inappropriate never stops fanatics of functional programming, that have totally misunderstood what FP is all about, from doing their favourite shoehorning exercises. So you see: map(acc.umul, seq) based on ignoring the len(seq)-long list of results; or, relying on the fact that acc.umul in fact returns None (which evaluates as false), filter(acc.umul, seq) which in this case just ignores an _empty_ list of results (I guess that's not as bad as ignoring a long list of them...?); or, of course: reduce(lambda x, y: x.umul(y) or x, seq, acc) which does depend strictly on acc.umul returning a false result so that the 'or' will let x (i.e., always acc) be returned; or just to cover all bases reduce(lambda x, y: (x.umul(y) or x) and x, seq, acc) Out of all of these blood-curling abuses, it seems to me that the ones abusing 'reduce' are the very worst, because of the more complicated signature of reduce's first argument, compared to the first argument taken by filter, or map with just one sequence. To be sure, one also sees abuses of list comprehensions here: [acc.umul(item) for item in seq] which basically takes us right back to the "abuse of map" case. List comprehension is also a rather FP-ish construct, in fact, or we wouldn't have found it in Haskell to steal/copy it...;-). Alex From gerson.kurz at t-online.de Sat Nov 1 10:00:22 2003 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Sat, 01 Nov 2003 15:00:22 GMT Subject: ANN: pyfromc - Python from C++ and vice versa References: <3fa3488c.12101640@news.t-online.de> <3FA3B325.1491D228@engcorp.com> Message-ID: <3fa3c4e1.43930000@news.t-online.de> Peter Hansen wrote: >Gerson, why not browse http://www.opensource.org/licenses/ I find "licensing" example code, at best, ridiculous. And that's basically all it is: it is an example, a starting point - it contains only one method "test". Please. It took some work to figure out how to exactly put the pieces together - but now that it works its almost trivial. Licensing example code is anal-retentive, over-protective and paranoid. There are way too many licenses attached to way too much unlicenseworthy stuff, just for the sake of license fetishism, and, I must say, "open source" has been not completely innocent in this development. I don't care if you manage to *sell* an example code that is freely available on the internet - if you do manage to sell it, hell, you *deserve* the money. Some years ago I wrote a joke language, SMITH# http://p-nand-q.com/humor/programming_languages/smith.html It is a joke, right, it is in my humor section. Well, I got contacted by debian-legal and you can read the exchange here: http://lists.debian.org/debian-legal/2001/debian-legal-200110/msg00170.html Debian actually has a list devoted to legal issues. I don't know about you, but I find that perverted, for a distribution that prides itself on its freedom. Back in the 80s, when I started programming on the Atari & Amiga, before the GPL became any public issue, we had three kinds of licenses : None, Public Domain and Other. And, guess what, I "published" software (say, in 1994 - be aware, I was kind of emotional back then - http://wuarchive.wustl.edu/aminet/util/moni/snoopy20.readme) and have never sued anybody since, nor been sued by anyone. Life is good! So, relax. From jan at jandecaluwe.com Fri Nov 7 06:39:45 2003 From: jan at jandecaluwe.com (Jan Decaluwe) Date: Fri, 07 Nov 2003 12:39:45 +0100 Subject: Issue with exception info formatting by traceback module Message-ID: <3FAB8481.4060303@jandecaluwe.com> Hi: There is a difference between exception info formatting by the interpreter versus the traceback module. For example, say we define an exception Error in file module.py: [jand at localhost jand]$ python Python 2.3 (#1, Sep 12 2003, 15:05:00) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import module >>> raise module.Error("test") Traceback (most recent call last): File "", line 1, in ? module.Error: test >>> try: ... raise module.Error("test") ... except: ... import traceback ... print traceback.print_exc() ... Traceback (most recent call last): File "", line 2, in ? Error: test None >>> In the second case, only the basename of the error is reported, which is less clear. This is relevant because the unittest framework uses the traceback module for exception reporting. I believe the traceback module should be modified to mimic the interpreter's behavior. Regards, jan -- Jan Decaluwe - Resources bvba - http://jandecaluwe.com Losbergenlaan 16, B-3010 Leuven, Belgium Bored with EDA the way it is? Check this: http://jandecaluwe.com/Tools/MyHDL/Overview.html From peter at engcorp.com Tue Nov 11 09:59:13 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Nov 2003 09:59:13 -0500 Subject: Tinkering with builtins (was: Re: True, False, None) References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311110003.567dc235@posting.google.com> Message-ID: <3FB0F941.939D0384@engcorp.com> Michele Simionato wrote: > > "John Roth" wrote in message news: > > There's a movement > > to make just about everything in the built-in scope immutable and > > not rebindable at any lower scope for performance reasons. > > I am a bit worried by this movement. While I have found no reason to twick > the builtins in production code, I have found specific situations where > the ability of tinkering with the builtins is extremely convenient. > Typically this happens in the debugging phase. For instance I have used > tricks such as modifying the `object` class to induce tracing capabilities > on all my classes, withouth touching my source code. Another use case I've raised in the past, and I believe it is accepted that it is a valid one, is in automated unit testing or acceptance testing where it is often extremely beneficial to be able to "mock" a builtin by replacing it with a custom test method. For us, the most common use of this is to change open() to return a special mock file object which doesn't actually cause any disk access. Removing the ability to do this would cripple our ability to properly test some code. Alex' suggestion of using -O to switch to a mode where builtins are static is okay as far as it goes, but it would prevent proper testing of code that relies on the aforementioned technique when one wishes to verify that the standard -O improvements still work. I'd vote for decoupling this behaviour from the rest of -O, as Michele suggests. -Peter From tjreedy at udel.edu Mon Nov 17 19:17:54 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Nov 2003 19:17:54 -0500 Subject: Python's simplicity philosophy References: <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> <%N8tb.28277$hV.1041253@news2.tin.it> Message-ID: "Alex Martelli" wrote in message news:Jj4ub.42718$hV.1644648 at news2.tin.it... > The point is that the primary meaning of "reduce" is "diminish", > and when you're summing (positive:-) numbers you are not diminishing > anything whatsoever Yes you are: you are reducing the number of numbers. Data reduction is a standard term (in US at least) for literally reducing lots of numbers to a fewer number of numbers, like count, sum, mean, sum_of_squares, variance, and/or maybe a few others. As the volumn of data generated by observational and experimental studies explodes, useful reduction becomes even more important. . unless you think in terms of multidimensional > arrays and diminishing dimensionality, Reducing a dimension 1 vector to a dimension 0 number is reduction in both senses. But even reduction of a homogeneous array to tuple of statistics is reduction in number if not dimension. Perhaps my career in statistics and data reduction made reduce() more immediately obvious to me than some other people. Terry J. Reedy From mikit at zoran.co.il Sat Nov 29 17:38:47 2003 From: mikit at zoran.co.il (Miki Tebeka) Date: 29 Nov 2003 14:38:47 -0800 Subject: How to I lock a file ? References: Message-ID: <6250403b.0311291438.6aaa8920@posting.google.com> Hello, > f1=file('a',"w+",os.O_EXCL|os.O_WRONLY) Have a look at the documentation, the 3'rd parameter to "file" is the buffer size. > So how to I lock this file to prevent from next opening ? Use os.open or the win32all package (with CreateFile). HTH. Miki From jcb at iteris.com Wed Nov 5 18:13:08 2003 From: jcb at iteris.com (MetalOne) Date: 5 Nov 2003 15:13:08 -0800 Subject: Is this horrible python code? References: Message-ID: <92c59a2c.0311051513.3b8801f8@posting.google.com> I think it is simpler using closures. def auditFunc(info, func, *args, **kw): def inner(): print 'finished a_func.__init__()' print info print "Execing..." ret = func(*args, **kw) print 'exiting a_func.__call__()' return ret return inner f = auditFunc({'name': 'Print a message'}, print_message) f() another = auditFunc({'name': 'Print a number'}, print_num, 42) another() From hungjunglu at yahoo.com Sun Nov 9 05:26:54 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 9 Nov 2003 02:26:54 -0800 Subject: Pure Aspect-Oriented Program: an example References: <8ef9bea6.0311052119.4f5ab5d6@posting.google.com> Message-ID: <8ef9bea6.0311090226.3cb67d10@posting.google.com> hungjunglu at yahoo.com (Hung Jung Lu) wrote in message > Here I only present a possible syntax of the "around" advice. > ... > aspect A { > method f_before_A = f > method f(...) { > print 'begin around-advice' > result = this.f_before_A() > print 'end around-advice' > return result > } > } (I changed comp.lang.java to comp.lang.java.programmer) Yikes, that's awfully bad. It violates functional programming philosophy of the meta-methods. I finally figured out a cleaner syntax for the "around" advice, using @-decorated names and method hooks. class M { method f(x) { print 'multiply by 2' result = 2 * x print 'result =', result return result } } aspect A { codeblock f_with_A { print 'post-multiply by 3' result = 3 * &f(...) print 'result =', result return result } method f at A(...) { this.f_with_A { &f = this.f@ } } } aspect B { codeblock f_with_B { print 'pre-multiply by 4' x = 4 * x result = &f(...) print 'result =', result return result } method f at B(...) { this.f_with_B { &f = this.f@ } } } aspect C inherits A, B { method f at C(...) { this.f_with_B { &f = this.f at A } } } endow M with C m = new M() x = 1 print 'input =', x print m.f(x) //------ output input = 1 pre-multiply by 4 post-multiply by 3 multiply by 2 result = 8 result = 8 result = 24 Notice that I have used a method hook &f, not a codeblock hook. Notice also the usage of (...) for signature decoupling. Aspect C will create the "@-decorated" methods f at A, f at B and f at C for class M. The original method can always be accessed as f@(x). When f(x) is accessed without name decoration, the latest @-decorated implemention is used. However, in order to avoid meta-method ambuiguities in multiple-aspect inheritance, the hooking process should always be done with explicit @-decorated names. If you really don't like a particular meta-method, you can always override it. So I think usage of explicit @-decorated name inside a meta-method should be OK. I guess the @-decoration could be used in all meta-methods, that is, even for the cases of "before" and "after" advices. Hung Jung From Mike at DeleteThis.Geary.com Wed Nov 12 14:03:26 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 12 Nov 2003 11:03:26 -0800 Subject: case-sensitivity References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> Message-ID: Douglas Alan: > I agree with Alex. Case sensitivity is evil! When color > monitors started becoming common, I began to worry > that programming languages would come to allow you > to have blue variable names, and red and green variables > names, and they would all be different. Or maybe even > variable names in mixed color! Then in mixed color and > font. I better be quiet now, lest I give anyone ideas. Too late. http://www.colorforth.com/ -Mike From google_mail at aristoweb.net Fri Nov 14 07:17:58 2003 From: google_mail at aristoweb.net (Corey Lubin) Date: 14 Nov 2003 04:17:58 -0800 Subject: Overriding variables used by base classes Message-ID: [original.py] someGlobal=1 class Original: def foo(self): # Make use of someGlobal [/original.py] [tainted.py] from original import * someGlobal=2 class Tainted(Original): pass [/tainted.py] How might one make it such that Tainted.foo makes use of tainted.someGlobal, rather than original.someGlobal? Must I use eval/exec? Note that the point is that I don't want to have to duplicate the definition of foo. Corey From marco at analog.se Sun Nov 9 14:43:17 2003 From: marco at analog.se (Marco) Date: 9 Nov 2003 11:43:17 -0800 Subject: ANN: ruleCore - The event pattern detector engine Message-ID: <438a319a.0311091143.256db982@posting.google.com> I would hereby like to announce that ruleCore 1.0beta6 is available under the GPL license from www.rulecore.com ruleCore is an event-driven reactive rule engine with GUI tools, all written in Python. The ruleCore Engine accepts events with XML-RPC and detects complex patterns of events, called situations. A situation is defined by combining events with different kind of nodes, such as logical or timer nodes. For example, ruleCore can do things like: "Detect the situation, if it is not december, when event HOST_DOWN comes after event ROUTER_DOWN and event FAILOVER does not come within 10 minutes" When a situation is detected a condition can be evaluated on all the events that took part in the detection process. If the condition is true an action is executed, normally a script. The ruleCore Engine is written in completely in Python. The GUI tools are also in Python and uses Qt with the PyQt wrapper. Everything is tested on recent versions of SUSE and RedHat. The rpm contains *everything* needed to run ruleCore, so it should run on most Linux distributions. Portability to Windows and Mac is a goal, but not tested yet. But as everything is in Python it should run provided that all the required software is installed. Although this is left as an exercise to the interested reader. The ruleCore Engine is based on ideas from the research done on active rules called Event-Condition-Action (ECA) rules. Google on ECA-rules or check the references section on www.rulecore.com to learn more about this type of event-driven active rules. /Marco From peter at engcorp.com Tue Nov 4 08:06:23 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 04 Nov 2003 08:06:23 -0500 Subject: Does python always need to compile ENTIRE program before it c an start to run it??? References: Message-ID: <3FA7A44F.7EA084D@engcorp.com> "Daniel P. M. Silva" wrote: > > On Mon, 03 Nov 2003 18:34:33 -0500, Ellinghaus, Lance wrote: > > If I remember correctly, Yes. > > Python will import each module, compile if necessary, and then execute it. > > This might cause additional modules to be compiled, loaded, etc.. But Python > > will not import a module more than one time. Each additional time the import > > is called for the same module, Python just binds a new reference into the > > namespace. > > What about this? > > [/tmp] > cat > a.py > import b > print "module A loaded" > [/tmp] > cat > b.py > import a > print "module B loaded" > [/tmp] > python a.py > module A loaded > module B loaded > module A loaded Special case, with a circular reference involving the __main__ script. Basically the problem is that the script that is invoked from the command line is not imported in the usual fashion, but is executed as the module __main__ (check sys.modules to verify this if you wish). As a result, if an imported module such as B tries to import a module called A, this module is not found in sys.modules already so the importing proceeds again. If module B had used "import __main__" this would not have happened. Call this a small lesson in one of the problems circular references can cause. Easiest to avoid them. :-) -Peter From dfarning at localhost.localdomain Tue Nov 11 03:07:10 2003 From: dfarning at localhost.localdomain (david farning) Date: Tue, 11 Nov 2003 08:07:10 GMT Subject: importing module as filename References: Message-ID: Peter Otten wrote: > > How about a symlink to disambiguate the module names, > e. g. ln -s config.py yumconfig.py, and then > > import config, yumconfig > Thanks, great suggestions. I will talk to the upstream maintainers about 1. changing config to something a little less ambigous ;) 2. having them add the symlink 3 me adding the symlink (I wouldn't want to muck around their sandbox too much) > Somewhat more ambitious: convert the program directory into a package by > adding an __init__.py script and then > > import config, yum.config > > Peter Dave Farning From ma at Bell.com Wed Nov 19 23:38:37 2003 From: ma at Bell.com (xam) Date: Thu, 20 Nov 2003 04:38:37 GMT Subject: PIL and jpg -> png conversion, do I really need java for this??? References: Message-ID: sorry, Python Magic already has a python interface. My suggestion was Python-wrapping CxImage. There is a learning curve for boost.python (mostly installation/configuration) but once you get it writing a great type-safe interface is a sinch. max "Raaijmakers, Vincent (IndSys,GE Interlogix)" wrote in message news:mailman.913.1069296010.702.python-list at python.org... Thanks for the advise. This seems a good solution but.. I just can't install it on Linux (RH7.2) from the sources. In a nutshell: - I downloaded boost.python and PythonMagick. - compiled bjam, copied this file into the same folder where the PythonMagick/readme.txt file is at. - changed the paths in buildLinux tried to run buildLinux but it complains that it can not find "boost-build.jam" Now, I really tried to do my best to follow every readme file, but this time it didn't help me. What step did I miss here? Vincent -----Original Message----- From: python-list-bounces+vincent.raaijmakers=ge.com at python.org [mailto:python-list-bounces+vincent.raaijmakers=ge.com at python.org]On Behalf Of Achim Domma Sent: Wednesday, November 19, 2003 5:00 PM To: python-list at python.org Subject: Re: PIL and jpg -> png conversion, do I really need java for this??? Hi Vincent, after a lot of problems with our server, I just got the PythonMagick website up and running again. If PNGs generated from ImageMagick work, it might be of help to you. Just have a look: http://www.procoders.net/pythonmagick regards, Achim -- http://mail.python.org/mailman/listinfo/python-list From martin at v.loewis.de Sun Nov 23 15:13:49 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 23 Nov 2003 21:13:49 +0100 Subject: minidom nodes without a document? In-Reply-To: References: Message-ID: Magnus Lie Hetland wrote: > Is it possible to build a minidom tree bottom-up without access to a > document node? It seems that simply instantiating the various node > classes doesn't quite do the trick... No. In the DOM, all nodes always belong to a Document. They don't have to be part of a hiearchy, though - you can create unattached Element nodes with createElement[NS], and put them in a hierarchy as you like. Regards, Martin From http Mon Nov 10 11:42:53 2003 From: http (Paul Rubin) Date: 10 Nov 2003 08:42:53 -0800 Subject: pickle complexity limit? References: Message-ID: <7x4qxckwdu.fsf@ruckus.brouhaha.com> martin at v.loewis.de (Martin v. L?wis) writes: > Read the pickle code, understand why it is recursive, and implement an > alternative that isn't recursive, yet preserves the original semantics > in terms of pickling order and sequence in which methods are called on > objects. When you are done, please contribute your changes back, to > sf.net/projects/python. I wonder if it's feasible to write a pickler as a C extension that works something like a pointer-reversing garbage collector, eliminating the need for recursion and still not needing any extra storage in the objects. From tom_verbeure at hotmail.com Tue Nov 18 13:33:10 2003 From: tom_verbeure at hotmail.com (Tom Verbeure) Date: 18 Nov 2003 10:33:10 -0800 Subject: Unit Testing Examples References: Message-ID: Thanks all for your suggestions! Tom From duncan at NOSPAMrcp.co.uk Wed Nov 19 03:53:54 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 19 Nov 2003 08:53:54 +0000 (UTC) Subject: New Guy References: Message-ID: "nards_collective" wrote in news:mailman.865.1069224343.702.python-list at python.org: > Thanks for the advise gys, but I still can't decipher the problem. > Below is a copy of the entir progra, the erro is stil in the first > 'if' command. The problem is that you have indented the 'if' statements. You aren't allowed to indent code arbitrarily in Python. Indent inside blocks, but the first if statement doesn't start a new block, so it MUST be at exactly the same indentation level as the preceding print statement. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From mensanator at aol.compost Sat Nov 29 10:38:12 2003 From: mensanator at aol.compost (Mensanator) Date: 29 Nov 2003 15:38:12 GMT Subject: GMPY compare warning References: Message-ID: <20031129103812.12054.00000926@mb-m26.aol.com> >Subject: Re: GMPY compare warning >From: "Duncan Smith" buzzard at urubu.freeserve.co.uk >Date: 11/29/2003 8:50 AM Central Standard Time >Message-id: > > >"Mensanator" wrote in message >news:20031129001740.25982.00001230 at mb-m05.aol.com... >> In the program that follows, I get the following warning message: >> >> collatz_.py:37: RuntimeWarning: tp_compare didn't return -1, 0 or 1 >> while b>1: >> >> In this case, b is a gmpy.mpz number. The program operates as it should, >> which I guess is why it's a warning. Is there some reason why I shouldn't >> use gmpy numbers with relational operators? Is this warning something >> that can safely be ignored? >> > >http://sourceforge.net/tracker/index.php?func=detail&aid=472523&group_id=547 >0&atid=305470 > >might help? Thanks. > >Duncan -- Mensanator Ace of Clubs From peter at engcorp.com Fri Nov 21 16:10:25 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Nov 2003 16:10:25 -0500 Subject: Zipping and Unzipping files References: Message-ID: <3FBE7F41.172BEC4A@engcorp.com> Doug Tolton wrote: > > Is there a simple way to zip and unzip files? > > I'm looking for something along the lines of: > > zfile = zipfile(r'c:\somefile.zip') > zfile.extract(r'c:\somefiles') > > I've looked at the documentation for zlib and zipfile, and they seem > pretty comprehensive, but also extremely low level. If needed, I can > probably make a workable component from them, but I was wondering if > there is one already written that I'm just missing. Probably not, since it's likely to require slight differences in each application. Try this (untested): import os, zipfile def extract(self, todir=''): for name in self.namelist(): f = open(os.path.join(todir, name), 'wb') f.write(self.read(name)) f.close() zipfile.ZipFile.extract = extract Now you should be able to execute the two example lines you showed above... -Peter From aleax at aleax.it Sat Nov 1 17:19:39 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 01 Nov 2003 22:19:39 GMT Subject: dictionaries with nested lists References: Message-ID: <%jWob.395492$R32.13119558@news2.tin.it> ruari mactaggart wrote: > can i write >>>>dictionary[key][list][3] > > to mean the 3rd item in the list that is the corresponding value for 'key' > ? No, but you can write dictionary[key][2] for that purpose: -- that [list] notation is unneeded and unsupported, -- indices start from 0 so the 3rd one is indexed as [2] Alex From __peter__ at web.de Wed Nov 12 05:48:02 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 12 Nov 2003 11:48:02 +0100 Subject: trouble understanding None References: Message-ID: Jakle wrote: > I'm trying to write a program (with my very limited knowledge of python) > that will convert text I type into those letters drawn with ascii symbols. > I did 2 letters then went to test it. Here's the code I have so far: > [...] > WOW, that came out weird, but if you copy/paste it into idle it looks > fine. That an "S" and a "T". Anyways, The idea is to have a function for > each letter, then use a for loop and a ton of if statements to traverse > and print the letters/functions. I understand that I might be doing too > much work to do this, but I'm trying to practice what I am learning. OK, > the test prints the letters, but also prints "None" at the end of each > function. I don't understand it. I'm reading "How To Think Like A Computer > Scientist: Learning With Python", and it only has one little paragraph > about the "None" return value, and that's only regarding conditional > statements. If someone could throw some wisdom my way I'm be very > greatful. Thanks ahead of time. Never put print statements into functions that shall themselves produce a printable result Be aware that in order to get a single printable backslash, you have to put it twice into a string constant: >>> print "\\" \ For a learning experience it would probably be best to stick with your approach and just write S(); T(); S() instead of print S(), T(), S() The next step would then be to put the functions into a dictionary and look them up: d = {"S": S, "T": T} for c in "some string": d[c]() However, you did appeal to the "child in the man", so I put together some code that does what you want but didn't dare ask :-) I won't go into the details, but the concept is to store an entire line of text and translate it into the twelve partial lines of your ascii art charset. With print >> obj, "some string" you can redirect the output to any obj that provides a write(s) method. Peter import sys charset = { "S": [ " ________ ", " /--------\ ", "// \\\\", "|| ^^", "|| ", r"\\________ ", r" \--------\ ", " \\\\", " ||", "_ ||", r"\\________//", r" \--------/ ", ], "T": [ "______________", "------ ------", " || ", " || ", " || ", " || ", " || ", " || ", " || ", " || ", " || ", " || ", ], " ": [" "] * 12 } class Big: def __init__(self, charset=charset, height=None, write=None, defaultchar=" "): self.charset = charset if height is None: height = len(charset.itervalues().next()) self.height = height self.cache = [] self.defaultchar = charset[defaultchar] if write is None: write = sys.stdout.write self.rawWrite = write def _writeLine(self): line = [self.charset.get(c, self.defaultchar) for c in "".join(self.cache)] self.cache = [] for row in range(self.height): self.rawWrite("".join([c[row] for c in line])) self.rawWrite("\n") def write(self, s): while True: pos = s.find("\n") if pos == -1: break self.cache.append(s[:pos]) self._writeLine() s = s[pos+1:] self.cache.append(s) def close(self): self.write("\n") big = Big() print >> big, "ST", "TS" print >> big, "STS" print >> big, "S\nT\nS" print >> big, "TS", big.close() From max at alcyone.com Mon Nov 17 03:19:11 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 17 Nov 2003 00:19:11 -0800 Subject: True inconsistency in Python References: Message-ID: <3FB8847F.6CB1BECA@alcyone.com> Tim Roberts wrote: > Python is certainly not the only language in which this occurs. Many > are > the C programmers who have been burned by: > > int SomeFunction(); > ... > if( SomeFunction == TRUE ) > { > } I think you're getting burned by something else, there :-). > Visual Basic has exactly the same problem. It's not a problem, explicitly comparison with a Boolean literal, whether or not Booleans are not distinct types (Lisp, C89), are distinct types with implicit conversion (C++, Python), or are distinct types in which implicit conversions are disallowed (Java) is completely superfluous. The proper way to test whether an expression is true is if (expression) ... What is the point of the explicit test with the true constant? What about the result of _that_ comparison, shouldn't that be tested with true as well -- ((expression == TRUE) == TRUE)? But what about _that_ result, shouldn't it be tested too? Explicit comparison with the true constant (or false constant) necessarily degenerates into complete uselessness. > Further, until very > recently, > True in VB actually evaulated to -1, so even comparing to "1" would > fail. That's because in traditional BASIC, "true" is all-bits on. The true constant wasn't 1 in the first place. > >Assuming the old behavior is desired, programmers need to be careful > >not to compare a variable with True as in: > > > >if var == True: # only works if var is 1 > > blah > > Your statement is absolutely true. End of story. It's true in that that might cause a problem, but it's not true that that's undesirable language behavior. It's programmer error -- in any language that has a Boolean true (or false) literal. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ So little time, so little to do. -- Oscar Levant From stephenlee at exe-coll.ac.uk Mon Nov 10 04:24:54 2003 From: stephenlee at exe-coll.ac.uk (Steve Lee) Date: 10 Nov 2003 01:24:54 -0800 Subject: Request for simple a customisable Python editor References: <8cf2994e.0311070800.1f07f9c8@posting.google.com> Message-ID: <22107734.0311100124.2bdcf861@posting.google.com> .. PyPE (http://pype.sourceforge.net/) an editor written in > python with wxwindows. Thanks I missed that one, seems not to be actively maintained though. > CUTE Think I'll give QT a miss this time round > pyscinitilla Replaced by http://sra.itc.it/people/cavada/PyScintilla2.html. Again I'll give GKt a miss for now. Steve From joshway_without_spam at myway.com Fri Nov 14 15:40:03 2003 From: joshway_without_spam at myway.com (JCM) Date: Fri, 14 Nov 2003 20:40:03 +0000 (UTC) Subject: for what are for/while else clauses References: Message-ID: John Roth wrote: > "JCM" wrote in message > news:bp3bmg$l3$1 at fred.mathworks.com... >> John Roth wrote: >> ... >> > Yep. It's one of the three termination conditions for a loop. >> >> What are the three conditions? I know of two: >> >> 1 Reaching the end of the iteration >> 2 Breaking out > 3. Not executing at all. I see that as an example of #1. From vepxistqaosani at netscape.net Fri Nov 14 10:53:49 2003 From: vepxistqaosani at netscape.net (Vepxistqaosani) Date: Fri, 14 Nov 2003 15:53:49 GMT Subject: Python busting out Message-ID: At my firm -- which must remain anonymous, I guess -- I'm the only Pythoneer. We are strongly encouraged to use only "Approved Technologies". However, we are even more strongly encouraged to get the job done; when Python is obviously superior to the alternatives, I can use Python. For instance, our Approved Technology for database reporting is Cognos Impromptu. But a recent report I had to write in Cognos involved a 20-way self-join of a 90-column view (don't ask). This was not an ideal solution. Since the final format was an Excel file, I volunteered to do it in Python. Python can run the same report in 1/20 the time and do all the formatting via Excel VBA. They still want me to figure out how to do this with Cognos, but they're so happy with the Python solution, they've forgotten to pressure me on the issue. The end result is that other folks around the company are getting interested in Python. So who needs books when you can offer performance? From pedery at ifi.uio.no Tue Nov 18 12:08:04 2003 From: pedery at ifi.uio.no (Peder Ydalus) Date: Tue, 18 Nov 2003 18:08:04 +0100 Subject: win32com from linux and jpq question Message-ID: <3FBA51F4.EC6049B9@ifi.uio.no> 1) Anyone knows if it will be possible to e.g. read cells in an excel sheet from linux? If python compiled bytecode is cross-platform (I don't know), maybe it could add the necessary bits and bytes from win32com? 2) I do not have PIL or other imaging libraries installed. Using plain PhotoImage() and Label, is it possible to insert a jpg into an application? Thanks! - Peder - From pclinch at internet-glue.co.uk Mon Nov 10 17:47:28 2003 From: pclinch at internet-glue.co.uk (Paul Clinch) Date: 10 Nov 2003 14:47:28 -0800 Subject: Blocking readline() Call? References: Message-ID: <8cf2994e.0311101447.53ddaebe@posting.google.com> "Scott Brady Drummonds" wrote in message news:... > Hi, everyone, > > I'm just figuring Python out but have become stalled with the following > snippit of code: For some reason, the program stalls after the "read line: > x" for the last line. The 'done reading cycle map' message is never > generated: > > while 1: > line = file.readline() > if line == '': > continue Perhaps you meant break. > data = line.strip().split(':') > cycleMap[int(data[0])] = int(data[1]) > i = i + 1 > print ('read line %d' % i) > file.close() > print ('done reading cycle map') > > I thought readline() was supposed to be non-blocking. Have I misunderstood > something? > > Thanks, > Scott Regards, Paul Clinch From Kepes.Krisztian at peto.hu Mon Nov 24 05:20:23 2003 From: Kepes.Krisztian at peto.hu (Kepes Krisztian) Date: Mon, 24 Nov 2003 11:20:23 +0100 Subject: Dyna grid Message-ID: <17910121023.20031124112023@peto.hu> Szia ! A k?vetkez? a gondom: Adott egy wx form, ami alapot k?pez, egyfajta template. Ezt szeretn?m felhaszn?lni, ?s kieg?sz?teni ?gy, hogy a rajta l?v? grid-ek dinamikusan j?jjenek l?tre. Sajnos ezt nem siker?lt megcsin?lnom, az ?j komponens nem l?tsz?dik a formon, pedig show-val iratom ki. (teh?t: megjelenik a form, majd gombnyom?sra elk?sz?l(n?)nek a grid-ek). Pl. gombnyom?sra akarok egy ?j gridet: def OnClick2(self,event): g=wxGrid(self, -1) # new grid g.CreateGrid(10,10) g.Show(1) self.mainsizer.Add(g, 0, wxALL|wxEXPAND, 8) # I want to show #self.mainsizer.Fit(self) self.SetSizer(self.mainsizer) self.mainsizer.SetSizeHints() De nem jelenik meg. Mi?rt ? Egy m?sik k?rd?s: hogyan lehet egy grid-et t?r?lni, hogy ut?na megint j?hessen a creategrid ??? Egyenkk?nt kell t?r?lni, ?s hozz?adni a sorokat, oszlopokat ? El?re is k?szi: KK ---------------------------------------------- ?dv, Kepes Krisztian -> mailto:Kepes.Krisztian at peto.hu From martin at v.loewis.de Mon Nov 10 01:29:40 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 10 Nov 2003 07:29:40 +0100 Subject: pickle complexity limit? References: Message-ID: "Mark Hahn" writes: > I don't understand how this could happen with pickle. Isn't it supposed to > stop when it runs into an object it has already pickled? Yes, and it does. > Couldn't it have been coded in a stackless way? Yes, but it doesn't. Please look at save_inst implementation; it ends with save(stuff) write(BUILD) This is where the recursion happens. You run into the limit only if you can find a path through your object graph that does not visit the same object twice. > What do I do now? I don't want to recompile with a deeper stack as this > will obviously only help in limited cases, not solve the real problem. Read the pickle code, understand why it is recursive, and implement an alternative that isn't recursive, yet preserves the original semantics in terms of pickling order and sequence in which methods are called on objects. When you are done, please contribute your changes back, to sf.net/projects/python. Regards, Martin From mje_orlando at earthlink.net Sat Nov 15 14:31:02 2003 From: mje_orlando at earthlink.net (Jay Eichelberger) Date: Sat, 15 Nov 2003 19:31:02 GMT Subject: Matlab, GUIs and Cygwin Message-ID: Greetings. I am using Python under Cygwin. I'm trying to do some statistical charts. The Matlab looked likely, but it uses GTK. Does anyone know if Cygwin limits me to TCL/tk, X11? I've done motif before on Unix, but I'm new to Python/cygwin/windows. Any suggestions? Should I go the route that 'renders' in a jpg file that be included in html?? Thanks, Jay From news at u-schramme.de Thu Nov 13 06:12:42 2003 From: news at u-schramme.de (Ulrich Schramme) Date: Thu, 13 Nov 2003 12:12:42 +0100 Subject: Palindrome In-Reply-To: References: <20031112223135.29045.00000109@mb-m12.aol.com> Message-ID: Georgy Pruss wrote: > I know what is a palindrome, but I can make up dozen things > the program could do with the palindrom. > G-: > I?m sorry, but it seems that I misunderstood your previous posting. -- -- Ulli www.u-schramme.de From pxtl at hotmail.com Tue Nov 25 23:25:34 2003 From: pxtl at hotmail.com (martin z) Date: Wed, 26 Nov 2003 04:25:34 GMT Subject: Creating a Python installer in win32 Message-ID: <2XVwb.40137$Fv8.32356@twister01.bloor.is.net.cable.rogers.com> Hey, all. I'll get to the point: project for class, got most of my needs figured out, just unsure about one detail: this is a large-scale design course, so it has to be a complete win32 app. That means a standalone installer. I can't just say "go fetch Python, then run this .py file". Anybody know how to set such a thing up? From aleax at aleax.it Thu Nov 6 17:06:37 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 06 Nov 2003 22:06:37 GMT Subject: PEP 289: universal and existential operators References: Message-ID: Delaney, Timothy C (Timothy) wrote: >> From: Alex Martelli [mailto:aleax at aleax.it] > > [lots of good stuff] > >> and if it comes to the comparison after the implied and, the >> itemsiterator is exhausted by that time. So, maybe, it _is_ >> for the better that the apparently popular preference for 'all' >> to mean 'alltrue' stops us from having 'all' work like in SQL >> instead - it does save us from potentially non-obvious behavior >> when both comparison chaining and iterators-as-opposed-to- >> iterables are simultaneously involved. > > I *love* watching people's thought processes in action :) It's more a case of "besides, those grapes weren't ripe" -- trying to rationalize/console myself that we won't get that cool SQLish 'all' -- in fact, it would suffice to keep track of whether more than one comparison is invoked (to restart iteration on an iterable, raise an appropriate ValueError on an iterator) to track all _practical_ cases, i.e., excepting perverse uses such as: if x > all(foos) < y : which DESERVE to fail nonobviously...!-) Alex From deets_noospaam at web.de Sun Nov 23 14:54:10 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Sun, 23 Nov 2003 20:54:10 +0100 Subject: python xml dom help please References: Message-ID: Mikl?s wrote: > Without having any thorough look at your (recursive)'deepen' function, I > can see there's no termination condition for the recursion.... > So that's one reason this won't work the way you want it to. Nope - he has a termination condition. deepen is called for all childNodes, so he makes a traversal of all nodes. Regards, Diez From pmaupin at speakeasy.net Tue Nov 11 21:26:39 2003 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 11 Nov 2003 18:26:39 -0800 Subject: Conversion of 24bit binary to int References: Message-ID: <653b7547.0311111826.608ae618@posting.google.com> Idar wrote: > Is there an effecient/fast way in python to convert binary data from file > (24bit hex(int) big endian) to 32bit int (little endian)? Have seen > struct.unpack, but I am unsure how and what Python has to offer. Idar As Peter mentions, you haven't _really_ given enough information about what you need, but here is some code which will do what I _think_ you said you want... This code assumes that you have a string (named teststr here) in the source format you describe. You can get a string like this in several ways, e.g. by reading from a file object. This code then swaps every 3 characters and inserts a null byte between every group of three characters. The result is in a list, which can easily be converted back to a string by ''.join() as shown in the test printout. I would expect that either the array module or Numpy would work faster with _exactly_ the same technique, but I'm not bored enough to check that out right now. If this isn't fast enough after using array or NumPy (or after Alex, Tim, et al. get through with it), I would highly recommend Pyrex -- you can do exactly the same sorts of coercions you were doing in your C++ code. teststr = ''.join([chr(i) for i in range(128,128+20*3)]) result = len(teststr) * 4 // 3 * [chr(0)] for x in range(3): result[2-x::4] = teststr[x::3] print repr(''.join(result)) Regards, Pat From duncan at NOSPAMrcp.co.uk Thu Nov 27 06:42:42 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 27 Nov 2003 11:42:42 +0000 (UTC) Subject: Java final vs Py __del__ References: Message-ID: Kepes Krisztian wrote in news:mailman.1133.1069928021.702.python-list at python.org: > In the Py the __del__ is same java's final, or it is to be called in > every way by GC ? There is more than one implementation of Python. In C Python, __del__ will be called as soon as there are no more references to the object, but the Java implementation of Python will never call __del__ until the object is garbage collected. Even in removing the last reference to an object, which causes __del__ to be called can happen in a slightly suprising way. Usually a variable going out of scope would be sufficient to release the object it referred to (assuming of course there are no other references to the same object), but if a function throws an exception, the objects referenced by the local variable will have their lifetimes extended, typically until the next time an exception is thrown (which probably happens in a completely unrelated function). The garbage collector can also cause objects to be released by collecting the objects which kept them alive, but if an object that participates directly in a cycle has a __del__ method then it will never be garbage collected, so its __del__ will never be called. When Python exits, it does its best to ensure that all objects are released in an orderly manner, but sometimes that just isn't possible. So some objects may not get their __del__ methods called on program exit, and other objects may find that when __del__ is called, there are no other objects around for them to reference. > > I build this method as safe method: if the programmer don't do any > closing/freeing thing, I do that ? No, this won't work reliably. If you want to do this, look at the atexit function. > > simple example: > > class a: > def __init__(self,filename): > self.__filename=filename > self.__data=[] > self.__file=None > def open(self): > self.__file=open(self.__filename,"w") > def write(self,data): > self.__data.append(data) > def close(self): > self.__file.writelines(self.__data) > self.__file.close() > self.__file=None > def __del__(self): > if self.__file<>None: > self.close() > # like destructor: we do the things are forgotten by > programmer > > Thanx for infos: > What I would suggest you do here, is something like (this is untested code, so it may have errors): import weakref import atexit ObjectsToClose = weakref.WeakValueDictionary() def CloseObjects(): try: while true: key, o = ObjectsToClose.popitem() o.close() except: pass atexit.register(CloseObjects) class a: def __init__(self,filename): self.__filename=filename self.__data=[] self.__file=None ObjectsToClose[id(self)] = self ... rest of class a goes here ... This code will ensure that the close method gets called on each of your objects when the program exits (unless you are running on Windows and the user uses control+break to kill the program --- if you are then you'll need some additional code to ensure that atexit gets called correctly). The WeakValueDictionary will automatically remove from itself any objects which are destroyed before the program closes. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From tzot at sil-tec.gr Wed Nov 5 09:30:28 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 05 Nov 2003 16:30:28 +0200 Subject: Please explain the meaning of 'stealing' a ref References: <7h3wuagiagy.fsf@pc150.maths.bris.ac.uk> Message-ID: On Tue, 04 Nov 2003 14:20:18 GMT, rumours say that Alex Martelli might have written: I want to clarify that all the questions in my first post and in this post are intended to help me understand the notions of "stealing a reference", "borrowing a reference" because I found api/refcountDetails.html a little unsatisfying. [snip: my referring to ext/refcountsInPython.html and supposing that an incref should be issued before calling a function "stealing" a reference] >Yes, you have to incref IF you want to keep owning that reference. So, "owning a reference" means simply that some code did an incref and is responsible to decref, right? This is my first request for clarification, although I understand that so far I was confusing "owning a reference" and "owning an object". >> decref afterwards yourself. What's the reason? Efficiency for > >You'll decref when you don't want to own that reference any more, >and you incref'd it, but if you do that soon, why bother incref'ing?-) I'd do that because I did not understand what "stealing a reference" means; therefore I translated "stealing" = decref, so I presumed that I should issue an incref in advance in order to make sure the object passed to the function does not cease to exist before the function returns. I assumed based on unclear (to me) terms. >The typical use case to explain the stealing is in the "Reference >Count Details" section of the API manual: > >PyObject *t; > >t = PyTuple_New(3); >PyTuple_SetItem(t, 0, PyInt_FromLong(1L)); >PyTuple_SetItem(t, 1, PyInt_FromLong(2L)); >PyTuple_SetItem(t, 2, PyString_FromString("three")); > >PyTuple_SetItem is very often called with a completely new reference >as its 3d argument, so it steals it to enable this easy idiom... w/o >the stealing you'd have to code, e.g.: > >PyObject *t; >PyObject *temp; > >t = PyTuple_New(3); > >temp = PyInt_FromLong(1L); >PyTuple_SetItem(t, 0, temp); >Py_DECREF(temp); > >etc -- much less handy. I understand that. So, a function "stealing" a reference means the function takes away from the caller the responsibility for decref'ing the object, and "stealing a reference" does not translate into some C code, right? This is my second request for clarification. >> simplicity of the function? If yes, why not enclose the function call >> in a incref / decref cycle and then export the enclosing function in the >> API? > >I don't know what you're talking about. Explain please? E.g. with one >of the few reference-stealing functions, PyTuple_SetItem ? You don't know what I'm talking about because neither I was sure what I was talking about; I now see I should not make assumptions since I was not sure as to what "stealing a ref" means. It was confusing to the readers of my post. >> Such stuff I wanted to know. >> >> Also, "borrowing" and "stealing" are the same thing? I just think that > >No! You get a borrowed reference when you get a reference but are not >transferred the ownership of it. That's a pretty widespread use regarding >references that are returned to objects that surely pre-existed. You >must then incref in the relatively rare case you want to keep hold of >that reference for the longer term. So a function "borrowing" a reference means that the function does not incref or decref an object which was passed to it, right? That is the third request. I assume that most functions of the python API "borrow" references? >> "beautifying" terminology at the C level is more confusing than helpful. > >What 'beautifying'...? "Beautifying" in the sense that I thought that both "stealing" and "borrowing" a reference translate into actual C code, a mistaken assumption. Thanks for your time. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From noemail at noemail4u.com Fri Nov 14 14:17:52 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Fri, 14 Nov 2003 19:17:52 GMT Subject: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <8hfsb.7707$nz.895@newsread2.news.pas.earthlink.net> Message-ID: <7b3711d05b0f4fd3661f95ed13d4e055@news.teranews.com> On Fri, 14 Nov 2003 18:07:44 GMT, Dang Griffith wrote: >On Wed, 12 Nov 2003 13:19:15 -0500, Douglas Alan >wrote: > >>I would say that if you didn't get introduced to at least the concept >>of functional programming and a hint of how it works, then something >>was seriously wrong with your CS education. >>|>oug > >I've been lurking this thread for a while, but missed the beginning. >Can I ask where you got your CS education (school and year)? >From the conversation, it seems that right or wrong, your education >exceeds those in this group. Where should I send my children >such that they receive a better CS education that I? > --dang Nevermind--I saw more posts and summarily reached a conclusion, reducing the alternatives to one. --dang From eric.brunel at pragmadev.N0SP4M.com Mon Nov 3 07:05:21 2003 From: eric.brunel at pragmadev.N0SP4M.com (Eric Brunel) Date: Mon, 03 Nov 2003 13:05:21 +0100 Subject: Textbox with ScrollBar References: Message-ID: PythonRAD wrote: > Hi at all, > > I looking for the widget that admit the multiline with scrollbar for > Tkinter... any idea? > > Help me please > Michelangelo > See widget ScrolledText in Pmw: http://pmw.sourceforge.net/doc/index.html HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From gerrit at nl.linux.org Sun Nov 30 09:23:54 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 30 Nov 2003 15:23:54 +0100 Subject: Bug in glob.glob for files w/o extentions in Windows In-Reply-To: References: Message-ID: <20031130142354.GA24127@nl.linux.org> Francis Avila wrote: > Behold the awesome visage of the One True Glob (TM): (Not that I'm starting > a holy war or anything ;) > *.* -> Filename has a dot in it, and that dot cannot be the first or last > char. > This is NOT the same as '*'!! > .* -> Filename has a dot as the first character. > *. -> Filename has a dot as the last character. > * -> Gimme everything. Note that Bash doesn't behave like this either: * does not give everything, rather it gives everything not starting with a dot. In Bash, * really means: [!.]* yours, Gerrit. -- 102. If a merchant entrust money to an agent (broker) for some investment, and the broker suffer a loss in the place to which he goes, he shall make good the capital to the merchant. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From __peter__ at web.de Fri Nov 14 03:19:26 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Nov 2003 09:19:26 +0100 Subject: logging.shutdown() ValueError: I/O operation on closed file References: Message-ID: j vickroy wrote: > As a follow-up question, why is a handle object not removed from > logging._handlers when its (i.e., handle) close() procedure is applied? > > That behavior appears to be responsible for the logging.shutdown() > failure. Seems that the author did not consider the use case of consecutively using different handlers operating on the same file set - I've not yet made up my mind, if you are misusing the logging system or if that's a bug. Anyway, as of 2.3.2 the package has still __status__ = "beta", so patches might be welcome. Peter From john at rygannon.com Mon Nov 3 14:03:42 2003 From: john at rygannon.com (John Dean) Date: Mon, 3 Nov 2003 19:03:42 GMT Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0310312008.ce341ea@posting.google.com> <87r80sdyb1.fsf@pobox.com> <7xn0bg6njb.fsf@ruckus.brouhaha.com> <7x7k2jpti9.fsf@ruckus.brouhaha.com> Message-ID: <3fa6a66a$0$12690$fa0fcedb@lovejoy.zen.co.uk> Here are some facts which I can back up with copies of email sent to the team by Shawn Gordon 1. I worked for TKC for a little over 2 years 2. The first 2 months I recieved not a single cent in payment 3. The 3 month I was paid the equivalent of one weeks pay 4. I never once in two received a full months money 5. In June we were all told to find alternative employment until TKC gets back in it feet again 6. My last pay month was May 2003 Both Mike and I are willing to write off TKC debt if Shawn agrees to allow us to release Rekall under the GPL. -- Best Regards John From talon2lm at yahoo.com Sat Nov 8 20:59:36 2003 From: talon2lm at yahoo.com (Rob) Date: Sat, 8 Nov 2003 18:59:36 -0700 Subject: Newbie question 2 References: Message-ID: Here's the code, I don't think my attachment made it.. import shelve import string UNKNOWN = 0 HOME = 1 WORK = 2 FAX = 3 CELL = 4 class phoneentry: def __init__(self, name = 'Unknown', number = 'Unknown', type = UNKNOWN): self.name = name self.number = number self.type = type # create string representation def __repr__(self): return('%s:%d' % ( self.name, self.type )) # fuzzy compare or two items def __cmp__(self, that): this = string.lower(str(self)) that = string.lower(that) if string.find(this, that) >= 0: return(0) return(cmp(this, that)) def showtype(self): if self.type == UNKNOWN: return('Unknown') if self.type == HOME: return('Home') if self.type == WORK: return('Work') if self.type == FAX: return('Fax') if self.type == CELL: return('Cellular') class phonedb: def __init__(self, dbname = 'C:/phonedata'): self.dbname = dbname; self.shelve = shelve.open(self.dbname); def __del__(self): self.shelve.close() self.shelve = None def add(self, name, number, type = HOME): e = phoneentry(name, number, type) self.shelve[str(e)] = e def lookup(self, string): list = [] for key in self.shelve.keys(): e = self.shelve[key] if cmp(e, string) == 0: list.append(e) return(list) def dele(name,ptype): e = shelve.open('C:/phonedata') print e f = name + ':' + ptype print try: del e[str(f)] e.close() print 'Entry deleted.' except (NameError): print 'No Entries with '+ptype+' exist!' b = 1 foo = phonedb() while b != 4: print print "Welcome to the Phone Database" print "Please choose from the following" print print "If you would like to display Phone Number(s) select 1" print print "If you would like to add an entry select 2" print print "If you would like to delete for an entry select 3" print print "To quit select 4 " b = input(':') if b == 1: print 'Enter the lookup up key to find (For example for all names with ''Rob'' in them type Rob)' print a = raw_input(':') for entry in foo.lookup(a): print '%-40s %s (%s)' % ( entry.name, entry.number, entry.showtype() ) print if b == 2: print "Please enter the full name: (Example: John Smith)" n = raw_input(':') print "Please enter the phone number: (Example: 970-432-5432)" p = raw_input(':') print "Please enter the phone type: (0 = Unkown, 1 = Home, 2 = Work, 3 = Fax, 4 = Cell)" t = raw_input(':') if t == '0': foo.add(n, p, UNKNOWN) if t == '1': foo.add(n, p, HOME) if t == '2': foo.add(n, p, WORK) if t == '3': foo.add(n, p, FAX) if t == '4': foo.add(n, p, CELL) if b == 3: print "Enter the name of the entry to delete" dn = raw_input(':') print "Enter the phone type: (0 = Unkown, 1 = Home, 2 = Work, 3 = Fax, 4 = Cell)" dp = raw_input(':') dele(dn,dp) "Rob" wrote in message news:Bf6dnT_Ctq5FCTCiRVn-hA at comcast.com... > Ok, my two problems for this program that I can't seem to get are... > > 1)Why won't the program let me delete an entry after just entering it? If I > run the program, add an entry then quit, then restart the program it will > let me delete it. Otherwise it won't see it...Am I missing something??? > > 2)In the dele function I'm trying to add exceptions. The problem is if I try > to delete an entry that doesn't exist it will give me this error: > > Traceback (most recent call last): > File "C:\Python23\phone.py", line 118, in -toplevel- > dele(dn,dp) > File "C:\Python23\phone.py", line 67, in dele > del e[str(f)] > File "C:\Python23\lib\shelve.py", line 133, in __delitem__ > del self.dict[key] > File "C:\Python23\lib\bsddb\__init__.py", line 94, in __delitem__ > del self.db[key] > DBNotFoundError: (-30991, 'DB_NOTFOUND: No matching key/data pair found') > > Ok great...so I try to add the DBNotFoundError in my Except() only it tells > me: > > Traceback (most recent call last): > File "C:\Python23\phone.py", line 118, in -toplevel- > dele(dn,dp) > File "C:\Python23\phone.py", line 70, in dele > except (DBNotFoundError, NameError): > NameError: global name 'DBNotFoundError' is not defined > > How can it give me an error and then not allow me to enter that error in my > Except()? > > Thanks for your help! > > > From martin at v.loewis.de Wed Nov 26 00:42:30 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 26 Nov 2003 06:42:30 +0100 Subject: Compiling 64 bit python - using wrong stdlibc++ References: <1069813229.180239@cousin.sw.oz.au> <1069813707.78669@cousin.sw.oz.au> <1069818722.69623@cousin.sw.oz.au> Message-ID: "John Ky" writes: > The solution can't be to change this environment variable right? If it helps, why not? > How do you run 32-bit and 64-bit python side by side? Running them side-by-side is possible by giving different --prefix options to configure. However, that is not your problem: you have problems *building* them side-by-side. I recommend that you don't compile Python with a C++ compiler, i.e. by giving --without-cxx to configure. Then the problem of linking libstdc++ goes away. Regards, Martin From eppstein at ics.uci.edu Mon Nov 10 11:08:59 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 10 Nov 2003 08:08:59 -0800 Subject: Undo class References: Message-ID: In article , Eric Brunel wrote: > > I'm developing a tool in Tkinter and would like to add Undo and Redo > > commands to my Edit menu. Does somebody know if anybody has implemented > > standard Undo/Redo as a Python module? I could not find any info with > > Google on the matter. > > On what king of widget? If it's a Text, you can use the native tk undo/redo > features: create the Text widget with the option undo set to 1, then use the > methods edit_undo() and edit_redo(). These are tk 8.4 features, so it may not > work for Python versions older than 2.3 (it doesn't work with 2.1; don't know > about 2.2) > > For other widgets, I doubt there can be a generic mechanism to manage the > undo/redo functions for you: after all, only you can tell what actions should > be > able to be undone or redone. But I'd be really happy if someone can prove me > wrong! The "only you can tell" argument is not convincing -- if you can tell, you can tell it to the undo manager. Take a look at the Cocoa UndoManager functionality. Basically, while you're handle a change to a UI object, you call U = undoManager.prepareWithInvocationTarget(self) U.methods(arguments...) where self.methods(arguments...) would be the calls you'd do to reverse the change, and it saves the method names and arguments for you. Later, when an undo is requested, it performs the calls you prototyped for it. Very convenient, shouldn't be too hard to program in Python directly (in fact it is available in Python on OS X now, via PyObj). -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From francisgavila at yahoo.com Thu Nov 27 02:00:31 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Thu, 27 Nov 2003 02:00:31 -0500 Subject: Some csv oddities Message-ID: Three things that seem odd with csv: Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import csv >>> class unix(csv.Dialect): ... delimiter = ':' ... escapechar = '\\' ... lineterminator = '\n' ... quoting = csv.QUOTE_NONE ... skipinitialspace = False ... >>> csv.register_dialect('unix', unix) Traceback (most recent call last): File "", line 1, in ? File "D:\PYTHON23\lib\csv.py", line 39, in __init__ raise Error, "Dialect did not validate: %s" % ", ".join(errors) _csv.Error: Dialect did not validate: doublequote parameter must be True or False Now, it seems to me that QUOTE_NONE makes doublequote meaningless, because there's no quote character. And csv.writer doesn't write the quotechar escaped--using the above dialect, cw.writerow(['1', '"', '3']) will write the raw bytes '1:":3\n'. However, the corresponding csv.reader chokes on those bytes. Untested patch (csv.py, line 64): if self.doublequote not in (True, False): - errors.append("doublequote parameter must be True or False") + if self.quoting != QUOTE_NONE: + errors.append("doublequote parameter must be True or False") Moving on... I also can't seem to use my own registered dialects: >>> class unix(csv.Dialect): ... delimiter = ':' ... escapechar = '\\' ... lineterminator = '\n' ... quoting = csv.QUOTE_NONE ... skipinitialspace = False ... doublequote = False #Fine ... >>> csv.register_dialect('unix', unix) >>> csv.list_dialects() #Worked ['excel-tab', 'excel', 'unix'] >>> fp = file('csvtest', 'wb') >>> csv.writer(fp, 'unix') #csv.reader fails too, same error Traceback (most recent call last): File "", line 1, in ? TypeError: bad argument type for built-in operation >>> ud = vars(unix) >>> csv.writer(fp, **ud) Traceback (most recent call last): File "", line 1, in ? AttributeError: '_csv.Dialect' object has no attribute '__module__' >>> del ud['__module__'] >>> del ud['__doc__'] >>> cw = csv.writer(fp, **ud) #if **ud works, why not 'unix'? Third issue was mentioned above: csv.reader chokes on quotechar, even if ignored. >>> cw.writerow('1 : 3'.split()) >>> cw.writerow('1 " 3'.split()) >>> del cw >>> fp.flush() >>> fp.close() >>> fp = file('csvtest', 'rb') >>> fp.read() # Looks good '1:\\::3\n1:":3\n' >>> fp.seek(0) >>> cr = csv.reader(fp, **ud) >>> cr.next() ['1', ':', '3'] >>> cr.next() Traceback (most recent call last): File "", line 1, in ? _csv.Error: newline inside string My guess is that it's trying to grab a string delimited by ", and hits the newline before getting a matching ": >>> import StringIO >>> fp = StringIO.StringIO() >>> cw = csv.writer(fp, **ud) >>> cr = csv.reader(fp, **ud) >>> cw.writerow('1 " 3 " 5'.split()) >>> fp.buflist ['1:":3:":5\n'] >>> cr.next() ['1', ':3:', '5'] This should be ['1', '"', '3', '"', '5']. One might just set quotechar=None for this dialect, but this raises: >>> cr = csv.reader(fp, quotechar=None) Traceback (most recent call last): File "", line 1, in ? TypeError: bad argument type for built-in operation >>> This is contrary to PEP 305's specs: quotechar specifies a one-character string to use as the quoting character. It defaults to '"'. Setting this to None has the same effect as setting quoting to csv.QUOTE_NONE. So it seems that it is impossible for csv.reader to parse dialects which don't use quoting. -- Francis Avila From davidb at mcs.st-and.ac.uk Thu Nov 20 21:04:16 2003 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 20 Nov 2003 18:04:16 -0800 Subject: Analyse of PDF (or EPS?) References: <3fbcc67e$0$9836$edfadb0f@dread14.news.tele.dk> Message-ID: <4de76ee2.0311201804.42d0c086@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message news:... > On Thu, 20 Nov 2003 14:48:52 +0100, Johan Holst Nielsen wrote: > >Is there any Python packages to analyse or get some information out of > >an PDF document... > > > >Like where the text are placed - what text are placed - fonts, embedded > >PDFs/fonts/images etc. It depends on the type of images (bitmap vs. vector). > IIRC you can get the full specs of pdf and eps at the adobe site. The full PDF specification is not exactly short, but it's fairly readable. > Some stuff is easy to get at, some may be compressed and/or encrypted, > and not so easy. Although the FlateDecode compression format is straightforward with existing libraries, some of the other compression techniques may be less accessible. > Conforming docs are supposed to be structured so that it is relatively easy > to grab chunks of document and do the kinds of things printing business s/w does, > like rotating and scaling and reordering pages, etc. I have a Python library which is able to identify a lot of the structure in simple documents, including basic text extraction, but I've become pretty disillusioned with it because so much work is required to extract more complex information. Maybe it's time to stick a license on it and upload it somewhere. David From matt at pollenation.net Thu Nov 27 04:04:28 2003 From: matt at pollenation.net (Matt Goodall) Date: Thu, 27 Nov 2003 09:04:28 +0000 Subject: Simple instructions on how to programmatically download an image from a web page? In-Reply-To: References: Message-ID: <3FC5BE1C.2020609@pollenation.net> Y2KYZFR1 wrote: >I have search the group and not found a working example on how to >simply download a .gif from a url. > > I guess you didn't think to search the documentation too ;-). >something as simple as >http://groups.google.com/images/threadview_logo.gif should be pretty >easy, guess not? > > >>> import urllib >>> data = urllib.urlopen(imageUrl).read() Cheers, Matt -- Matt Goodall, Pollenation Internet Ltd w: http://www.pollenation.net e: matt at pollenation.net From sac at noreply.com Tue Nov 18 13:22:09 2003 From: sac at noreply.com (Sac) Date: Tue, 18 Nov 2003 10:22:09 -0800 Subject: good ways to convert string into time References: <731fc603.0311180958.32135957@posting.google.com> Message-ID: Hank wrote: > hi, > > i have a string as follows > > 18Nov2003:18:23:43:405 > > Is there an easy way to convert that to absolute time? What i really > want to do is to parse these times from a log file and do time > comparisons, averages, stop minus start (elapsed). > > Probably create my own conversion table i guess? > > thanks Hank, A source that may be of interest to you is "Text Processing in Python" by Dr. David Mertz. Excellent reference. From edreamleo at charter.net Sat Nov 8 11:18:28 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Sat, 8 Nov 2003 10:18:28 -0600 Subject: Leo + Python: the ultimate scripting tool #3 References: Message-ID: Reasons why Leo and Python work so well together: 3. Scripts may use the structure of Leo's outlines. This is a first "big" reason why the combination of Python & Leo is spectacular. As shown in the example above, scripts may get access to the headline or body text of any node in a Leo outline. Therefore, scripts may use the _structure_ of the outline to gain access to a) other scripts, b) fragments of code for exec or eval or c) other data. It gets better... Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From frr at easyjob.net Thu Nov 13 06:27:03 2003 From: frr at easyjob.net (Fernando Rodriguez) Date: Thu, 13 Nov 2003 12:27:03 +0100 Subject: Trouble with metaclass Message-ID: Hi, I'm having trouble with a metaclass suposed to check the method signature of its classes. Here's the metaclass: class MetaChecker(type): def __new__(cls, name, bases, attribs): for name, value in attribs.iteritems(): if inspect.ismethod(value): if not isSingleArg(value): raise "%s is not a thunk method!"%name return type.__new__(cls, name, bases, attribs) def isSingleArg(fn): args = inspect.getargspec(fn)[0] if len(args) == 1: return 1 else: return None And here's a class with this metaclass: class Preconditions (object): __metaclass__ = MetaChecker If I define a descendant of Preprocesor with a method with 2 arguments, I don't get any error: class P (Preprocessor): def f(self, x): return x What am I doing wrong? O:-) From pmaupin at speakeasy.net Tue Nov 18 21:10:02 2003 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 18 Nov 2003 18:10:02 -0800 Subject: Reading a Bitstream References: Message-ID: <653b7547.0311181810.786118af@posting.google.com> Dietrich Epp wrote: > Are there any good modules for reading a bitstream? Specifically, I > have a string and I want to be able to get the next N bits as an > integer. Right now I'm using struct.unpack and bit operations, it's a > bit kludgy but it gets the right results. As Miki wrote, the array module will probably give you what you want more easily than struct.unpack. If you need more help, just post a few more details and I will post a code snippet. (As to the rest of Miki's post, I'm not sure that I really want to know what an "Upnacker" is :) Pat From aleax at aleax.it Thu Nov 13 11:33:01 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Nov 2003 16:33:01 GMT Subject: Try, except...retry? References: Message-ID: <1nOsb.16429$9_.587471@news1.tin.it> Robert Brewer wrote: ... > into cases like: > > try: > aPiranha = allPiranhas['Doug'] > except KeyError: > aPiranha = Pirhana() > allPiranhas['Doug'] = aPiranha > aPiranha.weapon = u'satire' Yeah, it IS frequent enough that Python has two well-known idioms to deal with it. If a call to Piranha() has very low cost, allPiranhas.setdefault('Doug', Piranha()).weapon = u'satire' is very compact. If calling Piranha() is potentially costly, this is unfortunately no good (due to Python's "strict" execution order, all arguments are evaluated before running the method), so: if 'Doug' not in allPiranhas: allPiranhas['Doug'] = Piranha() allPiranhas['Doug'].weapon = u'satire' or, to avoid indexing twice: aPiranha = allPiranhas.get('Doug') if aPiranha is None: aPiranha = allPiranhas['Doug'] = Piranha() aPiranha.weapon = u'satire' In retrospect, it WOULD perhaps be better if setdefault was designed to take a callable (and optional args for it) and only call it if and when needed -- that would add a little speed and clarity in the two most typical use cases, currently: dictOfDicts.setdefault(mainKey, {})[secondaryKey] = value and dictOfLists.setdefault(key, []).append(value) which would just become: dictOfDicts.setdefault(mainKey, dict)[secondaryKey] = value and dictOfLists.setdefault(key, list).append(value) respectively; and widen the applicability of .setdefault to other cases, while costing very little actual use cases (I've never seen setdefault correctly called with a 2nd argument that wasn't (), {}, or the like). Ah well, too late, just musing aloud. Still, it seems to me that the existing idioms are nevertheless superior to your desideratum: > which would, in my opinion, be better written (i.e. *clearer*) as: > > try: > allPiranhas['Doug'].weapon = u'satire' > except KeyError: > allPiranhas['Doug'] = Pirhana() > retry which does index twice anyway. > Of course, there are other ways of doing it currently, most notably with > 1) a while loop and a retry flag, or 2) just repeating the assignment: > > try: > allPiranhas['Doug'].weapon = u'satire' > except KeyError: > allPiranhas['Doug'] = Pirhana() > allPiranhas['Doug'].weapon = u'satire' > > Yuck to both. Yes, flags (hiding control flow in data!) and repeated code do suck, but you need neither to get exactly the same semantics as your desideratum: while True: try: allPiranhas['Doug'].weapon = u'satire' except KeyError: allPiranhas['Doug'] = Pirhana() else: break > Current docs, 4.2 Exceptions says, "Python uses the ``termination'' > model of error handling: an exception handler can find out what happened > and continue execution at an outer level, but it cannot repair the cause > of the error and retry the failing operation (except by re-entering the > offending piece of code from the top)." I'm proposing that 'retry' does > exactly that: reenter the offending piece of code from the top. Given > the aforementioned pressure to reduce try: blocks to one line, this > could become a more viable/common technique. It does not appear to me that, even assuming that this looping is in fact the best general approach, there is enough advantage to your proposed "try/except ... retry" technique, with respect to the "while/try/except/else: break" one that is already possible today. I could be wrong, of course: there is nothing that appears to me to be "outrageously nonPythonic" in your proposal -- it just seems that new statements need to be more of a win than this in order to stand a chance. But a PEP on this is surely warranted, if you want to try one. > Apparently Ruby has this option? Gotta keep up with the Joneses. :) I'm Yes, Ruby does allow retry in a begin/rescue/else/end construct (on the rescue leg only). I don't think the use case in the "Programming Ruby" book shows it in a good light _at all_, though -- and I quote: """ @esmtp = true begin # First try an extended login. If it fails because the # server doesn't support it, fall back to a normal login if @esmtp then @command.ehlo(helodom) else @command.helo(helodom) end rescue ProtocolError if @esmtp then @esmtp = false retry else raise end end """ Eep!-) The dreaded "flag", AND a rather intricated structure too...!!! It seems to me that a much clearer way is (Python-ish syntax, same semantics): try: self.command.ehlo(helodom) except ProtocolError: self.command.helo(helodom) self.smpt = False else: self.smpt = True (this leaves the self.smpt flag unset if the ProtocolError exception propagates, rather than ensuring it's false in that case, but if [unlikely...] this gave any problem, then just moving the "self.smpt = False" to the top would fix that:-). Admittedly the use of else IS "a bit precious" here, since assigning to self.smpt is VERY unlikely to raise a ProtocolError, so, maybe, try: self.command.ehlo(helodom) self.smpt = True except ProtocolError: self.command.helo(helodom) self.smpt = False would also be OK. I just try to foster the HABIT of using try/except/else to avoid "protecting", with an except, ANY more code than strictly necessary, on general principles. But in this case the else-less form has a very pleasing symmetry so I would nod it through during a code-inspection or the like:-). But the point is, the existence of retry has tempted those _excellent_ (and pragmatic:-) authors & programmers, Thomas and Hunt, into perverting a clean, simple structure into a little but definite mess. This sure ain't good recommendation for adding 'retry' to Python...:-). Given that the "key missing in a dict" case is also dealt with quite decently without looping, I would suggest you look for other use cases. Perhaps simplest...: try: spin = raw_input("Please enter your PIN: ") pin = int(spin) except (EOFError, KeyboardInterrupt): print "Bye bye!" return 0 except ValueError: print "PIN must be an integer [just digits!!!], please re-enter" retry else: return validatePIN(pin) > not enough of a Pythonista yet to understand all the implications of > such a scheme (which is why this is not a PEP), so I offer it to the > community to discuss. No special "implications", as the semantics are just about the same as the above-indicated (flags-less, duplication-less) "while True:" loop that is so easy to code explicitly today. It's just that, partly because of this (and attendant benefits that writing out "while" DOES clearly indicate to the reader that the following code may repeat, etc etc), it does not seem to me that 'retry' is worth adding. But unless somebody does write a PEP, you'll just have my opinion about this... Alex From roel.mathys at yucom.be Wed Nov 5 11:15:33 2003 From: roel.mathys at yucom.be (rm) Date: 5 Nov 2003 08:15:33 -0800 Subject: XORing long strings opimization? References: Message-ID: <9f76ee00.0311050815.66e3c6df@posting.google.com> Skip Montanaro wrote in message news:... > Noen> alist = [chr(x ^ y) for x in ord1 for y in ord2] > > Noen> This creates a way too big list... Im not familiar with two for > Noen> loops in one, so I cant see whats wrong :( > > Try: > > alist = [chr(x ^ y) for (x, y) in zip(ord1, ord2)] > > Your listcomp nests two for loops. You need to iterate over both ord1 and > ord2 at the same time. > > Skip this could work as well: import itertools alist = [ chr(x^y) for x,y in itertools.izip( itertools.imap(ord,a) , itertools.imap(ord,b)) ] if I'm not mistaken this will pull out 1 character at a time, maybe not fastest method, but you won't have multiple copies of the list (original or transformed), and when you're comparing big files this might be advisable rm From aleax at aleax.it Mon Nov 10 11:04:27 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 10 Nov 2003 16:04:27 GMT Subject: Load Python Scripts from Memory References: <4d1a42cd.0311100525.6f846ead@posting.google.com> Message-ID: Dean Ellis wrote: > I'm new to python and I have a question. Is it possible to load a > script/module from memory. I have a requirement in the application I > am building for scripts to be downloaded from a web site and run > (these can be pre-compiled scripts). I would rather not have to save > these scripts to disk then load them if possible. Yes, you set your own function __import__ in lieu of the built-in one, and in that function you can do absolutely anything you want. If what you get from the website is simply the source, or the code object to be executed in order to define your module (serialized and deserialized as you prefer), then your life is reasonably easy; if due to some weird constraint you have to get less easily dealt-with things, such as the memory image of a .pyc file, you may have more work to do, of course (basically, getting the code-object from the "pyc in-memory image", after possibly checking and skipping its header), but still, it _is_ a feasible task. > I would also like to add a feature where a compiled module could be > loaded directly from a resource file. I'm not quite sure what a "resource file" _IS_. I know about the "resources" that can be hidden in a Windows .EXE file, for example (and I think win32all has code to let you get at them), but of course those are NOT "a file", so I suspect you may be thinking of something else. > Anyone have any ideas on how this could be done? Once you clarify exactly what constraints you're operating under, I'm sure some design can be found to satisfy them. Suppose, for example, that what you want to do is as follows. If the Python code at any time imports a module whose name starts with _web_, then a pickled version of said module (either a source string or a code object) is obtained (e.g. via urrlib, etc, etc) and must be placed as a module in sys.modules &c -- and you also want to do the usual optimization whereby a second import uses the module that is already in sys.modules, etc, etc. Let's suppose further that you need not deal with packages & their complications, reload, and so on. Oh, and, if the name starts with _res_ instead, you will get its pickled version via some other way (some kind of function that reads stuff in memory from a "resource file", whatever THAT may be). Oh, incidentally, we also assume that you trust the code you receive *blindly* -- it has somehow been entirely validated, and you're quite willing to let it do ANYthing the current user is authorized to do (if that's not the case, then you do have a _serious_ problem...). Under these conditions you might do something like...: import __builtin__ base_importer = __builtin__.__import__ import cPickle, new, sys def __import__(name, *args): if name in sys.modules: return sys.modules[name] if name.startswith('_web_'): pickled = get_pickled_from_web(name[5:]) elif name.startswith('_res_'): pickled = get_pickled_from_resources(name[5:]) else: return base_importer(name, *args) module = new.module(name) unpickled = cPickle.loads(pickled) exec unpickled in module.__dict__ sys.modules[name] = module return module __builtin__.__import__ = __import__ Run this code once, e.g. at program startup, and assuming the get_pickled_... functions know how to get a pickled sourcecode string or codeobject from wherever, the rest should work (I'm typing the code in from memory, not testing it, so if there's any silly typo I apologize in advance... but still I hope this can help!). So, assuming there is something that stops you from using this very simple solution, you can (with our collective help) move on from here. Except that if the problem is that you do NOT fully trust the code you have been sent, then the situation may not be solvable to your safisfaction... Alex From netspam at shic.co.uk Tue Nov 11 07:52:59 2003 From: netspam at shic.co.uk (Steve H) Date: 11 Nov 2003 04:52:59 -0800 Subject: On python syntax... References: Message-ID: Peter Otten <__peter__ at web.de> and others posted some interesting replies: Thanks very much for the various suggestions. John: I'd thought of building a tree then calling write on it myself... in one sense I find that approach neat, however it has a significant disadvantage when it comes to writing long streams - it needs the whole object allocated before I start writing - hence introducing a potentially large latency and also, potentially, requiring many costly memory allocations - which may be a significant barrier to performance when used on 'longer' streams. The "use a stack" idea is OK - in so far as it solves the problem of matching up the write closing token (should I have many different tags - say, with XML) but doesn't address my main concern - i.e. that I don't want to have to write explicit code to output the close-context marker - whatever it is. Jp: Very neat Python 2.4 answer - I like it... but it doesn't really address my current concerns... it's a touch too clever for me as it relies upon details of the specific example I posted which don't hold in my 'real-world' examples. I'm also concerned that I'd need to allocate the whole string before writing it - which would cause high latency and significant resource usage in a streaming environment. Peter: This is far more like the sort of answer I'd hoped for... I think something like wrap() might be OK - I hadn't realised I could pass arbitrarily many arguments like that. One 'down' side to this is that I'd have prefered not to have to define a new function for each of my contexts, though I suppose this might not be too much of a hardship. I'd have preferred to be able to have many different nested contexts in a single function (to share local variables etc) - though I guess that this isn't going to be possible. The wrapitems() implementation is neat - I like it... but I don't think it would apply to my real world problem - where I expect to do more complex things than just iterate a fixed loop - I envision other "contexts" for example: conditionals, while loops, functions etc. I still have a feeling that some way to hook the close of an execution context would be extremely useful... though I'm beginning to believe that this isn't currently supported. I'd be completely satisfied with wrap() if I could define the wrapped function inline somehow - yet still execute it within wrap. I'd want the wrapped function to be anonymous and to have access to all the local variables available to wrap() - without having to explicity pass each one to the wrapped function... I guess the obvious lambda args:... approach isn't going to be effective because I'd still need to specify every argument separately. Steve From lliabraa at isrparc.org Thu Nov 20 11:31:01 2003 From: lliabraa at isrparc.org (Lane LiaBraaten) Date: Thu, 20 Nov 2003 16:31:01 +0000 Subject: mpeg player? In-Reply-To: <200311201345.24005.lliabraa@isrparc.org> References: <200311201345.24005.lliabraa@isrparc.org> Message-ID: <200311201631.01889.lliabraa@isrparc.org> On Thursday 20 November 2003 01:45 pm, Lane LiaBraaten wrote: > Is there any way to play mpeg files with python without using pygame? > > TIA, > LGL There is a program called mplayer for linux which can embed mpeg video in another window given the window id. Since tkinter has this information readily available (via .winfo_id()), I wrote a simple mpeg player with tkinter in about 30 lines. HTH, LGL From peter at engcorp.com Mon Nov 3 16:08:08 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Nov 2003 16:08:08 -0500 Subject: Does python always need to compile ENTIRE program before itcanstart to run it??? References: Message-ID: <3FA6C3B8.3C39794C@engcorp.com> "Michael T. Babcock" wrote: > > >"Michael T. Babcock" wrote: > > > > > >>> ... that'll still run 'fine' because you don't use "a" > >>> > >>> That said, the "compilation" time of a Python program is almost > >>> nonexistant in most cases. Most of the work is runtime; load a class, > >>> wait for the class to compile, and so on.. > >> > >> > > > >That's not *exactly* true, I'm afraid. The above example would > >actually raise a NameError, since the name "help" is not defined > >at the time of execution, if you tried constructing an a(). > > > > You seem to have completely missed my saying 'because you don't use "a"' > in that message. In fact, I actually ran that program to check before > making the post. For what its worth, if you had "help = " instead of > just "help", it would raise a SyntaxError on execution. However, it > doesn't know if "help" is a valid statement or not yet because it hasn't > evaluated 'a' and therefore leaves you alone about it. No, Michael, you're misinterpreting what happens. Try putting that "help =" in and see the difference. You actually get the SyntaxError *during import*, and more specifically during compilation, not execution. The NameError from the lone "help" line would on the other hand come during execution, as you say *if* it were actually executed. > >Therefore I believe your first statement is actually not true, and > >in fact Python code that "wouldn't compile" actually cannot be run, > >because it has to be compiled prior to running. > > It does not throw a SyntaxError, and it does in fact run. Have a go at it. I did, and of course it works, but that's *because it would not raise a SyntaxError* which is a compilation error, but in fact raises a NameError which is a runtime exception, and therefore quite different. -Peter From paul at boddie.net Mon Nov 24 06:56:58 2003 From: paul at boddie.net (Paul Boddie) Date: 24 Nov 2003 03:56:58 -0800 Subject: Programming cellular phones using Python/Jython ? References: Message-ID: <23891c90.0311240356.1513e84a@posting.google.com> "Mark Hahn" wrote in message news:... > > "Thomas Weholt" <2002 at weholt.org> wrote in message > news:rCsvb.294$n31.5237 at news2.e.nsc.no... > > > > Is it at all possible to use python to make apps on cellular/mobile > > phones, using something like Jython etc. ? > > I just got a samsung sph-i700 phone with pocket pc 2002 and it runs python > 2.2+ apps with win32 gui just fine. I got the binaries for it from: > http://www.murkworks.com/Research/Python/PocketPCPython/Overview I suppose the question was really more concerned with making use of the Java support that a lot of new mobile 'phones seem to have these days. I can't imagine that a significant number of 'phones out in the European market (and certainly in the Norwegian market) are running some kind of Windows derivative, but many manufacturers are promoting their Java application (eg. games) support. Paul From bokr at oz.net Mon Nov 3 23:37:56 2003 From: bokr at oz.net (Bengt Richter) Date: 4 Nov 2003 04:37:56 GMT Subject: how do I stop the screen scrolling ? References: Message-ID: On Mon, 3 Nov 2003 23:56:39 -0800, "ruari mactaggart" wrote: >how do I put a pause, 'hit any key to continue' type thing in printing a >long dictionary on the screen, please ? > If you want _any_ key, you'll have to go to a little trouble (see msvcrt module's getch etc., but even then you won't be able to catch e.g., Ctrl-Alt-Del and probably some others. If you do it that way, you may want to use kbhit to make sure there's nothing pending that would proceed immediately, and nothing left over (like a second char from a function key) when you finish), but if you're satisfied with the Enter key, it's very simple and built in: raw_input('Press Enter to continue ;-) ') You can of course capture whatever string was typed up to the Enter if you like: >>> theString = raw_input('Please type something and press Enter: ') Please type something and press Enter: something >>> theString 'something' >>> Also, depending on what is doing the scrolling, Ctrl-s and Ctrl-q might stop and start it. Regards, Bengt Richter From tim at worthy.demon.co.uk Tue Nov 25 12:07:21 2003 From: tim at worthy.demon.co.uk (Tim Howarth) Date: Tue, 25 Nov 2003 17:07:21 GMT Subject: win32com (VBScript to Python) problem References: <6e24de564c.tim@worthy.demon.co.uk> <4700e5564c.tim@worthy.demon.co.uk> <4428ee564c.tim@worthy.demon.co.uk> Message-ID: In message "Matteo Risoldi" wrote: > Just a comment: is shutdown.exe leaves the machine in the "you can switch > off", try shutdown -s, it does the job for me. Ah, I'm guessing that that is an XP addition, the version of shutdown.exe that I have (from Win2k reskit IIRC) doesn't undertsand that switch. -- ___ |im ---- ARM Powered ---- From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Nov 18 20:10:36 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 19 Nov 2003 02:10:36 +0100 Subject: time.mktime memory access violation bug In-Reply-To: References: Message-ID: <3fbac30d$0$58707$e4fe514c@news.xs4all.nl> Bengt Richter wrote: > Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import time > >>> time.mktime((1969, 12, 31, 17, 0, 0, 0, 0, 0)) > 3600.0 > >>> time.mktime((1969, 12, 31, 17, 0, 0, 0, 0, 1)) > 0.0 > >>> time.mktime((1969, 12, 31, 16, 0, 0, 0, 0, 1)) > [crash with popup] Curious. I get (windows XP): Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.mktime((1969, 12, 31, 17, 0, 0, 0, 0, 0)) Traceback (most recent call last): File "", line 1, in ? OverflowError: mktime argument out of range >>> time.mktime((1969, 12, 31, 17, 0, 0, 0, 0, 1)) Traceback (most recent call last): File "", line 1, in ? OverflowError: mktime argument out of range >>> time.mktime((1969, 12, 31, 16, 0, 0, 0, 0, 1)) Traceback (most recent call last): File "", line 1, in ? OverflowError: mktime argument out of range >>> On Linux I get the same results. Something fishy is going on with your Python... --Irmen de Jong From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Nov 28 16:21:57 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 28 Nov 2003 22:21:57 +0100 Subject: Binary number manipulation In-Reply-To: <20031128160051.37a304df.matt@satbp.com> References: <20031128160051.37a304df.matt@satbp.com> Message-ID: <3fc7bc75$0$1494$e4fe514c@news.xs4all.nl> Matthew A. Berglund wrote: > I am working on a problem that requires me to take 2 decimal integers, each > of which represents half of a word. I need to slap these things together > and get out another decimal integer. [...] > I do see the bit-wise operations available and this looks like I need to > simply perform these on my integers? Can it really be that simple? Probably. Consider the following (typed at the interactive prompt): >>> a=0x1234 >>> b=0xabcd >>> i=a<<16 | b >>> print i 305441741 >>> print hex(i) 0x1234abcd This example assumes that both words are 16 bits. There are some signed/unsinged issues, be warned. --Irmen From aleax at aleax.it Mon Nov 3 05:21:37 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 03 Nov 2003 10:21:37 GMT Subject: Selling Python Software References: <3FA614DA.E88331E2@alcyone.com> Message-ID: Erik Max Francis wrote: > Will Stuyvesant wrote: > >> I tried py2exe before, but someone told me it is always possible to >> decompile...revealing the source code. > > It's always possible to decompile programs compiled to machine code, as > well, you know. Ultimately, every software developer must defend > himself with licenses and legal means, not technical ones. ...unless said SW developer keeps the extremely precious parts of his SW safely on a network server under his control (yes, it IS possible to technically secure that -- start with an OpenBSD install...:-) and only distributes the run-of-the-mill "client-oid" parts he doesn't particularly mind about. The server-side SW can supply the precious parts of the overall program's functionality to the client-side SW via secure webservices or proprietary protocols; this also allows you to enforce different business models (subscription, pay-per-use, ...) more easily than distributing things does. Very little software is WORTH protecting so closely, but for that 1 in 1000, or whatever, this option IS, IMHO, worth considering. Alex From gerson.kurz at t-online.de Wed Nov 5 08:41:00 2003 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Wed, 05 Nov 2003 13:41:00 GMT Subject: Unicode and Zipfile problems References: <3fa8d5ee.304218@news.t-online.de> Message-ID: <3fa8fdaf.10480921@news.t-online.de> Here is my "dontcare"-codec, ugly on purpose: import codecs def E(i,e=''): l=lambda c:chr(min(ord(c),255)) r="".join(map(l,i)) return (r,len(r)) def D(i,e=''): l=lambda c: unichr(ord(c)) r=u"".join(map(l,i)) return (r,len(r)) class c(codecs.Codec): def encode(self, i,e=''): return E(i,e) def decode(self, i,e=''): return D(i,e) class w(c,codecs.StreamWriter): pass class r(c,codecs.StreamReader): pass getregentry = lambda: (E, D, r, w) To install, save as python23\lib\encodings\dontcare.py and enable it in site.py. Here is a testcode: try: print unicode(chr(0xFF)) except UnicodeDecodeError, e: print e try: print unichr(12345) except UnicodeEncodeError, e: print e From newsgroups at jhrothjr.com Sat Nov 1 12:32:57 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 1 Nov 2003 12:32:57 -0500 Subject: prePEP: Decimal data type References: <3cd884n4.fsf@yahoo.co.uk> Message-ID: "Alex Martelli" wrote in message news:a%Rob.394217$R32.13072021 at news2.tin.it... > John Roth wrote: > ... [snip] I decided to snip the prior piece rather than argue about your misconception of what I intended. This would have been obvious if you had left the context of my comment in, rather than starting it out with my response to something invisible to the reader. > > I think someone earlier suggested (in the context of the Money type) > > having the number of digits be an optional arguement to the constructor. > > That is: decimal(1.1, 1) showing one place after the decimal point. > > Constructing with some specified precision (not "SHOWING" but actually > constructing) would be fine. "Places after the decimal point" may or > may not be the ideal way to specify precision, that's a different issue > (if there are any applicable standards, I'd go for those, rather than > make any arbitrary decision in the matter). But letting the precision > default if left unspecified -- and thus letting construction from floats > just happen -- is a far different decision. Naive users will always > _believe_ that they're getting "good" precision, if they think at all > about the matter (which unfortunately they may not), unless they _are_ > forced to think about the subject by needing to specify precision very > explicitly. Thus, I think "construction from float with some default > precision" runs a substantial risk of tricking naive users. I agree with that. I'd just as soon require that the precision be specified if the input is a float. As far as using number of places after the decimal point, rather than some other unit, I will admit that I can't think of another unit. John Roth > > > Alex > From FBatista at uniFON.com.ar Tue Nov 4 16:04:21 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 4 Nov 2003 18:04:21 -0300 Subject: prePEP: Decimal data type Message-ID: Aahz wrote: #- > if otherType is an int or long: #- > #- > a. an exception is raised #- > b. otherType is converted to Decimal #- > c. Decimal is converted to int or long (with ``int()`` or #- >``long()``) #- #- otherType is converted to Decimal unless precision in the current #- Context would be exceeded; in that case you raise ValueError. Like it! #- > if otherType is a float: #- > #- > d. an exception is raised #- > e. otherType is converted to Decimal (rounding? see #- next item in #- > discussion) #- > f. Decimal is converted to float (with ``float()``) #- #- Raise an exception. Because of the precision issues in #- floating point, #- conversion to Decimal must always be explicit. Seems to be the best solution, according to that we can't found a "common sense" behaviour. #- > if otherType is a string: #- > #- > g. an exception is raised #- > h. otherType is converted to Decimal #- > i. Decimal is converted to string (bizarre, huh?) #- #- Exception is raised, just as with all other uses of strings #- and numbers. We all agree here. #- >When passing floating point to the constructor, what should happen? #- > #- > j. ``Decimal(1.1) == Decimal('1.1')`` #- > k. ``Decimal(1.1) == #- >Decimal('110000000000000008881784197001252...e-51')`` #- #- That's tough. I'm inclined toward requiring an explicit conversion #- through a function call that isn't the Decimal constructor, #- but ease of #- use is also a factor. We can have a Decimal.fromFloat(...), but with behaviour j or k? #- >2. The value could be of the type: #- > #- > - another Decimal #- > - int or long #- > - float #- > - string #- #- Also a tuple of int/longs. I didn't include that in the prePEP because it seems that the actual implementation support this just to dec == Decimal(repr(dec)), for every Decimal as dec. Has any other advantage? #- >4. The Context must be omnipresent, meaning that changes to #- it affects all #- > the current and future Decimal instances. #- #- Here's the tricky part (and where I abandoned work): the #- Context must be #- thread-local. Also, Context applies only to operations, not #- to Decimal #- instances; changing the Context does not affect existing instances if #- there are no operations on them. OK. I'll change the item 4. #- #- >15. To be immutable. #- #- This is why the Context can't affect existing instances. ;-) You're right. Again. :) . Facundo From __peter__ at web.de Sun Nov 30 05:19:21 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 30 Nov 2003 11:19:21 +0100 Subject: List files without extension, was: Bug in glob.glob for files w/o extentions in Windows References: <0Zfyb.48050$dl.2119318@twister.southeast.rr.com> Message-ID: Georgy Pruss wrote: > Anyway, "*." is not a bad DOS convention to select files w/o extention, > although it comes from the old 8.3 name scheme. BTW, how can you select > files w/o extention in Unix's shells? ls -I*.* The -I option tells the ls command what *not* to show. Peter From jjl at pobox.com Sat Nov 1 18:12:34 2003 From: jjl at pobox.com (John J. Lee) Date: 01 Nov 2003 23:12:34 +0000 Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0310312008.ce341ea@posting.google.com> <87r80sdyb1.fsf@pobox.com> <7xn0bg6njb.fsf@ruckus.brouhaha.com> Message-ID: <87k76j3cpp.fsf@pobox.com> Paul Rubin writes: > jjl at pobox.com (John J. Lee) writes: > > It's hard to see how somebody (apparently) falsely claiming the > > bankruptcy of a company can be described as behaving honestly. > > The claim that I see is that: > > Basically, the answer is TKC is bankrupt. TKC's team of developers > have not been paid for over 5 months (some even longer). > > The word "bankrupt" is qualified by the word "basically" which I take > to mean that TKC is out of money but there has not yet necessarily > been a legal filing of bankruptcy. On the other hand, the claim that [...] OK. It certainly didn't read that way to me. But I guess I should assume it was just unclear rather than dishonest. Apologies! > Are you saying that the claim is false and that the developers have > actually been paid within the past 5 months? No idea! John From gerrit at nl.linux.org Tue Nov 18 08:13:44 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 18 Nov 2003 14:13:44 +0100 Subject: PEP 321: Date/Time Parsing and Formatting In-Reply-To: References: <20031117161752.GA17615@nl.linux.org> Message-ID: <20031118131344.GA3790@nl.linux.org> John Roth wrote: > > > * CVS-style or tar-style dates ("tomorrow", "12 hours ago", etc.) > > The question here is class responsibilities. The datetime module is > at a lower conceptual layer than the tarfile module. If the format > is specific to the tarfile module, then it should be that module's > responsibility to do the conversion. If it is a generally useful > capability, then it should be the datetime module's responsibility. > I'd like to see that discussed. I think this example is generally useful, in two directions, both as output and as input. It is also used by at, I think. [second example] > > >>> datetime.datetime.rfc2822("Tue, 13 Aug 1985, 15:03:00 +0100") > > datetime(1985, 8, 13, 13, 5) > As long as it's kept simple. I have a real problem with the second > example; there are simply too many variations out there of the > alphabetic month and day of the week to cover them all. Actually, this already exists, but yields a timetuple rather than a datetime object. It is called email.Utils.parsedate. > > I prefer implementation #2. I'm never very happy with using constants > > defined inside modules. I have to type 'module.CONSTANT' all the time... > > I think a method is a very suitable way to do this. > > I'd like to reiterate my comment from earlier: Internet data handling > modules are at a higher logical level than datetime. If the formats are > not generally useful, it should be the using module that is responsible > for them: that is, the email and news modules for RFC822. If they > are, then it should be datetime. I agree. But I think rfc2822 _is_ useful beyond mail and news, as are the other formats mentoined. Less useful formats can provide a string in their own library, to be passed to either strptime or strftime. yours, Gerrit. -- 162. If a man marry a woman, and she bear sons to him; if then this woman die, then shall her father have no claim on her dowry; this belongs to her sons. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From pf_moore at yahoo.co.uk Mon Nov 17 16:01:57 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Mon, 17 Nov 2003 21:01:57 +0000 Subject: Making a maze.... References: <1PSsb.44675$jy.34613@clgrps13> <221e7b06.0311170946.3baaa2ca@posting.google.com> Message-ID: phil_nospam_schmidt at yahoo.com (Phil Schmidt) writes: > I couldn't resist... > -------------------------------------------------- Interesting! One thing I'd like (I don't know if the OP had this in mind) is to have a marked "start" point, and a marked "end" point. A guarantee that there is a route from "start" to "end" would be good, too :-) I'm not sure, at a brief glance, how easy the algorithm would adapt to this. Paul. -- This signature intentionally left blank From aahz at pythoncraft.com Tue Nov 25 11:51:46 2003 From: aahz at pythoncraft.com (Aahz) Date: 25 Nov 2003 11:51:46 -0500 Subject: Delete common entries between two dictionaries References: <4Guwb.7197$9O5.6638@fed1read06> <7x8ym55t3x.fsf@ruckus.brouhaha.com> <7xn0alwcfr.fsf@ruckus.brouhaha.com> Message-ID: In article <7xn0alwcfr.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >aahz at pythoncraft.com (Aahz) writes: >>Paul Rubin: >>> >>>for k in domains_white(): >>> if k in domains_black: >>> del domains_black[k] >> >> Didja try that before posting?.... (I see at least two errors.) > >Oops, editing error (I removed 'keys' which is no longer needed, but >forgot to remove the parentheses). No I didn't try it first. >What's the second error? Try it and find out! ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From http Sat Nov 15 17:03:19 2003 From: http (Paul Rubin) Date: 15 Nov 2003 14:03:19 -0800 Subject: Is RAII possible in Python? References: <4_utb.21936$IK2.1678737@news20.bellglobal.com> Message-ID: <7x1xs9mgrc.fsf@ruckus.brouhaha.com> Pierre Rouleau writes: > AFAIK, the call of __del__() method on object destruction is not > garanteed to be called when the interpreter exists. Is this true? I think it is supposed to be called. > Is the __del__() mehod of an object garanteed to be called when a > function exists normally or is forced to exit by an exception? No. > Is RAII available in Python? You can use the try/finally construction to make sure the object gets destroyed when the finally clause runs. From BoteDesSchattens at web.de Thu Nov 20 16:02:06 2003 From: BoteDesSchattens at web.de (Tobias Pfeiffer) Date: 20 Nov 2003 21:02:06 GMT Subject: What is Togl??? Message-ID: Hi! On my Debian Linux System, I installed the python-opengl package and all that had a direct dependency. Then I wanted to look at the samples that are shipped with that package (at /usr/share/doc/python- opengl/Demo/). But every script I run in one of the subfolders gives me: Traceback (most recent call last): File "text.py", line 4, in ? from OpenGL.Tk import * File "/usr/lib/python2.2/site-packages/OpenGL/Tk/__init__.py", line 39, in ? _default_root.tk.call('package', 'require', 'Togl') _tkinter.TclError: can't find package Togl So what is Togl??? I apt-cache searched for it and it gives me liblablgl-ocaml and liblablgl-ocaml-dev but nothing changes when they are installed. So I googled for that error message but found only very few pages that led me to the thought that I need to install some additional Tk-packages. As an appendix I give you the output of dpkg -l | grep tk (A) and dpkg -l | grep gl (B). Thanks in advance! Bye Tobias (A): ii gdk-imlib1 1.9.14-13 imaging library for use with gtk ii gtkglarea5 1.2.3-2 Gimp Toolkit OpenGL area widget ii libatk1.0-0 1.2.4-1 The ATK accessibility toolkit ii libgdk-pixbuf2 0.22.0-2.0.1 The GdkPixBuf image library, gtk+ 1.2 ii libgnorbagtk0 1.4.2-14 GNOME CORBA services (Gtk bindings) ii libgtk1.2 1.2.10-16 The GIMP Toolkit set of widgets for X ii libgtk1.2-comm 1.2.10-16 Common files for the GTK+ library ii libgtk2.0-0 2.2.1-6 The GTK+ graphical user interface ii libgtk2.0-comm 2.2.1-6 Common files for the GTK+ graphical ii libgtkgl2.0-1 1.99.0-2 Gimp Toolkit OpenGL area widget ii libwxgtk2.4 2.4.0.8 wxWindows Cross-platform C++ GUI ii libwxgtk2.4-py 2.4.0.8 wxWindows Cross-platform C++ GUI ii netkit-inetd 0.10-9 The Internet Superserver ii perl-tk 800.024-1.1 Perl module providing the Tk graphics ii python-gtk 0.6.11-8 GTK support module for Python. ii python-tk 2.2.3-3 Tkinter - Writing Tk applications ii python2.2-gtk2 1.99.16-2 Python bindings for the GTK+ widget ii python2.2-tk 2.2.3-3 Tkinter - Writing Tk applications ii tk8.3 8.3.5-3 Tk toolkit for Tcl and X11, v8.3 - ii tk8.4 8.4.3-3 Tk toolkit for Tcl and X11, v8.4 - (B): ii gtkglarea5 1.2.3-2 Gimp Toolkit OpenGL area widget ii libdb1-compat 2.1.3-7 The Berkeley database routines [glibc ii libglade-gnome 0.17-2.7 Library to load .glade files at ii libglade0 0.17-2.7 Library to load .glade files at ii libglib1.2 1.2.10-9 The GLib library of C routines ii libglib2.0-0 2.2.2-1 The GLib library of C routines ii libglut3 3.7-20 the OpenGL Utility Toolkit ii libgtkgl2.0-1 1.99.0-2 Gimp Toolkit OpenGL area widget ii liblablgl-ocam 0.99-15 Runtime libraries for lablgl ii python-opengl 1.5.7-5.4 Python binding to OpenGL ii trans-de-en 1.2-2 A German-English translation ii xlibmesa3-gl 4.2.1-6 Mesa 3D graphics library [XFree86] ii xlibmesa3-glu 4.2.1-6 Mesa OpenGL utility library [XFree86] From frr at easyjob.net Thu Nov 20 09:00:02 2003 From: frr at easyjob.net (Fernando Rodriguez) Date: Thu, 20 Nov 2003 15:00:02 +0100 Subject: smtp server References: <29jmrvc4s9blgmpusb3t70b9g2c8q3q3gf@4ax.com> Message-ID: On Wed, 19 Nov 2003 13:54:52 +0100, Gerhard H?ring wrote: >Fernando Rodriguez wrote: >> Hi, >> >> Is there any python smtp server available with source? > >Try this: > >import smtpd I'll check it out, thanks. It's not included in the docs though... From alan.gauld at btinternet.com Fri Nov 28 14:54:35 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Nov 2003 19:54:35 GMT Subject: if - else References: <871xrtr8yb.fsf@pobox.com> <5ctxb.120283$Ec1.5141313@bgtnsc05-news.ops.worldnet.att.net> <87smk9mmgj.fsf@pobox.com> Message-ID: <3fc7a6dd.70951673@news.blueyonder.co.uk> On Fri, 28 Nov 2003 12:35:45 GMT, "Georgy Pruss" wrote: > | if (10 == sum) {...} > | > | rather than > | > | if (sum == 10) {...} > > Yes, there's such a style, and it's considered by experienced C > programmers to be as weird as if( (a References: Message-ID: On Fri, 21 Nov 2003, anton muhin wrote: > Really common mistake: lists are _mutable_ objects and self.myList > references the same object as the default parameter. Therefore > a.myList.append modifies default value as well. It does?! Ah, I've found it: listHolder.__init__.func_defaults Hmm... this behaviour is *very* counter-intuitive. I expect that if I were to define a default to an explicit object... def process_tree1( start=rootNode ) ...then I should indeed be able to process rootNode through manipulating start. However, if I define a default as a new instance of an object... def process_tree2( myTree=tree() ) ...then the function should, IMHO, create a new object every time it is entered. (By having func_defaults point to tree.__init__, or summat.) Was there any reason that this sort of behaviour was not implemented? > Mutable defaults are better avoided (except for some variants of memo > pattern). Standard trick is: > > def __init__(self, myList = None): > if myList is None: > self.myList = [] > else: > self.myList = myList Thank you. I shall use this in my code. (Although I would have preferred a trick that uses less lines!) -- <<>> Defender of Spudkind From donn at u.washington.edu Mon Nov 17 12:36:30 2003 From: donn at u.washington.edu (Donn Cave) Date: Mon, 17 Nov 2003 09:36:30 -0800 Subject: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <8hfsb.7707$nz.895@newsread2.news.pas.earthlink.net> Message-ID: In article , Ville Vainio wrote: > Douglas Alan writes: > > > Well, bah! There are precious few constructs in this world that are > > clearer and more readable than > > > > reduce(add, seq) > > I asked my non-programmer girlfriend what she thinks your construct > does - she didn't know. She immediately understood what sum(seq) does. You guys are hysterical. "reduce" is a performance trap waiting to pounce! (But while profiting from this bogus argument, let's not support any solution for that problem.) It's hard to understand, just ask my girlfriend! (Great. By the way, what does she think of list comprehensions, generators, etc.?) Go ahead and get rid of reduce, that sounds like a good idea to me. The reason though is just that it's not very useful in the context of a language like Python, and it seems to confuse people who draw the conclusion that Python must be some kind of functional programming language. This will be a wake-up call on that score. Donn Cave, donn at u.washington.edu From eric.brunel at pragmadev.N0SP4M.com Wed Nov 5 04:32:41 2003 From: eric.brunel at pragmadev.N0SP4M.com (Eric Brunel) Date: Wed, 05 Nov 2003 10:32:41 +0100 Subject: best GUI toolkit for python: tkinter, wxPython or what? References: <3fa13dd3.2565248@news.dsl.pipex.com> <87he1j52yc.fsf@theasylum.dyndns.org> Message-ID: Tim Lavoie wrote: >>>>>>"Frithiof" == Frithiof Andreas Jensen writes: >>>>> > > Frithiof> Actually, *I* didn't have any trouble with Tkinter > Frithiof> look&feel - The reason I do not use it is beacuse there > Frithiof> are no - well none that I could find anyway - tools > Frithiof> available to design Tkinter GUI's with! > > Perhaps this might help: > http://vtcl.sourceforge.net/ Does it generate Python/Tkinter code? AFAICT, at least from the web page, it doesn't... Another pointer: http://starship.python.net/crew/mike/src/Spectix/Spectix.html SpecTix does generate code for Python/Tkinter, even if it's still a bit experimental. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From pf_moore at yahoo.co.uk Wed Nov 26 17:29:45 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Wed, 26 Nov 2003 22:29:45 +0000 Subject: Compressing output via pipes References: Message-ID: <65h6kbl2.fsf@yahoo.co.uk> "Orr, Steve" writes: > Oracle provides an export utility (exp) and I have a shell script which > compresses its output (not stdout) thru a pipe but l need a platform > portable Python script for this. How platform portable? If you want to do this on Windows, you're basically out of luck, as Windows doesn't support named pipes like this. If you're talking just Unix variants, I'd guess that a minimal shell script is as portable as you need. Paul -- This signature intentionally left blank From gerrit at nl.linux.org Sun Nov 16 04:28:21 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 16 Nov 2003 10:28:21 +0100 Subject: RuntimeError 'maximum recursion depth exceeded' In-Reply-To: <30ntb.5073$C14.183051@twister.southeast.rr.com> References: <30ntb.5073$C14.183051@twister.southeast.rr.com> Message-ID: <20031116092821.GA23979@nl.linux.org> Georgy Pruss wrote: > Sometimes I get this error. > E.g. > > >>> sum = lambda n: n<=1 or n+sum(n-1) # just to illustrate the error > >>> sum(999) > 499500 > >>> sum(1000) > ........... > RuntimeError: maximum recursion depth exceeded > > Is there any way to set a bigger stack in Python? Yes, use sys.setrecursionlimit() See http://www.python.org/dev/doc/devel/lib/module-sys.html : setrecursionlimit(limit) Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash. Note that in this case, you can simlpy use the builtin sum: See http://www.python.org/dev/doc/devel/lib/built-in-funcs.html : sum(sequence[, start]) Sums start and the items of a sequence, from left to right, and returns the total. start defaults to 0. The sequence's items are normally numbers, and are not allowed to be strings. The fast, correct way to concatenate sequence of strings is by calling ''.join(sequence). Note that sum(range(n), m) is equivalent to reduce(operator.add, range(n), m) New in version 2.3. ...but I assume you already knew the latter, since you said that you example was just to illustrate the error. Just to be sure. yours, Gerrit. -- This space intentionally left blank. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From jjl at pobox.com Wed Nov 12 13:57:55 2003 From: jjl at pobox.com (John J. Lee) Date: 12 Nov 2003 18:57:55 +0000 Subject: STrange error importing win32gui References: <3fb27d5f.57321764@news.cybermesa.com> Message-ID: <87fzgtfm8c.fsf@pobox.com> joconnor at cybermesa.com (Jay O'Connor) writes: > I'm using Python 2.3 on windows and trying to use the win32 libs. I > keep getting the following error > > >>> import win32gui > > Traceback (most recent call last): > File "", line 1, in -toplevel- > import win32gui > ImportError: DLL load failed: A device attached to the system is not > functioning. > > I'm not sure what it means ot how to fix it. Any thoughts? Don't you just love those informative Windows error messages? I had that error message before (can't remember the circumstances), and never found out what the problem was. Had to work around it rather than fix it. John From Mike at DeleteThis.Geary.com Fri Nov 7 13:59:25 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Fri, 7 Nov 2003 10:59:25 -0800 Subject: NEWBIE: lists as function arguments References: Message-ID: Joe Poniatowski: > From what I've read in the tutorial and FAQ, I should be able to > pass a mutable object like a list as a function argument, and have > the caller see changes made to the list by the function. I must be > doing something wrong - the function in this case assigns items to > the list, but in the main module it's still empty: > > Python 2.3.2 (#1, Oct 23 2003, 11:10:37) > [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-81)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> ls = [] > >>> def f1(l2=[]): > ... l2 = ['word1','word2'] > ... print l2 > ... > >>> f1(ls) > ['word1', 'word2'] > >>> ls > [] You may be thinking of a language that has variables and assignment statements that change those variables. Python doesn't actually have either of these. Instead, it has names that are bound to objects. Your code "l2 = ['word1','word2']" *rebinds* the name "l2" to a new list object. It doesn't affect the object that l2 was bound to before this statement. > However, I can return the list and it works OK: > >>> ls = [] > >>> def f1(l2=[]): > ... l2 = ['word1','word2'] > ... print l2 > ... return l2 > ... > >>> ls = f1(ls) > ['word1', 'word2'] > >>> ls > ['word1', 'word2'] This works because when you say "ls = f1(ls)" you're rebinding ls to the object that f1() returns. You still haven't changed the list that ls was originally bound to--ls now refers to the new object. -Mike From mwilson at the-wire.com Fri Nov 21 16:58:52 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 21 Nov 2003 16:58:52 -0500 Subject: Exceptions, assigning a tuple References: <3fbdb857$0$1727$5a62ac22@freenews.iinet.net.au> <3FBDBA3E.23D54A7C@alcyone.com> Message-ID: In article <3FBDBA3E.23D54A7C at alcyone.com>, Erik Max Francis wrote: >Derek Fountain wrote: > >> What I don't understand is the assignment of a tuple in the except >> clause. >> [ ... ] >This is just using tuple unpacking in assignment: > >>>> tup = 1, 2, 3 >>>> x, y, z = tup >>>> x >1 >>>> y >2 >>>> z >3 > >This syntax can be used anywhere an lvalue is allowed, which might >include the "variable" of a for statement: > [ ... ] >and the "variable" in a try/except clause is just another example of >this. [ ... ] The use of tuple unpacking that surprised me most is in function arguments: Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f ( (a,b) ): ... print a, b ... >>> x = (1,2) >>> f(x) 1 2 >>> It almost looks like Prolog unification (but isn't really.) Regards. Mel. From mtadin66 at yahoo.com Tue Nov 4 03:35:11 2003 From: mtadin66 at yahoo.com (Marijan Tadin) Date: Tue, 4 Nov 2003 09:35:11 +0100 Subject: Selling Python Software References: Message-ID: Well, I am by no means Python or programming expert, but I've been reading posts to the same topic before. I wonder why nobody mentioned Pyrex in this context: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ As far as I've understood, in Pyrex module you can mix Python and C-code, and Pyrex will translate this module in C-code (Python extension module), and then all you have to do is compile this C-sorce file (automaticaly created by Pyrex). You can also write pure Python code in your Pyrex module, and Pyrex will translate this into a C-code. Then you can use py2exe with this compiled extensions (otherwise generated *.exe file is actually *.zip file with *.pyc files in it). There might be a problem: AFAIK there are some restrictions, and you can not use all the features of Python in Pyrex, but in that case, you may put just some vital parts of your programm in Pyrex. By doing so, you get the same protection as you would have if you've written your programm in C, and it would be much more difficult to decompile your code then from *.pyc file, and I believe that this is what many people are asking for. Of course, if the value of your programm is high enough, so that some dedicated cracker wants to crack it, then everything that was written in other posts fully applies. I hope this helps a little, Marijan Tadin From tchur at optushome.com.au Sun Nov 2 14:50:19 2003 From: tchur at optushome.com.au (Tim Churches) Date: 03 Nov 2003 06:50:19 +1100 Subject: Shelve operations are very slow and create huge files In-Reply-To: References: Message-ID: <1067802619.1187.15.camel@emilio> On Mon, 2003-11-03 at 04:28, Eric Wichterich wrote: > Hello Tim, > > thank you for your thoughts. I tried to use cPickle and gzip instead of > shelve. But it ran much slower than before. > So I used the profiler to check where the most time is needed. > To read the data and convert it back to a dictionary needed around 9 > seconds with shelve. > With cPickle, it even needed 11 seconds. > With gzip & cPickle, it also needed 11 seconds (the file was now around > 250 kB instead of 1,7 MB). > Using pickle instead of cPickle, it needed over 45 seconds. > It seems that the file size doesn't matter at all. But 9 seconds just > for converting data from a pickle back to a Python dictionary??? Presumably you will be reading the stored query results hundreds or thousands of times - otherwise the fact that it takes 9 sec versus 1 second doesn't matter. Or maybe you need a faster computer? Or perhaps a more relaxed lifestyle? > Thanks also for mentioning DMTools. Do you know whether it is useful > for (fast) convertion from a pickle (or some file stored on the server) > into a Python dictionary? I didn't find much real-life examples or > further descriptions of these tools. It doesn't use any special tricks - it just provides convenience functions for caching query results using gzipped cPickles. However, gains may only be seen with larger result sets that you are dealing with. Tim C > > Greetings, > Eric > > Am Sonntag, 02.11.03 um 08:36 Uhr schrieb Tim Churches: > > > On Sun, 2003-11-02 at 03:38, Eric Wichterich wrote: > >> One script searches the MySQL-database and stores the result, the next > >> script reads the shelve again and processes the result. But there is a > >> problem: if the second script is called too early, the error "(11, > >> 'Resource temporarily unavailable') " occurs. > > > > The only reason to use shelves is if your query results are too large > > (in total) to fit in memory, and thus have to be retrieved, stored and > > processed row-by-row. > > > >> So I took a closer look at the file that is generated by the shelf: > >> The > >> result-list from MySQL-Query contains 14.600 rows with 7 columns. But, > >> the saved file is over 3 MB large and contains over 230.000 lines (!), > >> which seems way too much! > > > > But that doesn't seem to be the case - your query results can easily > > fit > > in memory. However, the query may still take a long time to execute, so > > it may be reasonable to want to store or cache the results for further > > processing later. However, it is much quicker to just pickle (cPickle) > > the results to a gzipped file than to use shelve. The use of gzip > > actually speeds things up, provided that your CPU is reasonably fast > > and > > your disc storage system is mundane (any CPU faster than about 500 Mhz > > sees gains on most result sets). Also it saves disc space. > > > > Ole Nielsen and Peter Christen have written a neat set of Python > > functions which will automatically handle the caching of query results > > from an MySQL datadase in gzipped pickles - see > > http://csl.anu.edu.au/ml/dm/dm_software.html - except the files don't > > seem to be available from that page - Ole and Peter, please fix! > > > > -- > > > > Tim C > > > > PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere > > or at http://members.optushome.com.au/tchur/pubkey.asc > > Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 > > > > > > -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From bokr at oz.net Tue Nov 4 19:09:46 2003 From: bokr at oz.net (Bengt Richter) Date: 5 Nov 2003 00:09:46 GMT Subject: prePEP: Decimal data type References: Message-ID: On Tue, 4 Nov 2003 15:26:35 -0300, "Batista, Facundo" wrote: [...] > >#- I.e., '1.1' means something different from '1.1000',=20 >#- even though hopefully >#- Decimal('1.1')=3D=3DDecimal('1.1000'). > >Decimal('1.1') =3D=3D Decimal('1.1000') =3D=3D Decimal(11) / = >Decimal(10) Yes, but what about Decimal('1.1')/Decimal('3') =?=> Decimal('0.4') vs Decimal('1.1000')/Decimal('3') =?=> Decimal('0.3667') vs (Decimal(11)/Decimal(10))/Decimal('3') =?=> Decimal('0.4') so e.g., Decimal('1.1')/Decimal('3') !(?)= Decimal('1.1000')/Decimal('3') Or is the "Context" thing defining what all the "Decimal" constructions above do, and extra zeroes in a literal may be ignored? (If so, how does a "Decimal" know what "Context" to refer to if you have more than one "Context" going? -- IOW why wouldn't you take Decimal+Context => Decimal subclass, and let the sublass instance find its "Context" info by way of its inheritance instead of some other Decimal<->Context association? I guess I am missing the "Context" info, sorry. Where is its relation to Decimal defined? > > >#- >1. The syntax should be ``Decimal(value)``. >#- Decimal(value, precision_info) when the value cannot be=20 >#- presumed exact, IWT. >#- > >#- >2. The value could be of the type: >#- > >#- > - another Decimal >#- presume this is just a copy, unless precision info=20 >#- is provided? > >That's right. > > >#- > - int or long >#- assume no-fractional-bits precision? > >Remember that the precision is in the context. Sorry, how is context defined, so as to be accessed by the Decimal constructor? Or is there a metaclass that modifies Decimal with custom context? > > >#- even if there is an exponent? I.e., what does=20 >#- '1.000e3' mean? Same as '1000' or >#- '1000.000' ? What about '1.000e-2' ? Same as=20 >#- '0.010' or as '0.01' ? > >Decimal('1.000e3') =3D=3D Decimal('1000') =3D=3D Decimal('1000.000')=20 > >and > >Decimal('1.000e-2') =3D=3D Decimal('0.010') =3D=3D Decimal('0.01')=20 > >as a human can tell! :) Well, I meant same in a broader sense, as in will it act the same? E.g., will the result of dividing them each by Decimal('3') have the same (equal) results? If not, then they may be equal before dividing, but they're not the same. > > >#- Maybe there needs to be an abstract base class that you=20 >#- _have_ to subclass and >#- specify all these things? > >You just specify in the context what type of rounding you want. And = >that's >all. I guess I need a pointer to the context definition. I didn't wind up with a clear concept. I probably was falling asleep or something. I guess I should re-read ;-/ > > >#- > m =3D Decimal(...) >#- > m =3D=3D eval(repr(m)) >#- Does that mean repr(m) will always look like=20 >#- "Decimal('')" ? > >Still don't know. Ok, fair enough ;-) > > >#- But what about rules for precision promotion -- i.e., if you add >#- Decimal('1.1') and Decimal('0.05') I would expect the result=20 >#- to have the >#- more precise precision, and repr like "Decimal('1.15')" > >Remember the precision is in the context, not in each instance.=20 Again, how does Decimal find whatever context it should get precision from? > > >#- I have a hunch (a*b)*c could sometimes come out different=20 >#- from a*(b*c) >#- if rounding-to-specified-precision is imposed at every operation. > >This can happen, as with all the roundings data types. > Isn't this a fairly subtle thing to expect programmers to realize, who you will be trying to make things easy for with a Money class based on this stuff? Of course, you could use this stuff at very high precision, and then implement a class with Currency properties that would appear to enforce precision rounding only on assignment, and appear to evaluate rhs expressions with (for practical purposes) infinite precision. IMO that might be easier to think about. Right hand side expressions would seem continuously mathematically accurate, and assignments would choose the discrete quantized values. Then rules would be on theoretical values mapped at controlled times, and the problem would be making sure that enough precision was carried to guarantee as-if-infinite-precision rounding results (and presumably raising an exception if that broke down). This sounds like interval math in disguise kind of, but maybe it's not that bad in practical contexts? >Anyway, you always can set the "rounding" trap in the context to raise = >an >exception... > Assuming you get a call to a handler from the middle of an expression evaluation, what would you do? Seems like subtle programming decisions either to document or pass the buck on in an EZMoney module built on this ;-) Regards, Bengt Richter From kylotan at hotmail.com Sun Nov 23 01:19:55 2003 From: kylotan at hotmail.com (Kylotan) Date: 22 Nov 2003 22:19:55 -0800 Subject: Frustration with Boa Constructor References: <7T02VNBM37943.8988541667@Gilgamesh-frog.org> <153fa67.0311212057.108a1119@posting.google.com> Message-ID: <153fa67.0311222219.5c2e221b@posting.google.com> Javier Ruere wrote in message news:... > Boa now supports wxSizers. > > Javier The version I have is the same one that is available for download on the website and seems to have absolutely nothing on wxSizers. In fact I remember reading recently that there is preliminary support but it is only in CVS. Perhaps that is what you mean? -- Ben Sizer From 3seasA at Tthreeseas.DOT.not Thu Nov 20 20:31:08 2003 From: 3seasA at Tthreeseas.DOT.not (3seas) Date: Fri, 21 Nov 2003 01:31:08 GMT Subject: Matrix - Metaphors, Analogies and the REAL References: <3fb10a9e.42064405@news.cybermesa.com> Message-ID: Followup set to comp.sys.amiga.misc Amazing how people just can't seem to get that. Knode must not be working to well.... as my posts being sent to only csam are showing up in python... Maybe the question to ask is why the hell do people keep sending this to the python group, but show no interesting in dealing with the python code for it. Don Romero wrote: >> From: joconnor at cybermesa.com (Jay O'Connor) > >>> On Tue, 11 Nov 2003 12:20:58 GMT, "RaYzor" > >>> People who think the Matrix series of films are real in any way are >>> amongst the saddest people on Earth. > >> Imagine if it was "Dark City" > > "The OMEN" The following link is the search result of inputting the email address of "Toonces the cat" into google groups. And what you will find from me is rather informative http://groups.google.com/groups?q=toonces at cybergate.com If you read thru what toonces was sending back to me of my own words you will find this: " .... For myself it is doing so thru computers, but there are efforts of others as well and in other ways, such as addressing the many facets or perspective of government, religion, science, philosophy, humainty, etc... Changes that really began in our lifetime and are picking up speed to easily reach the goals in our lifetime. The current investigation of IRS abuse is in fact directly related to IRS Abuse this man received due the work. In team-work, whether knowledgable of each other or not, but supporting the same general goal, evey bit helps." But ..... http://www.neo-tech.com/irs-class-action/ I WAS WRONG! It was not the man (who created Neo-Tech from his research) or his abuse by IRS that cracked the http://www.google.com/search?q=irs.class-action IRS dbase, but a woman named Sue. Neo: Trinity, the one who cracked the IRS Dbase? I thought you were a guy. Trinity: Most guys do... Yeah, it based on real life people and events, and things names changed to .... -- 3 S.E.A.S -- Virtual Interaction Configuration (VIC) Changing how we preceive and use computers email @ translate not to net, remove capitol letters, one . web @ http://threeseas.net From tim.one at comcast.net Tue Nov 4 19:57:31 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 4 Nov 2003 19:57:31 -0500 Subject: prePEP: Decimal data type In-Reply-To: Message-ID: [Batista, Facundo] > Nice picture, :). But in Money you *want* to get rounded in the > decimal places. > > Example of decimal with precision = 100: > > 1122334455667788 --> 1122334455667788 > 1122334455.667788 --> 1122334455.667788 > > But in Money, you may want to get rounded to two decimals: > > 1122334455.667788 --> 1122334455.67 What are these example of? Literals? If you don't want 40 digits after the decimal point in a literal, don't write 40 digits after the decimal point in a literal. Or, if you have to, use the spec's quantize() function to round to the number of fractional decimal digits you want. After that, + and - take care of themselves (they neither increase nor decrease the number of decimal digits after the radix point, and IBM's arithmetic *remembers* that -- e.g., 3.12 - 1.12 is 2.00 in that scheme, not 2 or 2.0 or 2.000). You do need to explicitly round (if desired) after * and /. Because of the high value attached to 100% conformance to imposed standards in accounting apps, I think it's a good thing that you're forced to round explicitly when the result of a calculation can't be represented exactly in the mandated format -- those are exactly the places where your app will fail to meet the requirements, so it's good to be aware of them. > ... > So, unbounded precision and fixed point are the same? (I always > assumed that) It depends on who you ask, but most people would probably say "no". "Fixed point" has no fixed meaning -- it's been applied to a plethora of schemes over the decades, and each meaning has its own gang of frightened defenders <0.9 wink>. My FixedPoint class provided an historically peculiar meaning (fixed # of digits after the decimal point, unbounded # of digits before it), but one I found useful at the time. Most meanings of "fixed point" have in mind a fixed number of digits both before and after the decimal point, and rarely the same number of digits before as after. Variants in all areas are rampant. For example, for multiplication Java's BigDecimal class gives a number of digits after the decimal point in the product equal to the sum of the number of digits after the decimal points in both inputs; in the same case, FixedPoint rounds the infinitely-precise result to the larger of the number of digits after the decimal point across both inputs. Both schemes are crazy for some apps. For example, if there's 8.875% tax on a $1.01 item, 1.08875 * 1.01 = 1.0996375 # BigDecimal = 1.09964 # FixedPoint are both probably useless as-is. Under the IBM spec, you multiply and then call quantize with a second argument of (for example) 0.01. Assuming banker's rounding, that gives the 1.10 you're probably seeking. Or maybe that's not what you want -- maybe your municipality wants the excess truncated. They're both equally easy (and equally difficult ) under the IBM spec. What doesn't work is hoping that some class will do rounding correctly in all cases by magic. From gerrit at nl.linux.org Mon Nov 17 12:55:20 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 17 Nov 2003 18:55:20 +0100 Subject: PEP 321: Date/Time Parsing and Formatting In-Reply-To: <20031117161752.GA17615@nl.linux.org> References: <20031117161752.GA17615@nl.linux.org> Message-ID: <20031117175520.GA18132@nl.linux.org> Hi, PEP 321 reads: > Python 2.3 added a number of simple date and time types in the > ``datetime`` module. There's no support for parsing strings in various > formats and returning a corresponding instance of one of the types. > This PEP proposes adding a family of predefined parsing function for > several commonly used date and time formats, and a facility for generic > parsing. I was recently surprised by this fact. I don't know why there isn't such a function/method. In my opinion, it isn't a question of whether to add them or not, but how. > Input Formats > ======================= > > Useful formats to support include: > > * `ISO8601`_ > * ARPA/`RFC2822`_ > * `ctime`_ > * Formats commonly written by humans such as the American > "MM/DD/YYYY", the European "YYYY/MM/DD", and variants such as > "DD-Month-YYYY". > * CVS-style or tar-style dates ("tomorrow", "12 hours ago", etc.) I think there should be a 'strptime' equivalent, on which the former three input formats are build. I think the latter should be a class method of Timedelta. Then, those examples would be used as such: >>> datetime.datetime.iso8601("1985-08-13 15:03") datetime(1985, 8, 13, 13, 5) >>> datetime.datetime.rfc2822("Tue, 13 Aug 1985, 15:03:00 +0100") datetime(1985, 8, 13, 13, 5) >>> datetime.date.strptime("13/08/1985", "%d/%m/%Y") date(1985, 8, 13) >>> datetime.timedelta.fromstring("tomorrow") timedelta(1) A rising question, especially in the latter case, is how to deal with locale's. > 1) Add functions to the ``datetime`` module:: > 2) Add class methods to the various types. There are already various > class methods such as ``.now()``, so this would be pretty natural.:: > > import datetime > d = datetime.date.parse_iso8601("2003-09-15T10:34:54") > > 3) Add a separate module (possible names: date, date_parse, parse_date) > or subpackage (possible names: datetime.parser) containing parsing > functions:: I prefer solution 2. I think it is the most object-oriented way. And we already have several date/time modules: datetime, time, calendar. I think we should have only one, and have calendar integrated into time. I try to avoid using the time module whenever I can. I don't like it. It doesn't nicely fit into my brain, it isn't object-oriented, I think it is to much low-level. > * Naming convention to use. > * What exception to raise on errors? ValueError, or a specialized exception? The current time.strptime raises a ValueError. This sounds like a good idea. I personally like to have exceptions as specialized as reasonable, so I would prefer a subclass of ValueError. > * Should you know what type you're expecting, or should the parsing figure > it out? (e.g. ``parse_iso8601("yyyy-mm-dd")`` returns a ``date`` instance, > but parsing "yyyy-mm-ddThh:mm:ss" returns a ``datetime``.) Should > there be an option to signal an error if a time is provided where > none is expected, or if no time is provided? Well... datetime is a subclass of date, so any date is a legal datetime. I propose that date implements a strptime with all applicable codes, and datetime extends this implementation. Not sure about how to deal with time, though. Shouldn't datetime be a subclass of both date and time? > * Anything special required for I18N? For time zones? Using relative dates as input uses English input, so this one is suitable for I18N. I'm not sure about .strptime() though... I don't think it should, since 05/04/03 may yield entirely different results in different locale's, which is not true for 'tomorrow'. > Generic Input Parsing > ======================= > > Is a strptime() implementation that returns ``datetime`` types sufficient? It would at least need to be in the datetime module. > Not all input formats need to be supported as output formats, because it's > pretty trivial to get the ``strftime()`` argument right for simple things > such as YYYY/MM/DD. Only complicated formats need to be supported; RFC2822 > is currently the only one I can think of. > > Options: > > 1) Provide predefined format strings, so you could write this:: > 2) Provide new methods on all the objects:: > > d = datetime.datetime(...) > print d.rfc822_time() I prefer implementation #2. I'm never very happy with using constants defined inside modules. I have to type 'module.CONSTANT' all the time... I think a method is a very suitable way to do this. yours, Gerrit. -- 205. If the slave of a freed man strike the body of a freed man, his ear shall be cut off. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From kristian.ovaska at helsinki.fi Wed Nov 19 05:07:12 2003 From: kristian.ovaska at helsinki.fi (Kristian Ovaska) Date: Wed, 19 Nov 2003 10:07:12 GMT Subject: plotting data against a time axis References: <20031115221933.GA10810@nl.linux.org> Message-ID: <23fmrvsq2eceg09u35rftdogvacqk5m192@4ax.com> Gerrit Holl : >http://people.nl.linux.org/~gerrit/stats.png X-axis seems to be yy/mm, but the starting point (01/11) is the same as the ending point - how's that possible? After 01/12 comes 01/01. Yet the data seems to be different for the two 01/11's. Regarding Gnuplot, I too think it's fine for many plotting tasks, even if the output is a bit rough. Here's a plot on my daily caffeine usage (bizarre, eh?): http://www.cs.helsinki.fi/u/hkovaska/images/kofeiini.png -- Kristian Ovaska - http://www.cs.helsinki.fi/u/hkovaska/ From swativ at gwu.edu Thu Nov 27 15:02:56 2003 From: swativ at gwu.edu (suenacita1) Date: Thu, 27 Nov 2003 20:02:56 -0000 Subject: Ques From CS Grad Student Message-ID: Hi. I'm a masters student at the George Washington University currently taking an Open Source Software Development course. One of our assignments was to do a presentation on an open source project and i chose Python. I have most of my presentation done but had a couple questions where I want the help of the Python community to help me answer. 1. How many members are involved directly, and how many peripherally? 2. What do you use to drive releases? 3. How often does the project release major and minor revisions? 4. What tools do they use to manage the source? 5. How does the Python project resolve conflicts between members? I'd greatly appreciate some feedback. Thanks in advance. Swati From edreamleo at charter.net Sat Nov 8 11:11:15 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Sat, 8 Nov 2003 10:11:15 -0600 Subject: Leo + Python: the ultimate scripting tool Message-ID: I would like to say a few (actually more than a few) words here about some recent discoveries I have made concerning the interaction of Leo and Python. If you don't want to hear an inventor enthuse about his work, please feel free not to read further :-) There are at least three, no four, no five, no six, no seven reasons why Leo and Python work so well together. Most are new (in my mind) with the 4.1 release of Leo. The first several reasons may not seem like much. As you will see, this appearance is completely misleading: the combination of features is incredibly powerful. To keep the individual posts shorter I shall list these 7 reasons and a conclusion in "replies" to this posting. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From http Sat Nov 22 15:14:03 2003 From: http (Paul Rubin) Date: 22 Nov 2003 12:14:03 -0800 Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> Message-ID: <7xislcjh4k.fsf@ruckus.brouhaha.com> rkern at ucsd.edu (Robert Kern) writes: > Note that the question is phrased as a "proprietary vs. GPL" > dichotomy. I think the following entry is more appropriate: > > http://www.gnu.org/licenses/gpl-faq.html#TOCGPLModuleLicense No I don't think it's more appropriate. That entry is about adding your own module to a GPL'd program. Such a module doesn't have to be GPL'd, as long as its license is "GPL-compatible". The original question was not about that. It was about using part of a GPL'd program in another program. That is prohibited unless the second program is also GPL'd. From peter at engcorp.com Mon Nov 10 16:05:54 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Nov 2003 16:05:54 -0500 Subject: make order of function definitions irrelevant References: <3FAFF284.8EA7AEFB@engcorp.com> Message-ID: <3FAFFDB2.20F185A3@engcorp.com> anton muhin wrote: > > Peter Hansen wrote: > > As it stands, the first line in the above code is still redundant, > > and can be removed with no ill effects, as "func" is not actually > > called until it is bound to a real function. > > Sure, thanks. It just a little bit clearer. I would respectfully claim that, to a Python programmer, it's actually just a little bit _less_ clear, just because of the "unnecessity" of doing it. One might have to waste a moment to try to figure out why it's done that way. Only to a programmer coming from another language, one which requires such declarations, might this seem clearer, and I'm unsure about that. (And the sooner said programmer unlearns some things, the sooner Python will feel more comfortable.) All IMHO... no offense intended. -Peter From keflimarcusx at aol.comNOSPAM Mon Nov 17 07:50:23 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 17 Nov 2003 12:50:23 GMT Subject: Newbie - Variable Scope References: Message-ID: <20031117075023.12288.00000314@mb-m25.aol.com> >I have a 2 Python scripts that contain the following lines: > >test.py >------- >from testmod import * >a1 = 10 >modfunc() > >testmod.py >----------- >def modfunc(): > print a1 > >When I run test.py, it returns the following error: > > File "testmod.py", line 2, in modfunc > print a1 >NameError: global name 'a1' is not defined > >My intent is to make a1 a global variable - so that I can access its value >in all functions of imported modules. What should I do? > >Thanks in advance, > >Rohit I think this is technically one script (not "two scripts"), just in two modules, but whatever. First off, you're using the form "from x import y", (in this case, x is 'testmod' and y is '*') which shouldn't be used for your own modules unless you know what you're doing. It is better to write this as "import x". This has nothing to do with the problem, though. What you have to do for your specific test case is have testmod.py import test.py, because it uses a variable that's defined in test.py. Using "from x import *" doesn't make the x act like a C-style include file, though there are many similarities. Of course, it's best to avoid situations where two modules import each other altogether. I would put the globals in a third module and have everything import that module. Thus, one solution would be this: test.py ------- import testmod import globals globals.a1 = 10 testmod.modfunc() testmod.py ---------- import globals def modfunc(): print globals.a1 globals.py ---------- # Blank, but you can define 'a1' here instead of in test.py if it's more appropriate Of course, the uber-best solution is to avoid globals altogether, but that's another thing... - Kef From qual at tiscali.de Sat Nov 1 16:43:43 2003 From: qual at tiscali.de (Uwe Hoffmann) Date: Sat, 01 Nov 2003 22:43:43 +0100 Subject: import cx_Oracle In-Reply-To: References: <3fa32966$0$1118$6c56d894@feed0.news.be.easynet.net> Message-ID: GrayGeek wrote: > Bernard Delm?e wrote: > > >>>It gives me an error about being unable to find the OCISetDefault entry >>>point in 'oci.dll'. >> >>cx_Oracle works on top of the regular oracle client, which you'll >>need to install before it works. The OCI libraries are parOCISetDefault t of that. > > > I have it installed, and have used it to create webpages using Oracle's > HTP.P function, and I also accessed tables on the Oracle9 server from JDev9 > and from PLSQLDeveloper. The oci.dll is in the Oracle Home/dll directory. > As my first post indicated, cx_Oracle is able to see oci.dll, it just can't > communicate with it properly. > ??? i think that the binaries were built against another version of oracle. i had a similar problem with DCOracle2 (versions 8.0.5 vs. 8.1.7 or 7.3.3 vs. 8.0.5). As far as i remember OCISetDefault was one of the problematic symbols. From marfadeu at gmx.de Sun Nov 2 15:56:24 2003 From: marfadeu at gmx.de (Markus Faust) Date: Sun, 02 Nov 2003 21:56:24 +0100 Subject: F2py and Compaq Visual Fortran 6.6, Win-XP Message-ID: Hi, I'm trying to link Fortran files generated with ?Compaq Visual Fortran Optimizing Compiler Version 6.6 (Update B)? under ?Enthought Edition build 1028, Python 2.3 (#46, Aug 11 2003, 09:34:05) [MSC v.1200 32 bit (Intel)] on win32? on Windows-XP?. I changed mingw32_support.py as proposed by Pearu Peterson on April 8 2003 (I changed `if 1:` block into `if 0:` block). When trying the following Python session: import sys from scipy_distutils.command.build_flib import compaq_visual_fortran_compiler class wrap(compaq_visual_fortran_compiler): def announce(self, s): sys.stdout.write(s+'\n') wrap().get_version() I get detecting Compaq Fortran compiler... DF /what found Compaq Visual Fortran Optimizing Compiler Version 6.6 (Update B) Traceback (most recent call last): File "E:\Programme\F2PY-2.37.233-1545\docs\test_visualfortran.py", line 8, in ? wrap().get_version() File "E:\Python23\lib\site-packages\scipy_distutils\command\build_flib.py", line 1443, in __init__ from distutils.msvccompiler import find_exe ImportError: cannot import name find_exe and f2py -c ?help-compiler results in Not found/available: PG Fortran compiler Not found/available: Absoft Fortran compiler Not found/available: Intel Fortran compiler Not found/available: Itanium Fortran compiler Not found/available: NAG Fortran compiler Traceback (most recent call last): File "", line 1, in ? File "E:\Python23\lib\site-packages\f2py2e\f2py2e.py", line 522, in main run_compile() File "E:\Python23\lib\site-packages\f2py2e\f2py2e.py", line 514, in run_compile setup(ext_modules = [ext]) File "E:\Python23\lib\site-packages\scipy_distutils\core.py", line 42, in setup return old_setup(**new_attr) File ".\distutils\core.py", line 135, in setup File ".\distutils\dist.py", line 422, in parse_command_line File ".\distutils\dist.py", line 525, in _parse_command_opts File "E:\Python23\lib\site-packages\scipy_distutils\command\build_flib.py", line 103, in show_compilers compiler = compiler_class() File "E:\Python23\lib\site-packages\scipy_distutils\command\build_flib.py", line 1443, in __init__ from distutils.msvccompiler import find_exe ImportError: cannot import name find_exe and f2py -c --fcompiler-exec=D:\Program Files\Microsoft Visual Studio\DF98\BIN\F77.EXE -DNO_APPEND _FORTRAN -DUPPERCASE_FORTRAN -m hello hello.f running build running run_f2py creating d:\dokume~1\faust\lokale~1\temp\tmptfnr7c Reading fortran codes... Reading file 'hello.f' Post-processing... Block: hello Block: foo Saving signatures to file "d:\dokume~1\faust\lokale~1\temp\tmptfnr7c\hello.pyf" Reading fortran codes... Reading file 'd:\\dokume~1\\faust\\lokale~1\\temp\\tmptfnr7c\\hello.pyf' Post-processing... Block: hello Block: foo Building modules... Building module "hello"... Constructing wrapper function "foo"... foo(a) Wrote C/API module "hello" to file "d:\dokume~1\faust\lokale~1\temp\tmptfnr7c/hellomodule.c" running build_flib Traceback (most recent call last): File "", line 1, in ? File "E:\Python23\lib\site-packages\f2py2e\f2py2e.py", line 522, in main run_compile() File "E:\Python23\lib\site-packages\f2py2e\f2py2e.py", line 514, in run_compile setup(ext_modules = [ext]) File "E:\Python23\lib\site-packages\scipy_distutils\core.py", line 42, in setup return old_setup(**new_attr) File ".\distutils\core.py", line 149, in setup File ".\distutils\dist.py", line 907, in run_commands File ".\distutils\dist.py", line 927, in run_command File ".\distutils\command\build.py", line 107, in run File "E:\Python23\lib\cmd.py", line 333, in run_command File ".\distutils\dist.py", line 926, in run_command File "E:\Python23\lib\cmd.py", line 117, in ensure_finalized line = self.cmdqueue.pop(0) File "E:\Python23\lib\site-packages\scipy_distutils\command\build_flib.py", line 170, in finalize_options verbose = self.verbose) File "E:\Python23\lib\site-packages\scipy_distutils\command\build_flib.py", line 1561, in find_fortran_compiler compiler = compiler_class(fc,f90c,verbose = verbose) File "E:\Python23\lib\site-packages\scipy_distutils\command\build_flib.py", line 1443, in __init__ from distutils.msvccompiler import find_exe ImportError: cannot import name find_exe Has anybody an idea what could be wrong? Finally I would like to link f90 files to Python. Markus From __peter__ at web.de Sun Nov 9 06:15:38 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 09 Nov 2003 12:15:38 +0100 Subject: Tkinter, icursor() method on a Text widget References: <6d171fff.0311082240.31a5731f@posting.google.com> Message-ID: snx7s wrote: > Hi, > > using Tkinter, on a Text widget i would like to place the cursor to a > given position like the icursor() method of the Entry widget. > Is it possible do that, if it is how please ? > > Thank You. Use text.mark_set(Tkinter.INSERT, "5.2") to move the cursor to column 2 in row 5, where columns start at 0 and the first line is 1. There are other more complicated forms, like text.mark_set(Tkinter.INSERT, "1.0 +100 chars") which goes to the hundreth char (counting newlines). For details and the general concept behind this, see http://www.nmt.edu/tcc/help/pubs/tkinter.pdf Peter From nav+posts at bandersnatch.org Sat Nov 22 16:18:53 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 22 Nov 2003 16:18:53 -0500 Subject: 2 different python versions / how to install packages? References: Message-ID: I would install Python 2.3 in a seperate location from the system version. The system version is probably in /usr/bin, so install Python 2.3 with "--prefix=/usr/local". Make sure /usr/local/bin is before /usr/bin in your PATH. Then, when you run configure for the extensions you want to install, the configure script should pick up /usr/local/bin/python, and all should be well. You will also need to make sure /usr/local/bin is before /usr/bin if you use "#!/usr/bin/env python" in your scripts. Or you could just explicitly say "#!/usr/local/bin/python" to make sure you're using the "correct" version. 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 klapotec at chello.at Mon Nov 10 22:49:48 2003 From: klapotec at chello.at (Christopher Koppler) Date: Tue, 11 Nov 2003 03:49:48 GMT Subject: What do you think of this Python logo? References: Message-ID: On Mon, 10 Nov 2003 15:33:34 -0800, Scott Chapman wrote: >On Monday 10 November 2003 14:16, Brandon J. Van Every wrote: >> What do you think of this Python logo? >> http://pythonology.org/logos >> Good, bad, indifferent, love it, hate it? > >I like it. >I like the font. It shrinks well and is not obnoxious. The font is the traditional beauty products font Optima, which I don't think is the image that should get across. Although... Make up your code with Python! sounds silly enough at this time of morning that it could work. -- Christopher From jsbenson at bensonsystems.com Sat Nov 29 23:26:50 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Sat, 29 Nov 2003 20:26:50 -0800 Subject: python-list query re sockets, select or: twisted and other file-descriptors & twisted question Message-ID: <061d01c3b6fa$2d0a12e0$210110ac@jsbwxp3> In response to the question about doing serial i/o and using a select statement, I'd like to quote from http://www.python.org/doc/current/lib/module-select.html select(iwtd, owtd, ewtd[, timeout]) This is a straightforward interface to the Unix select() system call. The first three arguments are lists of `waitable objects': either integers representing file descriptors or objects with a parameterless method named fileno() returning such an integer. The three lists of waitable objects are for input, output and `exceptional conditions', respectively. Empty lists are allowed, but acceptance of three empty lists is platform-dependent. (It is known to work on Unix but not on Windows.) The optional timeout argument specifies a time-out as a floating point number in seconds. When the timeout argument is omitted the function blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks. The return value is a triple of lists of objects that are ready: subsets of the first three arguments. When the time-out is reached without a file descriptor becoming ready, three empty lists are returned. Among the acceptable object types in the lists are Python file objects (e.g. sys.stdin, or objects returned by open() or os.popen()), socket objects returned by socket.socket(). You may also define a wrapper class yourself, as long as it has an appropriate fileno() method (that really returns a file descriptor, not just a random integer). Note: File objects on Windows are not acceptable, but sockets are. On Windows, the underlying select() function is provided by the WinSock library, and does not handle file desciptors that don't originate from WinSock. (end quote) So, select might not yet work on Windows serial ports as well as sockets. This is also a subject of interest to me, but all I can think of is handling the sockets via select() and polling periodically for data on the serial port using callLater() and some win32 calls. Maybe the win32 serial port handling could even be wrapped in a 'waitable object' as described above for use with the Python select() call. I recall reading somewhere that the twisted framework has the ability to handle serial communications in connection with Global Positioning System device interaction, but don't have any information about it. I'm going to post this to the twisted mailing list : Question for twisted folks: How can I add serial Windows serial port communications as a twisted protocol? Please cross-post back to the python-list. From mis6 at pitt.edu Thu Nov 13 08:51:25 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 13 Nov 2003 05:51:25 -0800 Subject: Trouble with metaclass References: Message-ID: <2259b0e2.0311130551.4f133a23@posting.google.com> Fernando Rodriguez wrote in message news:... > Hi, > > I'm having trouble with a metaclass suposed to check the method signature of > its classes. > > Here's the metaclass: > > class MetaChecker(type): > def __new__(cls, name, bases, attribs): > for name, value in attribs.iteritems(): > if inspect.ismethod(value): > if not isSingleArg(value): > raise "%s is not a thunk method!"%name > return type.__new__(cls, name, bases, attribs) > > > def isSingleArg(fn): > > args = inspect.getargspec(fn)[0] > if len(args) == 1: > return 1 > else: > return None > > > And here's a class with this metaclass: > > class Preconditions (object): > > __metaclass__ = MetaChecker > > > > If I define a descendant of Preprocesor with a method with 2 arguments, I > don't get any error: > class P (Preprocessor): > def f(self, x): > return x > > > What am I doing wrong? O:-) The metaclass is right and actually the names you are using (Preconditions/ Preprocessors) suggest to me that you are using the right tool for the job; the only problem is that you must use 'inspect.isfunction' and not 'inspect.ismethod', because of the methods <=> functions mismatch I am sure you know everything about ;) If not, please feel free to ask. Also, I would use return super(mcl,MetaChecker).__new__(mcl,name,bases,attribs) instead of type.__new__, anticipating the need for multiple inheritance of metaclasses. Michele From max at alcyone.com Mon Nov 17 21:47:34 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 17 Nov 2003 18:47:34 -0800 Subject: True inconsistency in Python References: <3FB8847F.6CB1BECA@alcyone.com> <3FB92086.9CBD0761@alcyone.com> <8qhirvgi2sf5l3vkfocq65mcb94c6pbb9s@4ax.com> <3FB95BC5.A33E6DDE@alcyone.com> <34nirv8qfphublscs12ct3acufciv828rp@4ax.com> Message-ID: <3FB98846.D5688F09@alcyone.com> Ron Adam wrote: > I'm not arguing at all. Only exploring the issue. Maybe you should summarize your central tenets, I'm afraid they've gotten lost. It seems like we've run around in a big circle. > The interpreter initializes True and False when it starts. So for > small applications, they are fairly dependable, it shouldn't be a > problem to use them. For large application with multiple files > imported into them written by several programmers, it might not be a > bad idea to initialize them like above to be safe. Unless you're using naughty things like `from module import *', no collision can occur. If you are, why are you more worried about collisions with the True/False constants, rather than any of the other builtins? They're all just as possible. > So maybe you are correct, we shouldn't use anything. (?) My point is that you need to expect a sane environment. If you're working with fellow engineers who keep planting time bombs, maybe they should be removed from the team rather than having to defensively work around their potential disasters. Python has as a central concept that everyone's an adult. If you want to mess things up really badly, you can. If you want to use some clever trick in order to save a lot of work, you can do that too. With power and flexibility comes the ability to mess things up really badly. Lack of constants is an example of this idea in Python (as is, for example, the lack of access control on object attributes). If someone's going to keep overriding True and False, or int, or open, then you're not going to get anywhere. Python isn't designed so that you can write code that is completely protected from the misbehavior of other engineers. And it shouldn't be. > Yes, so what are True and False? Are they just preinitialized > variables? Are do they have special properties of their own? They're builtins, just like all the other builtins like int, max, file, map, etc. > From what I've seen so far, the 'True' and 'False' values are useful, > but the names 'True' and 'False' can be changed and aren't synonymous > with the values 'True' and 'False'. Two different things. All the other "preinitialized variables" have exactly the same characteristic. There are no constants in Python. > So how would you use True and False? I say go ahead and use them to > make your code readable, but if its a large or mission critical > application, you might want to make sure they are what they should be > before you do by initializing them the same as you would any other > variable. I never suggested that True and False shouldn't be used; far from it. I just used your objection (that their values can be overridden) to illustrate a reductio ad absurdum. Either that's a really scary thing (which you can't defend against) and the interpreter comes crumbling down, or you assume that people are going to behave themselves and don't worry about it. > If a programmer is malicious and wants to sabotage code, making True > and False constants will hardly stop them. Exactly. So I don't understand what your point is; you're the one who brought up the danger of overriding True and False. > What am I missing? The thread is about 'True inconsistency in > Python', and the reason it's inconsistent is because it can be changed > so easy. You've gotten severely sidetracked on this thread. The original inconsistency mentioned in this thread is that explicit comparisons with True or False do not involve an implicit conversion to bool. So 3 == True is False, even though bool(3) == True is True. > Doing this causes an error: > > >>> 1 = 2 > SyntaxError: can't assign to literal > > Doing this does not cause an error: > > >>> True = False > >>> That's because a literal is not a name that can be assigned to, anymore than 'asdf' = 2 + 3 could possibly make any sense. True and False are, on the other hand, names. > Are True and False Bools? True and False are names which are initially bound to the true and false Boolean values, respectively. They're names like any other names: x, thisIsAVariable, int, str, sys, etc. > Why are they not also literals? Wouldn't that be consistent? They're not literals because that's not the way that they're handled by the language. None, for instance, is not a literal; it's a name. So neither are True and False. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ So little time, so little to do. -- Oscar Levant From adalke at mindspring.com Wed Nov 12 03:32:36 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 12 Nov 2003 08:32:36 GMT Subject: True, False, None References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> Message-ID: Michele Simionato > Better to say: singletons are classes. But True and False are not > classes (no '__base__' attribute, for instance) so they are not > singletons. I don't follow your statement. Not all singletons are classes. Imported modules are singletons, yes? And as an implementation choice the numbers -1 to 100 are singletons as are the single character byte strings. (Implementation choice since the spec requires that None references a singleton but not that 1 and 3-2 always reference the same object.) >>> import sys >>> sys.__base__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute '__base__' >>> (1).__base__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'int' object has no attribute '__base__' >>> > I think using smallcaps would have been more consistent. Well, I do too. Just conjecturing. Andrew dalke at dalkescientific.com From scott_list at mischko.com Fri Nov 7 14:29:52 2003 From: scott_list at mischko.com (Scott Chapman) Date: Fri, 7 Nov 2003 11:29:52 -0800 Subject: Request for simple a customisable Python editor In-Reply-To: <3FABDD1C.AFBAF3C8@engcorp.com> References: <3FABDD1C.AFBAF3C8@engcorp.com> Message-ID: <200311071129.52420.scott_list@mischko.com> On Friday 07 November 2003 09:57, Peter Hansen wrote: > OP: > > >I want to develop a simple Python program to edit source code that > > > is persisted in a database (memo fields). It would be very nice if you could make a Unix file that actually wrote to and read from a python script. The script would open a connection to the database and read/write as required. Then any editor could be used, even FTP and it would be totally transparent to the application. Can this be done? I've been thinking of putting my Python code in a database also and been wondering how to do that easily. Scott From mertz at gnosis.cx Wed Nov 19 14:35:19 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Wed, 19 Nov 2003 14:35:19 -0500 Subject: rotor alternative? References: <9a6d7d9d.0311181113.3bf45ec8@posting.google.com> <7xwu9x32j2.fsf@ruckus.brouhaha.com> <9a6d7d9d.0311190924.bdf3ac6@posting.google.com> Message-ID: <3X8u/kKkXMNB092yn@gnosis.cx> aaron at reportlab.com (Aaron Watters) wrote previously: |FWIW it was loosely inspired by RC4 and it seems to scramble |things up nicely. For cryptography, "inspired by" is a very bad standard. Very small changes to algorithms can hugely lessen their strength. Moreover, "seeming to scramble" is almost worthless--good algorithms need literally years of serious study by very good cryptographers before even minimal assurances of strength can be made. Yours, Lulu... -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From hanzspam at yahoo.com.au Fri Nov 21 03:12:15 2003 From: hanzspam at yahoo.com.au (Hannu Kankaanp??) Date: 21 Nov 2003 00:12:15 -0800 Subject: How do you pass a standard operator such as '<' as a parameter? References: Message-ID: <840592e1.0311210012.63f5fcab@posting.google.com> "Peter Milliken" wrote in message news:... > Wrote too soon - the obvious answer is not to use a "comparison" function at > all when instantiating the class but rather to just code the "<" in the > class "add" procedure and then make sure the data type that is being used > contains a __lt__ operator :-) i.e. the class definition should just be: Huh? I was certain you wanted to use comparison function to get flexibility, but by hard-wiring < to the code you'll lose that. One might want to have the list ordered by some other property, e.g. from largest element to smallest, or by tuple's second element. Someone might want to put the same objects in several containers, and the elements would be sorted differently in each container. You could just add "less than" as a default behaviour def __init__ (self, comparator=operator.lt): From pclinch at internet-glue.co.uk Mon Nov 10 15:39:52 2003 From: pclinch at internet-glue.co.uk (Paul Clinch) Date: 10 Nov 2003 12:39:52 -0800 Subject: Load Python Scripts from Memory References: <4d1a42cd.0311100525.6f846ead@posting.google.com> Message-ID: <8cf2994e.0311101239.66b23c16@posting.google.com> dean.ellis at capitaes.co.uK (Dean Ellis) wrote in message news:<4d1a42cd.0311100525.6f846ead at posting.google.com>... > Hi > > I'm new to python and I have a question. Is it possible to load a > script/module from memory. I have a requirement in the application I > am building for scripts to be downloaded from a web site and run > (these can be pre-compiled scripts). I would rather not have to save > these scripts to disk then load them if possible. Possible to get clever with hooking into the import see http://www.python.org/doc/2.3.2/whatsnew/section-pep302.html But, mainly look at exec, execfile, eval() and compile(). Of course its up to you to determine this is safe, security-wise. > > I would also like to add a feature where a compiled module could be > loaded directly from a resource file. View the new import from zip file feature in Python2.3! http://www.python.org/doc/2.3.2/whatsnew/node5.html > Anyone have any ideas on how this could be done? > > Dean Regards, Paul Clinch From hwlgw at hotmail.com Tue Nov 4 16:11:16 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 4 Nov 2003 13:11:16 -0800 Subject: Selling Python Software References: Message-ID: Thank you all for your input and thoughts! I am replying to my first post since otherwise I would have to choose one of the threads and I can't: several are useful. I got the customer's interest via a CGI based webservice that did show what I can do. Given this, now it would be very simple for me to keep it as a webservice and give them a client script using the urllib module or something like that...it would access the webservice and they would never see the algorithm (I want to keep that to myself). That is the solution I would like best. Not only because I want to keep stuff to myself, but also because then I can easily upgrade to new versions in one fell swoop if they or others are interested. But a program that has to be connected to the internet is not acceptable, their boss says. Humph. Maybe I should trust them and do normal bussiness as I did before with other customers already: just send them the commandline version of the program; but somewhere in the back of my mind I feel uneasy about this. Dunno why. Maybe just because they have a pointy haired boss. Alex Martelli told about software bussiness in southern europe, well, it's one big EU now, with the italian Berlusconi as chairman (soon appointed invulnerable for that job too?), and I feel it's the same thing now here in mideurope too. I guess I am going to send them an MIT licence (although I am afraid those licences are pretty useless in The Netherlands), the .pyc files for the algorithm and the utility modules, and a .py file for the main program. Or maybe I am going to use upx or another .exe encrypter (but then I have to find out first if I can wrap my head around the usage of the latest py2exe thing). Then if I find out later they copied the algorithm then maybe I have a case against them. Just let's not hope it comes to that, I'd rather start another project. But this little thing I like and it would be great if I could make some extra money with it. Curious? It does XML transformations. With a twist. Will let you know how it works out, takes a couple of weeks perhaps until they decide. Thank you! From aleax at aleax.it Tue Nov 4 10:31:02 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 04 Nov 2003 15:31:02 GMT Subject: Please explain the meaning of 'stealing' a ref References: <20031103221927.08116.00000258@mb-m15.aol.com> Message-ID: KefX wrote: >> what exactly is the meaning of a function >>"stealing a reference"? > > It decrements the reference count. *NO*! It _takes over ownersip_: it DOESN'T decrement the refcount at that point; rather, it takes over the future responsibility for decrementing it at some point in time, i.e., the abstract "ownership" of the reference. See my other post in this thread for the classic example from Python's online API docs ... if PyTuple_SetItem _decremented the reference_ to the newly created PyObject* it's passed, how WOULD it fill the tuple's item?-) > If you still need the reference, > Py_INCREF() it beforehand. If you still need to OWN the reference, yes. If you just need to USE it for a while during which you're sure the tuple that's now "owning" it isn't going away, no need to incref-then-decref. Alex From FBatista at uniFON.com.ar Tue Nov 4 13:26:35 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 4 Nov 2003 15:26:35 -0300 Subject: prePEP: Decimal data type Message-ID: bokr at oz.net wrote: #- (First, thanks for the plain-text post ;-) This is not my choice. I *always* send the mail as plain-text. But sometimes (and I don't know specifically when) the mail server convert it to RTF and adds a warning ad, :(. The perils of working to a Exchange-Mail-Server kind of enterprise. #- I.e., '1.1' means something different from '1.1000', #- even though hopefully #- Decimal('1.1')==Decimal('1.1000'). Decimal('1.1') == Decimal('1.1000') == Decimal(11) / Decimal(10) #- >1. The syntax should be ``Decimal(value)``. #- Decimal(value, precision_info) when the value cannot be #- presumed exact, IWT. #- > #- >2. The value could be of the type: #- > #- > - another Decimal #- presume this is just a copy, unless precision info #- is provided? That's right. #- > - int or long #- assume no-fractional-bits precision? Remember that the precision is in the context. #- even if there is an exponent? I.e., what does #- '1.000e3' mean? Same as '1000' or #- '1000.000' ? What about '1.000e-2' ? Same as #- '0.010' or as '0.01' ? Decimal('1.000e3') == Decimal('1000') == Decimal('1000.000') and Decimal('1.000e-2') == Decimal('0.010') == Decimal('0.01') as a human can tell! :) #- Maybe there needs to be an abstract base class that you #- _have_ to subclass and #- specify all these things? You just specify in the context what type of rounding you want. And that's all. #- > m = Decimal(...) #- > m == eval(repr(m)) #- Does that mean repr(m) will always look like #- "Decimal('')" ? Still don't know. #- But what about rules for precision promotion -- i.e., if you add #- Decimal('1.1') and Decimal('0.05') I would expect the result #- to have the #- more precise precision, and repr like "Decimal('1.15')" Remember the precision is in the context, not in each instance. #- I have a hunch (a*b)*c could sometimes come out different #- from a*(b*c) #- if rounding-to-specified-precision is imposed at every operation. This can happen, as with all the roundings data types. Anyway, you always can set the "rounding" trap in the context to raise an exception... . 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 benm at cyber.com.au Tue Nov 25 00:38:40 2003 From: benm at cyber.com.au (Ben McGinnes) Date: Tue, 25 Nov 2003 16:38:40 +1100 Subject: Puffin Automation Framework (PAF) query In-Reply-To: <3FC1E6CC.58426F73@hotmail.com> References: <3FBDF4DC.2825D2A3@hotmail.com> <3FC1E6CC.58426F73@hotmail.com> Message-ID: <20031125053840.GD28702@vanilla.office.cyber.com.au> Alan Kennedy(alanmk at hotmail.com)@Mon, Nov 24, 2003 at 11:09:00AM +0000: > > What you're discovering is the puffin author's inappropriate use of > XML. > > Although the documents you're using may be well-formed, the author has > imposed other implicit constraints on the contents of the XML files > used for configuration. And since these constraints are not > documented, you'll only find them in one of two ways: > > 1. Tripping over them, as you have just done. > 2. Reading the source. Urgh! That is terrible ... > Apart from using a DOM to store the test results (Ugh!), the other > great XML sin committed in Puffin is that old canard: trying to use > XML as a programming language. Whereas the article on the IBM developerWorks site implied (or perhaps that should read "impLIEd") that the XML was just used as a method of parsing configuration parameters. *sigh* > For example, I just pulled this > fragment out of one of the sample test plans that comes with puffin: > > > > > > > > > > Which is exactly the type of thing I found the conflict with, with the action name tags above and the actual test actions in the action.xml file. > XML as a programming language is a dead-end! I quite agree. I think the program was named after the wrong bird ... dodo might be more appropriate. > I think it would be useful for you to re-read the last message in that > thread, from John J. Lee. Points of note include Yeah, that thread has some very useful info in it. Thanks for pointing it out. > 1. Webunit may be a better choice than Puffin (I can't say: I haven't > used it). I'm looking into WebUnit now (the mechanicalcat.net version, not the other one mentioned in the thread). > 2. If your requirements are as simple as indicated, then you may find > it far more productive to roll your own using the python standard > library. This should only take a few hours for someone familiar with > the standard library (as your esteemed colleague certainly is :-). > Alternatively, try a Google Groups search of c.l.py for "automate > httplib" or "automate form". Looks like that's what WebUnit is geared towards, but it may need some tweaking for our work anyway. Looks like WebUnit's one of the primary candidates at the moment and small enough to be easily expanded on if necessary. > If time is of the essence, and nobody on the project has the > time/experience for the task, I am available for contract work at > reasonable rates ;-) Heh. :) Regards, Ben From davygrvy at pobox.com Wed Nov 12 17:38:08 2003 From: davygrvy at pobox.com (David Gravereaux) Date: Wed, 12 Nov 2003 14:38:08 -0800 Subject: Regular expression code implementation review between Tcl vs Python References: <394af34.0311110758.3b1781ea@posting.google.com> <3fb10cc1.7910169@News.CIS.DFN.DE> <394af34.0311112107.20b9a34f@posting.google.com> <394af34.0311120725.4ab9bb39@posting.google.com> Message-ID: Google_Post at slink-software.com (K_Lee) wrote: >David Gravereaux wrote in message news:... >> Google_Post at slink-software.com (K_Lee) wrote: >> >> >I guess the TCL original goal was also to support >> >Win16, DOS, etc. >> >> No it wasn't. Given whatever core an extension is loaded into, the >> extension grabs the function table from the core it is loaded into. >> >> Say for example I build all of Tcl statically into my application (kinda >> dumb, but let's just say). If I try to load an extension into it, where is >> it supposed to get the Tcl functions it needs? Do you see the issue Stubs >> solves? >> > > >Ok, David, I understand better now. > >(Putting on my monday morning quarterback hat.) > >If the original design specifies that > * If you load extension with .so/dll, you are required > load tcl from .so/dll. >then we can get rid the stub interface, right? Yes, I think so. But still extensions would get locked to a named shared library. For example, loading a BLT extension which was linked against tcl83.lib (implicit) into tclsh84 will breach and crash. Either way with or without Stubs, implicit linking is still available. The EXTERN macro in the prototypes exports them all. >That doesn't sound like an unreasonable requirement for >people who use any tcl + extension. It's real easy to use, though. 1) compile with -DUSE_TCL_STUBS and link with tclstub8X.(lib|a) 2) Use this in the extension's exported *_Init as the first call: #ifdef USE_TCL_STUBS if (Tcl_InitStubs(interp, TCL_VERSION, 0) == NULL) { return TCL_ERROR; } #endif Beyond that, you don't need to think about it. You can even extend the Stubs concept for applications that embed Tcl. Steps would be: 0) same as #1 above. 1) Knowing the path to a certain Tcl dll/so at or greater than the version you require, dlopen/LoadLibrary it. 2) Get the address for Tcl_CreateInterp from the outside with dlsym/GetProcAddress 3) make the first interp 4) call Tcl_InitStubs (code from tclstub8x.(lib|a) in us) 5) call Tcl_FindExecutable (very important!) 6) Done, function table loaded. Tcl_DeleteInterp or use it... You have avoided 880 (or more) GetProcAddress calls to fill your own tables. Before Stubs came around, I was guilty of doing that :) Now you have an application that is upgradable from the outside, given that the path to the Tcl dll/so is settable or auto-discovered in some manner. >I still think Tcl'folks did a great jobs, just like to know the >trade off vs. features better. It gets even better with extensions that export a Stubs table. You can build extensions for extensions :) Witness: #undef TCL_STORAGE_CLASS #define TCL_STORAGE_CLASS DLLEXPORT EXTERN int Gui_irc_Init (Tcl_Interp *interp) { #ifdef USE_TCL_STUBS if (Tcl_InitStubs(interp, "8.3", 0) == NULL) { return TCL_ERROR; } #endif #ifdef USE_ITCL_STUBS if (Itcl_InitStubs(interp, "3.1", 0) == NULL) { return TCL_ERROR; } #endif new IRCWindowsItclAdapter(interp); return TCL_OK; } Using the services of [Incr Tcl] as well as Tcl, that extension declares class methods for this script: itcl::class IRC::ui { constructor {args} { _initUI } destructor { _destroyUI } public { method destroy {} {itcl::delete object $this} method echo {} @irc-ui-echo method window {} @irc-ui-window method menu {} @irc-ui-menu method hotkey {} @irc-ui-hotkey method alias {} @irc-ui-alias method channel {} @irc-ui-channel method query {} @irc-ui-query method chat {} @irc-ui-chat method queries {} @irc-ui-queries method chats {} @irc-ui-chats method say {} @irc-ui-say method input {} @irc-ui-input } private { method _initUI {} @irc-ui-construct method _destroyUI {} @irc-ui-destruct } } The '@irc-ui-*' names refer to Tcl_CmdObjProcs set by the extension with Itcl_RegisterObjC(). IMO, Stubs does not stop at the core. >K Lee -- David Gravereaux [species: human; planet: earth,milkyway(western spiral arm),alpha sector] From radam2 at tampabay.rr.com Tue Nov 18 20:46:00 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Wed, 19 Nov 2003 01:46:00 GMT Subject: True inconsistency in Python References: <3FB8847F.6CB1BECA@alcyone.com> <3FB92086.9CBD0761@alcyone.com> <8qhirvgi2sf5l3vkfocq65mcb94c6pbb9s@4ax.com> <7rhjrvgefdpfkm15divsor9e3iktl0falh@4ax.com> <2IqdnVvoQ973IyeiRVn-hg@comcast.com> Message-ID: On Tue, 18 Nov 2003 19:50:49 -0500, "Terry Reedy" wrote: >[Prohibiting this scenario (import module and mask builtins there in) >has been suggested. I believe it was once approved and is still under >consideration but the change has the problem that there seem to be >legitimate uses.] It might conflict with existing programs that assign 'True = 1' and 'False = 0', I can see where that could be a very common occurrence for people who are new to Python. And once they learn about the True and False values, they may not go back and change the older programs. ie... if it'n not broke don't fix it. In other words, they leave them as is and move on to the next project. _Ronald Adam From gerrit at nl.linux.org Mon Nov 17 10:42:16 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 17 Nov 2003 16:42:16 +0100 Subject: plotting data against a time axis In-Reply-To: References: Message-ID: <20031117154216.GA17285@nl.linux.org> Alexander Schmolck wrote: > Gerrit Holl writes: > > zero experience, I don't know where to start. What makes it difficult > > is that I have a time axis instead of a simple integer x-axis. Gnuplot > > doesn't seem to be able to do this, or does it? > > > gnuplot > > G N U P L O T > Version 3.8j patchlevel 0 > last modified Wed Nov 27 20:49:08 GMT 2002 > > Terminal type set to 'x11' > gnuplot> help time > Ambiguous request 'time'; possible matches: > time/date > time_specifiers > timefmt > timestamp > > Not what you want? Hm, maybe it is, actually :). It seems my estimate was incorrect; to be fair, I assumed Gnuplot was used solely for plotting functions, not data. Maybe it is wise to invest some time in learning Gnuplot, I may be happy with it later as well. Thank you all (John, Alexander, Dennis, Paul) for the responses! Gerrit. -- 275. If any one hire a ferryboat, he shall pay three gerahs in money per day. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From casey at caseyporn.com Tue Nov 4 23:19:41 2003 From: casey at caseyporn.com (Casey Whitelaw) Date: 4 Nov 2003 20:19:41 -0800 Subject: XORing long strings opimization? References: <3ISpb.24447$BD3.4566933@juliett.dax.net> <%AWpb.24470$BD3.4569022@juliett.dax.net> Message-ID: Noen wrote in message news:<%AWpb.24470$BD3.4569022 at juliett.dax.net>... > Here is the result, if anyone wants it :) > It was quite quick indeed, It took me 10.3279999495 seconds to XOR > "a"*1000000 large string. Im going to XOR 700000000 mb sized files, so > if anyone know how to make it even faster, please tell me :) > > import string > def xorstring(s1,s2): > """ XOR string s1 with s2 """ > # Argument check > if not (type(s1) == type("")) or not (type(s2) == type("")): > raise TypeError, "Arguments are not strings" > if len(s1) != len(s2): > raise ValueError, "Size differs in strings" > # Xoring > > # Create lists > l1 = map(ord, s1) > l2 = map(ord, s2) > > # Xor it all together > xorlist = [] > xorlist = [chr(x ^ y) for (x, y) in zip(l1, l2)] > return string.join(xorlist,"") # Backward compatible Just fiddling around with the (excellent) suggestions already posted, and found a couple of things. Alex's suggestion using array is the fastest, but was slightly faster when using xrange() rather than enumerate(): def xor6(s1, s2): a1 = array.array("b", s1) a2 = array.array("b", s2) for i in xrange(len(a1)): a1[i] ^= a2[i] return a1.tostring() On my system, this XORs 500,000 characters in 0.39s, with Noen's original taking 0.67s. Using psyco produced a further ~3x speedup, reducing this to 0.14s. That's pretty fast! Casey From stephenlee at exe-coll.ac.uk Fri Nov 7 06:43:54 2003 From: stephenlee at exe-coll.ac.uk (stephenlee at exe-coll.ac.uk) Date: Fri, 7 Nov 2003 11:43:54 +0000 Subject: Request for simple a customisable Python editor Message-ID: I want to develop a simple Python program to edit source code that is persisted in a database (memo fields). The code to be edited is iHTML and SQL and I want syntax colouring and good basic features including tabs for multiple 'files' and searching. It will be a Win32 deployment. My question is can anyone recommend a good Python editor program that I can use as a starting point for customisation? I'd like to base it on Scintilla and wxPython (though I really want the easiest/fastest solution). Or does something already exist? I prefer to keep it simple and focused on our requirements so an full python IDE is probably not a good starting point. :) The requirements are bound to grow so a good architecture is important. Obviously I'll need source to add the required DB connectivity. So far I have Dave Kuhlman's wxEditor and Patrick O'Brien's Py family shortlisted. Cheers Steve Lee This mail has been scanned by Nortons Anti Virus Version 8 for Lotus Notes From gerson.kurz at t-online.de Fri Nov 21 13:04:37 2003 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Fri, 21 Nov 2003 18:04:37 GMT Subject: COM makepy broken in ActivePython 2.3.2? Message-ID: <3fbe51ff.47726500@news.t-online.de> I have problems getting "COM makepy" working in ActivePython 2.3.2. This is what happens when I start "COM makepy" from the Pythonwin Menu: PythonWin 2.3.2 (#49, Nov 6 2003, 10:18:20) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> Failed to execute command: from win32com.client import makepy;makepy.main() Traceback (most recent call last): File "C:\Python23\Lib\site-packages\Pythonwin\pywin\framework\toolmenu.py", line 103, in HandleToolCommand exec "%s\n" % pyCmd File "", line 1, in ? File "C:\Python23\Lib\site-packages\win32com\client\__init__.py", line 12, in ? import dynamic, gencache, pythoncom File "C:\Python23\Lib\site-packages\win32com\client\gencache.py", line 623, in ? __init__() File "C:\Python23\Lib\site-packages\win32com\client\gencache.py", line 52, in __init__ Rebuild() File "C:\Python23\Lib\site-packages\win32com\client\gencache.py", line 610, in Rebuild _SaveDicts() File "C:\Python23\Lib\site-packages\win32com\client\gencache.py", line 57, in _SaveDicts raise RuntimeError, "Trying to write to a readonly gencache ('%s')!" \ RuntimeError: Trying to write to a readonly gencache ('C:\TEMP\gen_py\2.3')! --------------------------------------------------- OK, so I figure it wants to write to C:\TEMP\gen_py (why? IIRC this used to be buried somewhere along the site-packages). I create the directory & import a class. This is what happens: Generating to C:\TEMP\gen_py\2.3\08EF934A-521D-4E29-A92F-0FDE92DDE9D6x0x1x0.py Failed to execute command: from win32com.client import makepy;makepy.main() Traceback (most recent call last): File "C:\Python23\Lib\site-packages\Pythonwin\pywin\framework\toolmenu.py", line 103, in HandleToolCommand exec "%s\n" % pyCmd File "", line 1, in ? File "C:\Python23\Lib\site-packages\win32com\client\makepy.py", line 362, in main GenerateFromTypeLibSpec(arg, f, verboseLevel = verboseLevel, bForDemand = bForDemand, bBuildHidden = hiddenSpec) File "C:\Python23\Lib\site-packages\win32com\client\makepy.py", line 273, in GenerateFromTypeLibSpec gencache.AddModuleToCache(info.clsid, info.lcid, info.major, info.minor) File "C:\Python23\Lib\site-packages\win32com\client\gencache.py", line 514, in AddModuleToCache mod = _GetModule(fname) File "C:\Python23\Lib\site-packages\win32com\client\gencache.py", line 590, in _GetModule mod = __import__(mod_name) File "C:\TEMP\gen_py\2.3\08EF934A-521D-4E29-A92F-0FDE92DDE9D6x0x1x0.py", line 12, in ? from win32com.client import Dispatch ImportError: cannot import name Dispatch --------------------------------------------------- Now when I try this: import win32com.client instance = win32com.client.Dispatch("...") it tells me that Dispatch is not found ???? I restart pythonwin & python2.3.2 & win32all "out of the box" before and didn't have any of these problems. So, is "COM makepy" broken in AP232? From bignose-hates-spam at and-benfinney-does-too.id.au Fri Nov 7 17:10:29 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 8 Nov 2003 09:00:29 +1050 Subject: Precise calculations References: <0e547e2582633f8ea23d0b5e5d337128@news.meganetnews.com> Message-ID: On 8 Nov 2003 08:26:07 +1050, Ben Finney wrote: > On Fri, 07 Nov 2003 13:17:44 GMT, Ladv?nszky K?roly wrote: >> Could anybody help me on how to do precise calculations with Python >> the way hand-held calculators do? > > Use rounding, e.g. as implemented by the str() function. Apologies; str() doesn't do rounding per se, it shows the float values with fewer significant digits without changing the internal value. -- \ "Once consumers can no longer get free music, they will have to | `\ buy the music in the formats we choose to put out." -- Steve | _o__) Heckler, VP of Sony Music, 2001 | Ben Finney From graham__fawcett at hotmail.com Thu Nov 13 14:52:27 2003 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 13 Nov 2003 11:52:27 -0800 Subject: Newby Question: Remove files older than 7 days from a directory References: Message-ID: "kbass" wrote in message news:... > I would like to remove file that are older than 7 days old from a directory. > I can do this in shell script rather easy but I would like to integrate this > functionality into my Python program. How can this be achieved? Which module > can be used to perform this tasks? Thanks! > > Shell Script example: find /path/to/dir -mtime +30 -exec rm '{}' \; > > > Kevin Well, one way would be import os os.system("find /path/to/dir -mtime +30 -exec rm '{}' \;") but that's cheating (and non-portable, of course). Gerhard's code is a great example, but it won't recurse into subdirectories like the find command does. For that you need the os.path.walk() or (in Python 2.3) the os.walk() function. The os.path.walk() version is notorious for its counterinuitiveness, hence the newer, friendlier version in the os module. I'd gladly recommend Joe Orendorff's 'path' module, which doesn't come with the Python Standard Library, but which you can download and include either in your site-packages directory, or just put it in the same directory as your application. The path module takes a more object-oriented approach than the walk() variants in the standard library. Example: import time from path import path seven_days_ago = time.time() - 7 * 86400 base = path('/path/to/dir') for somefile in base.walkfiles(): if somefile.mtime < seven_days_ago: somefile.remove() The path module is available at http://www.jorendorff.com/articles/python/path/ -- Graham From francisgavila at yahoo.com Tue Nov 4 17:01:44 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Tue, 4 Nov 2003 17:01:44 -0500 Subject: Mixing generators and recursion References: <3fa808c3.20995000@news.t-online.de> <3FA80AB2.2E4C17EE@engcorp.com> <3fa80eaa.22505703@news.t-online.de> Message-ID: "Gerson Kurz" wrote in message news:3fa80eaa.22505703 at news.t-online.de... > No, it has nothing to do with the pathname. Try this: > > def f(nested): > if not nested: > f(True) > else: > yield 42 > > for k in f(False): print k > > Step through it in the mind: > - f(False) gets called > - it is not nested, so f(True) gets called > - it is nested, so should yield 42 - but it doesn't! > - instead, you get an empty list. Computer's can't read our minds, though.... > def f(nested): > if not nested: F is false so... > f(True) ...call function f(True), which returns a *generator*... ...which is never bound to anything, so the refcount goes to 0. > else: > yield 42 Above never gets executed by anything at all. Look: >>> def g(): ... yield 'Hello there!' ... >>> type(g) >>> g.next() Traceback (most recent call last): File "", line 1, in ? g.next() AttributeError: 'function' object has no attribute 'next' >>> G = g() >>> type(G) >>> G.next() 'Hello there!' >>> See the difference? What you want something like: def f(nested): if not nested: for v in f(True): yield v else: yield 42 for k in f(False): print k # 42 I.e., you must explicitly iterate the generator. No 'yield' ever yields without a next() asking first. (That next() call can be implicit or explicit, but it's still always there.) -- Francis Avila From a.neudecker at uni-bonn.de Sun Nov 16 13:40:47 2003 From: a.neudecker at uni-bonn.de (Andreas Neudecker) Date: Sun, 16 Nov 2003 19:40:47 +0100 Subject: +/-infinity in Python? In-Reply-To: References: Message-ID: Hello Peter, Magnus, thanks for your hints. I will read the PEPs first, because I need compatibility at least for Linux and Windows ... Kind regards Andreas Andreas Neudecker wrote: > Hi. > > Is there anything like +infinity and -infinity available in Python, and > can it be used in comparisons together with int or float numbers? > > Regards > > > Andreas > > From tdelaney at avaya.com Wed Nov 5 19:02:18 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 6 Nov 2003 11:02:18 +1100 Subject: alwayssortedlist (was Re: On PEP 322 (ireverse)) Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DEDF6094@au3010avexu1.global.avaya.com> > From: Alex Martelli [mailto:aleaxit at yahoo.com] > > Ah, a British vs American nuance, I suspect. "effective" > (according to > American Heritage) only means "it does the job" -- according > to the British > "Chalmers 21th Century Dictionary", it may also have such > connotations as > "producing a pleasing effect; impressive, striking". Guess I > _should_ have > said "efficient" instead and avoided the "transatlantic > nuances" issue. No idea what either the yanks or the poms say about it. Mine is an Australian point of view :) For me, at a technical level, "effective" means that it does the job correctly. There are various levels of "effectiveness". My current project deals with discovering layer 2 network devices (among other things). For me, the level of "effectiveness" of the discovery is defined as the number of devices discovered out of the total number that are in the address range to be tested. The simplest method, and guaranteed 100% "effective" at discovering contactable devices, is to simply do a ping sweep of the entire address range. However, this can often take several days. One of my primary aims is to reduce the time required (number of addresses tested), but still have a very "effective" discovery e.g. only scan 10% of the address space, but still find near 100% of the devices out there. "Elegance" OTOH has the connotations for me that "Chalmers 21th Century Dictionary" appears to give for "effective". A method that scanned only 10% of the address space, but was 100% "effective" is an "elegant" solution (although the actual implementation of the method may not be). Tim Delaney From googlegroups at spacerodent.org Sun Nov 23 02:35:56 2003 From: googlegroups at spacerodent.org (Dennis Roberts) Date: 22 Nov 2003 23:35:56 -0800 Subject: Help with script with performance problems Message-ID: I have a script to parse a dns querylog and generate some statistics. For a 750MB file a perl script using the same methods (splits) can parse the file in 3 minutes. My python script takes 25 minutes. It is enough of a difference that unless I can figure out what I did wrong or a better way of doing it I might not be able to use python (since most of what I do is parsing various logs). The main reason to try python is I had to look at some early scripts I wrote in perl and had no idea what the hell I was thinking or what the script even did! After some googling and reading Eric Raymonds essay on python I jumped in:) Here is my script. I am looking for constructive comments - please don't bash my newbie code. #!/usr/bin/python -u import string import sys clients = {} queries = {} count = 0 print "Each dot is 100000 lines..." f = sys.stdin while 1: line = f.readline() if count % 100000 == 0: sys.stdout.write(".") if line: splitline = string.split(line) try: (month, day, time, stype, source, qtype, query, ctype, record) = splitline except: print "problem spliting line", count print line break try: words = string.split(source,'#') source = words[0] except: print "problem splitting source", count print line break if clients.has_key(source): clients[source] = clients[source] + 1 else: clients[source] = 1 if queries.has_key(query): queries[query] = queries[query] + 1 else: queries[query] = 1 else: print break count = count + 1 f.close() print count, "lines processed" for numclient, count in clients.items(): if count > 100000: print "%s,%s" % (numclient, count) for numquery, count in queries.items(): if count > 100000: print "%s,%s" % (numquery, count) From johan at weknowthewayout.com Fri Nov 21 07:07:08 2003 From: johan at weknowthewayout.com (Johan Holst Nielsen) Date: Fri, 21 Nov 2003 13:07:08 +0100 Subject: Analyse of PDF (or EPS?) In-Reply-To: References: <3fbcc67e$0$9836$edfadb0f@dread14.news.tele.dk> Message-ID: <3fbe000f$0$9791$edfadb0f@dread14.news.tele.dk> Grzegorz Makarewicz wrote: > Johan Holst Nielsen wrote: > >> Hi, >> >> Is there any Python packages to analyse or get some information out of >> an PDF document... >> >> Like where the text are placed - what text are placed - fonts, >> embedded PDFs/fonts/images etc. >> >> Please let me know :) >> >> Regards, >> Johan >> > > http://www.trisoft.com.pl/~mak/wxpdf.zip > > My first attempt to decode PDF-s with SWIG-ged xpdf, requires sources of > python and wxPython - binaries for python22 (windows) are included. Hmmm http://www.trisoft.com.pl/~mak/wxpdf.zip Not Found The requested URL /~mak/wxpdf.zip was not found on this server. :( Did I get the wrong URL :( Regards, Johan From aleax at aleax.it Mon Nov 17 10:51:59 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 17 Nov 2003 15:51:59 GMT Subject: Books I'd like to see References: <2259b0e2.0311132223.11af146a@posting.google.com> Message-ID: Dave Benjamin wrote: > In article , Alex Martelli wrote: >> Michele Simionato wrote: >> ... >>> But Python is designed in such a way that a lot of it can be taught >>> without talking about objects. Yes, you are right that in its heart >>> it is very strongly object oriented (maybe even more than Java or Ruby), >> >> I don't know about "more than Ruby" -- Ruby's pretty thoroughly OO, too. >> I'd call it a wash. > > Ruby certainly claims to be more OO (and if Smalltalk is your definition > of OO, it's a logical conclusion). Of course, everyone has a different > definition of what OO really is. Including Alan Kay. =) I'm familiar with Ruby's claims, but, as methods/functions aren't really first-class objects there, I don't necessarily buy into them. >>> other hand, if you already knew OOP from another language, then you >>> are an experienced enough programmer and you can learn Python from >>> the Nutshell, isn't it? >> >> But the Nutshell only gets into OO _after_ it has covered functions, flow >> control, etc; it doesn't _start_ from OO, which is the original poster's >> request. > > Was this a conscious decision? If so, what were your motivations behind > procedural-first vs. objects-first? You can productively use Python without understanding nor using 'class'. Sure, you'll be defining and using objects all the time, but that's much like Monsieur Jourdain's "speaking prose for over forty years" without knowing he was doing so... not necessarily an issue. On the other hand, functions and flow control (and other minutiae:-) _are_ indispensable, so, there would be nothing truly gained by introducing 'class' before them. Alex From t_therkelsen at hotmail.com Fri Nov 28 10:40:54 2003 From: t_therkelsen at hotmail.com (Troels Therkelsen) Date: 28 Nov 2003 15:40:54 GMT Subject: python-dev Summary for 2003-10-16 through 2003-11-15 References: Message-ID: In article , Brett C. wrote: > This is the twenty-eighth and twenty-ninth summaries written by Brett > Cannon (does anyone even read this?). I do. As said elsewhere in this thread, and I agree with this, the summaries you write have just the perfect mix of cold facts and editorial musings. I lurk on python-dev, so I know just how hard it is to keep track of everything, and I must say I think you're doing a great job. /Troels Therkelsen From nospam at nowhere.hu Mon Nov 24 14:33:30 2003 From: nospam at nowhere.hu (Miklós) Date: Mon, 24 Nov 2003 20:33:30 +0100 Subject: 2.2.2 Annoyance References: Message-ID: Michael Hudson wrote in message news:m37k1pzkjw.fsf at pc150.maths.bris.ac.uk... > "Mikl?s" writes: > > > """ > > __getitem__(self, key) > > Called to implement evaluation of self[key]. For sequence types, the > > accepted keys should be integers and slice objects. Note that the special > > interpretation of > > """ > > I think this is talking about implementing __getitem__, not calling it > directly. Historically these things have been quite different, though > they are becoming less so. > Well, I've never been really into the guts of Python ... but could you shed some light for me on that why these two things are different? What I experienced was this "feature" broke my code (actually it was in a 3rd party code library) and it took a while for me to recognize the documentation was wrong (or whatever, depending on your explanation..) and slice objects shouldn't be passed to __getitem__ that way in Python 2.2 (and that this works for Python 2.3) > > 2.2.3 will not make any difference on this point. Well, then my patches will stay and slow down things a bit. Cheers, Mikl?s > > Cheers, > mwh > > -- > ARTHUR: Don't ask me how it works or I'll start to whimper. > -- The Hitch-Hikers Guide to the Galaxy, Episode 11 From DmitryPoplavsky Sat Nov 8 05:25:41 2003 From: DmitryPoplavsky (Dmitry Poplavsky) Date: Sat, 08 Nov 2003 12:25:41 +0200 Subject: New BlackAdder release ( Python IDE ) Message-ID: BlackAdder 1.0-031106 for Python development on Windows and Linux Rancho Santa Margarita, CA -- 8 November 2003 -- theKompany.com, producers and distributors of high-quality open source and commercial Linux software, are pleased to announce the availability of BlackAdder 1.0, a Windows/Linux UI development environment for Python based on Qt. BlackAdder combines a visual design environment with debugging, syntax highlighting, ODBC interfaces and extensive HTML documentation into a comprehensive platform for developing Python applications with PyQt. BlackAdder is an exciting product for rapidly developing applications on Linux or Windows using the popular Python language. Besides being a powerful IDE with an extensive array of tools to make developing your application quick and easy. BlackAdder is tightly integrated with PyQt which is a set of bindings for Python to allow you to make use of the popular Qt multi-platform windowing toolkit from Trolltech. Our optional Business Edition gives you a full commercial license for both PyQt and Qt as used from BlackAdder. Features: * Integrated Qt Designer * Syntax highlighting text editor * Supports the latest versions of Python, PyQt and Qt * eGenix.com mx Extensions for ODBC access from Python have been included. * Integrated Debugger * The debugger allows class instance objects to be displayed. * No restrictions are placed on the types of files that can be included in a project. * Project Explorer for adding existing file sets to a project * Extensive project management capability * Integrated CVS support * and much more& BlackAdder can be purchased or free demos downloaded from www.thekompany.com/products/blackadder. Regards Dmitry. From bignose-hates-spam at and-benfinney-does-too.id.au Tue Nov 18 02:22:01 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 18 Nov 2003 18:12:01 +1050 Subject: True inconsistency in Python References: <3FB8847F.6CB1BECA@alcyone.com> <83bjrvcm92o6l2gte1nbehrpvofm0r5i88@4ax.com> Message-ID: On Tue, 18 Nov 2003 07:15:01 GMT, Ron Adam wrote: > I believe the words 'True' and 'False' need to be treated the same as > the digits 1, 2, 3, ... The values of the digits do not change. We > depend on them not changing. Possibly so. For myself, I think it's good that they exist at all now. Incremental improvement toward a canonical Boolean type is good. - We now have a separate 'bool' type. - We now hove True and False singleton objects of type 'bool'. - Boolean expressions now evaluate to one of these two objects. These are all quite recent in Python. Perhaps immutable Boolean values will be in a future Python version. However, I don't see that it's a pressing need. Assigning a new value to None is possible (until recently, it didn't even generate a warning). How much Python code does this break? How many potential errors does it cause? My guess would be few. Same for the True and False values (and the numbers, if they were mutable). There are many ways to shoot yourself in the foot in Python, if you try hard enough. This is one of them. Acknowledge its existence, acknowledge that you'd be crazy to do it, and move on. -- \ "Yesterday I parked my car in a tow-away zone. When I came back | `\ the entire area was missing." -- Steven Wright | _o__) | Ben Finney From aleax at aleax.it Fri Nov 7 12:13:33 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 07 Nov 2003 17:13:33 GMT Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> Message-ID: <1pQqb.432528$R32.14304849@news2.tin.it> Erik Max Francis wrote: > But reduce isn't simply intended for adding up numbers. It's for doing > any kind of reduction. However, so many of reduce's practical use cases are eaten up by sum, that reduce is left without real use cases to justify its existence. If you consider the couple of uses left in the standard library, for example... e.g., take cvs.py: quotechar = reduce(lambda a, b, quotes = quotes: (quotes[a] > quotes[b]) and a or b, quotes.keys()) ...a masterpiece of clarity, right? The simple Python alternative, quotechar = None for k in quotes: if not quotechar or quotes[k]>quotes[quotechar]: quotechar = k may be deemed boring, but then why not go for speed & concision with...: quotechar = max([ (v,k) for k,v in quotes.iteritems() ])[-1] ...?-) All 4 uses in csv.py are similar to this, and the one in difflib.py: matches = reduce(lambda sum, triple: sum + triple[-1], self.get_matching_blocks(), 0) is clearly best expressed in Python 2.3 as: matches = sum([ triple[-1] for triple in self.get_matching_blocks() ]) The only other uses are in Lib/test/ -- and even there, apart from tests of reduce itself, all are "reduce(add..." [i.e., sum!] save for *one*...: def factorial(n): return reduce(int.__mul__, xrange(1, n), 1) even in that one case (and apart from the confusing choice of having factorial(n) return the factorial of n-1...), the most simplistic implementation: def fac(n): result = 1 for i in xrange(2, n): result *= n return result is only 3 times slower, and, if one is in a hurry, recursion and memoization are obviously preferable: def facto(n, _memo={1:1}): try: return _memo[n] except KeyError: result = _memo[n] = (n-1) * facto(n-1) return result the performance numbers being: [alex at lancelot bo]$ timeit.py -c -s'import facs' 'facs.factorial(13)' 100000 loops, best of 3: 10.3 usec per loop [alex at lancelot bo]$ timeit.py -c -s'import facs' 'facs.fac(13)' 10000 loops, best of 3: 32 usec per loop [alex at lancelot bo]$ timeit.py -c -s'import facs' 'facs.facto(13)' 1000000 loops, best of 3: 1.26 usec per loop > Yes, I'm sure specific reductions based on summing are faster than using > reduce. But that goes without saying. Furthermore, Numeric is not > builtin to Python, so that seems a red herring to me. Either you should > compare builtins to builtins, or not. If you want APL-ish functionality with Python, Numeric is where you'll find it (one day numarray, Numeric's successor, may finally gain entrance into the standard library, but, don't hold your breath...). But comparing plain Python code to a built-in that's almost bereft of good use cases, and finding the plain Python code _faster_ on such a regular basis, is IMHO perfectly legitimate. If a built-in gives me obfuscated or slow code, where plain good old "let's code it out in Python" gains clarity or speed, then it's time for that built-in to go. 'reduce' exists for purely legacy reasons, and, IMHO, would count as a wart were it not for Python's admirable determination to keep old code running (however, even that determination can be overdone, and I look forwards to the 3.0 release where old by-now-unwarranted built-ins can be put out to pasture...). Alex From andrew-pythonlist at puzzling.org Sun Nov 2 23:29:15 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Mon, 3 Nov 2003 15:29:15 +1100 Subject: Weird asyncore behaviour In-Reply-To: <3fa58d78_1@news.adelaide.pipenetworks.com> References: <3fa58d78_1@news.adelaide.pipenetworks.com> Message-ID: <20031103042915.GB4667@frobozz> On Mon, Nov 03, 2003 at 09:34:23AM +1030, Freddie wrote: > Hi, > > I've been playing around with asyncore for one of my projects, currently > using it to fetch HTTP pages without blocking things. Having a few > issues, though. With the code below, I would start a new async_http > instance with "async_http(url, returnme)". If it encountered a redirect, > that object would start a new one as "async_http(url, returnme, > seen=self._seen)" to remember what URLs it had seen. The problem is that > after a while (usually after several async_http objects are active at > once), newly created async_http objects would have the seen parameter > with URLs filled in already! I have absolutely no idea how that could be > happening :\ I 'solved' it by explicitly passing "seen={}" for new > objects, but I would still like to know why this is happening :) > > Freddie > > > class async_http(asyncore.dispatcher): > def __init__(self, parent, returnme, url, seen={}): That line is the problem. Default arguments are only created once, at function definition time, not every time the function is called. So the same 'seen' dictionary is being used for all async_http instances. Generally, rather than using mutable default arguments, do: def __init__(self, parent, returnme, url, seen=None): if seen is None: seen = {} ... -Andrew. From jdunnett81 at hotmail.com Wed Nov 12 11:18:30 2003 From: jdunnett81 at hotmail.com (Jeff Dunnett) Date: 12 Nov 2003 08:18:30 -0800 Subject: Pythom HTML Libraries Message-ID: Hello Everyone, I was wondering if anyone can point me to a good tutorial for the htmllib library? Hopefully something with some sample code. Thanks. Regards, Jeff From c.sette_NOSPAM_ at reddevils.it Fri Nov 7 10:22:28 2003 From: c.sette_NOSPAM_ at reddevils.it (Carlo Sette) Date: Fri, 07 Nov 2003 16:22:28 +0100 Subject: XML DOM References: Message-ID: Thank you all, my XML document is corrupted.... Sorry. Carlo From edreamleo at charter.net Sat Nov 8 08:10:47 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Sat, 8 Nov 2003 07:10:47 -0600 Subject: Leo 4.1 beta 1 An outlining editor References: Message-ID: > Leo is a killer Python application! Thanks for these kind words :-) Working on Leo is one of the great joys of my life. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From rmunn at pobox.com Fri Nov 21 10:26:56 2003 From: rmunn at pobox.com (Robin Munn) Date: Fri, 21 Nov 2003 15:26:56 GMT Subject: best Wx editor References: Message-ID: RN wrote: > I come from M$ Visual Studio background. > > The editors, compilers, etc, are awesome in Linux. > > I have still not come across a intuitive graphical debugger. > > The only debbuger that came close TotalView from Etnus - its damn expensive. > > I have tried DDD, KDevelop, etc. > > Any recommendations? Can't point you in the direction of a really intuitive graphical debugger, I'm afraid. But I do have a recommendation for you. Why not help improve an existing one? Pick an open-source debugger that was close to what you wanted to see, join the mailing list, and start discussing possible improvements. Tell them your background, and that you were expecting the debugger to work like *this*, but it did *that* instead. Help them make it more intuitive. If they don't get feedback from users, how will they know what the users were expecting the tool to do? -- Robin Munn rmunn at pobox.com From M.Boeren at guidance.nl Wed Nov 19 07:18:35 2003 From: M.Boeren at guidance.nl (Marc Boeren) Date: Wed, 19 Nov 2003 13:18:35 +0100 Subject: List of lists Message-ID: <7BE0F4A5D7AED2119B7500A0C94C58AC3D6E64@DELLSERVER> > I was wondering if anyone knows a short way to do the following.. > I have 2 lists of list..eg > [('a','b','c'),('k','-','l'),('1','2','3')] > [('a','b','c'),('k','-','x'),('1','4','3')] > > I want to comapre the two lists of lists and count the number of > times the sublists match. In the above example its 1 Anytime you need to do something on corresponding items in two lists, you should think of zip(), as this binds the matching elements together. Look at: >>> a = [('a','b','c'),('k','-','l'),('1','2','3')] >>> b = [('a','b','c'),('k','-','x'),('1','4','3')] >>> [aa==bb for aa, bb in zip(a,b)] [True, False, False] >>> sum([aa==bb for aa, bb in zip(a,b)]) 1 the list-comprehension [aa==bb for aa, bb in zip(a,b)] can be used to count how many items matched, but is also useful to determine exactly which items matched. Cheerio, Marc. From bokr at oz.net Mon Nov 3 21:49:10 2003 From: bokr at oz.net (Bengt Richter) Date: 4 Nov 2003 02:49:10 GMT Subject: nearest neighbor in 2D References: Message-ID: On Sun, 02 Nov 2003 22:12:47 -0600, John Hunter wrote: > >I have a list of two tuples containing x and y coord > > (x0, y0) > (x1, y1) > ... > (xn, yn) > >Given a new point x,y, I would like to find the point in the list >closest to x,y. I have to do this a lot, in an inner loop, and then I >add each new point x,y to the list. I know the range of x and y in >advance. Are you trying to find closest location to a mouse cursor as it moves, and then adding a point when there's a click? I.e., your particular use case might suggest a strategy that's different from, e.g., what you'd do if each new point's coordinates where read from file or came from a generator, and you had exactly one search leading to exactly one update of the set. And also what you wanted to do with the completed set. > >One solution that comes to mind is to partition to space into >quadrants and store the elements by quadrant. When a new element >comes in, identify it's quadrant and only search the appropriate >quadrant for nearest neighbor. This could be done recursively, a 2D >binary search of sorts.... This might be a way of pruning, but you'd have to take into account that nearest square doesn't guarantee nearest diagonal distance. Just blathering off the top of my head, ... I think I would try dividing x and y into maybe a 16*16 grid of squares. A new point will fall into one of those, and then if you find some existing points in that square, you could brute force find the closest (remembering that comparing squared radial distances works as well as comparing their square roots ;-) and then see if that shortest distance can reach into any adjacent squares, and search those too if so, since there could be a point just the other side of the border, or diagonally across an adjacent corner that could be closer than your currently determined distance. You could keep info about points in a square in lists or dicts (16*16 might be sparsely populated, best in a dict of squares accessed by grid coordinates (i.e., 4 bits apiece, maybe as tuple or combined as a single number (but then you could use a list pre-populated with None's instead of a dict, so either way). I guess in the extreme you could compute a complete table of nearest point coordinates for every possible x,y point, so you'd have a raster map of voronoi regions, with each region colored by the coordinates of its nearest point. The more points you had, the less info would have to be updated for each new point. I wonder when the crossover would occur ;-) > >Can anyone point me to some code or module that provides the >appropriate data structures and algorithms to handle this task >efficiently? The size of the list will likely be in the range of >10-1000 elements. > What are the ranges of x and y? Regards, Bengt Richter From roy at panix.com Tue Nov 25 11:36:48 2003 From: roy at panix.com (Roy Smith) Date: Tue, 25 Nov 2003 11:36:48 -0500 Subject: best practices - how to organize classes References: <59e5b87.0311250821.629674f0@posting.google.com> Message-ID: In article <59e5b87.0311250821.629674f0 at posting.google.com>, mirandacascade at yahoo.com (Miranda Evans) wrote: > Seeking reference material (a url, a book, an article) that offers > advice and guidelines for organizing classes within files. > > For example, assume two classes: > 1) SuperABC - a superclass > 2) InheritorABC - a class that inherits from SuperABC > > I can think of two ways of organizing these classes within files: > 1) One class per file: > - the file SuperABCClass.py contains the source code for the class > SuperABC > - The file InheritorABCClass.py contains the source code for the class > InheritorABC > - InheritorABC imports SuperABCClass > 2) Grouping classes into one .py file: > - the file GroupedABCClasses.py contains the source code for the class > SuperABC and the source code for the class InheritorABC > > Seeking reference material that might answer the questions: > When does it make sense to employ the one-class-per-file technique? > When does it make sense to group classes into one .py file? > What are the tradeoffs of using one-class-per-file technique vs the > grouping classes into a single file technique? I don't think there is any single correct answer. It's more of a judgement call. In general, I'll put more than one class in a single source file only if they formed a logically self-contained unit of inter-dependant classes. Kind of like an inner class in C++. For example, let's say I was building a RedBlackTree class, and I needed a TreeNode class to store the individual nodes. I would probably put both classes in one file. If I needed to define exception classes, they would certainly go in the same source file as the class which generated those exceptions. From nessus at mit.edu Tue Nov 11 13:18:25 2003 From: nessus at mit.edu (Douglas Alan) Date: Tue, 11 Nov 2003 13:18:25 -0500 Subject: Python's simplicity philosophy References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: "Dave Brueck" writes: >> > Part of the problem here is that just saying "only one way to do >> > it" is a horrible misquote, and one that unfortunately misses IMO >> > some of the most important parts of that "mantra": >> Well, perhaps anything like "only one way to do it" should be removed >> from the mantra altogether, since people keep misquoting it in order >> to support their position of removing beautiful features like reduce() >> from the language. > You're joking, right? It is one of the key aspects of Python that makes the > language such a good fit for me. Changing the philosophy because a *few* > people don't "get it" or because they are apt to misquote it seems crazy. Of course I am not joking. I see no good coming from the mantra, when the mantra should be instead what I said it should be: "small, clean, simple, powerful, general, elegant" -- not anything like, "there should be only one way" or "one right way" or "one obviously right way". I have no idea what "one obviously right way" is supposed to mean (and I don't want to have to become Dutch to understand it) without the language being overly-restricted to the point of uselessness like FP is. Even in FP, I doubt that there is always, or even typically one obviously right way to accomplish a goal. To me, there is never *one* obviously "right way" to do anything -- the world (and the programming languages I chose to use) offer a myriad of possible adventures, and I would never, ever want it to be otherwise. |>oug From kkto at csis.hku.hk Mon Nov 10 01:48:22 2003 From: kkto at csis.hku.hk (Isaac To) Date: Mon, 10 Nov 2003 14:48:22 +0800 Subject: recursion vs iteration References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <7ihe1cn6of.fsf@enark.csis.hku.hk> Message-ID: <7i3ccwk9c9.fsf@enark.csis.hku.hk> >>>>> "David" == David Eppstein writes: David> Perhaps, for Fibonacci, they are almost the same. For the David> recursive vs iterative versions of 0-1 knapsack which I posted David> earlier in this thread, the same values are computed in the same David> places by the same formula, it's not tail-recursive because there David> are two subproblem values used in each instance of the formula David> (anyway we're in a Python group and Python doesn't optimize out David> tail recursions), and the recursive version computes them in a David> different order than the iterative one and doesn't compute as David> many of them. Hmm... don't keep your eye closed. I mean an *iterative* version can always be turned into a tail recursion, while you are not talking about the iterative version. You are talking about the recursive version, which can be turned into an iteration using a stack. This is what I said exactly: Isaac> since every iteration can be turned into a tail recursion without Isaac> losing efficiency (given the appropriate compiler optimization), Isaac> and every recursion can be turned into an iteration using a Isaac> stack To do this basically you turn your program into an interpretor performing the instruction cycle as a loop; and the stack needed is for the low-level implementation of the recursion. So instead of def f(n): if n == 0: # statement 1 return 1 # statement 2 else return f(n-1)*n # statement 3/4, recursion You'd write (untested code, depend on a stack with push and pop operations...) def f(n): s = Stack() state = [1,n,0] # [statement nr, value of n, return value slot] s.push(state) while true: # the loop implementing the instruction cycle state = s.pop() if state[0] == 1: # "if n == 0" if state[1] == 0: # if n == 0 state[0] = 2 # then goto statement 2 else: state[0] = 3 # else goto statement 3 s.push(state) else if state[0] == 2: # "return 1" if s.empty(): # if no more recursion return 1 # then return 1 laststate=s.pop() laststate[2] = 1 # else write 1 to return value slot s.push(laststate) else if state[0] == 3: # "f(n-1)" s.push([4, state[1], 0]) # prepare for return s.push([1, state[1]-1, 0]) # restart execution, n=n-1 else: # "return retval*n" if s.empty(): # if no more recursion return state[2]*state[1] # then return retval*n laststate=s.pop() laststate[2] = state[2]*state[1] # else write that to return value slot s.push(laststate) You can see it involves no recursion, and is completely mechanical. It works basically for all recursions, including the one you mentioned. Basically one go back to the principle in which a computer works. Of course, depending on circumstances it can be optimized a bit. The above only shows that recursion is not absolutely necessary. Regards, Isaac. From jsbenson at bensonsystems.com Wed Nov 19 16:58:16 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Wed, 19 Nov 2003 13:58:16 -0800 Subject: beeping under linux Message-ID: <035b01c3aee8$3d47b0a0$a90a500a@jsbwxp3> Re: ------------------------------ Date: 19 Nov 2003 19:41:28 +0000 From: Alexander Schmolck Subject: beeping under linux To: python-list at python.org Message-ID: Content-Type: text/plain; charset=us-ascii This is only partly a python question, but what is the easiest way to get python to (reliably) beep under linux? By reliably I mean that ``print "\b"`` won't do because it depends on the terminal settings -- so I guess I'm looking for some simple way to more or less directly access the internal speaker (maybe writing to something in /dev/). [The usage scenario is simply to have an effective way of signalling that a long running-process finshed, without me having to constantly look at the screen] 'as ------------------------------ How about playing a sound using a system() command? I had a similar problem about twenty years ago, and hooked my Commodore 64 up via a serial adapter to the extension port on the Tandem (minicomputer) terminal's auxiliary port. When a long-running compile finished, a script wrote a special string out to the terminal which was watched for by the C-64. Then the C-64 used his speech synthesizer to say something. I found that by passing special strings to the synthesizer, I could get a "Max Headroom", "T-t-t-t-talking 'bout my generation" or Porky Pig effect. None of my co-workers liked it, so it was used mostly at night. Another time I was using Tandy T-100 4-line LCD laptops which had a cassette start/stop switch port. I got a long-running sound effect of a crowd booing and hissing, left it in the cassette player controlled by a wire from the start/stop port and played the tape for a few seconds whenever the operator made a mistake. This was roughly about the time that the Macintosh appeared and took user interface in a completely different direction. I'm thinking of taking out a patent anyway, you never know. To cap this off, a major aerospace defense contractor I worked for had rigged up an ascii switch connected to the Tandem computer that ran part of their factory. A process on the Tandem polled the OS to verify that certain critical components were up, and if any weren't, it printed a string out to the ascii switch which detected the string and activated something like a foghorn. The programmers were conditioned to respond to the foghorn with immediate sprinting for the machine room, which was disconcerting the first time I experienced it. A less-invasive way to get your attention might be to use a GUI toolkit to put up a big, empty window and flash it light and dark. From sylphaleya at mailandnews.com Tue Nov 18 08:10:18 2003 From: sylphaleya at mailandnews.com (Manuel Huesser) Date: Tue, 18 Nov 2003 14:10:18 +0100 Subject: C++ extention References: <6b17fa95.0311180136.723d51b2@posting.google.com> Message-ID: Try to compile with g++ -fno-rtti Manuel From frr at easyjob.net Fri Nov 21 10:45:25 2003 From: frr at easyjob.net (Fernando Rodriguez) Date: Fri, 21 Nov 2003 16:45:25 +0100 Subject: Question about Objects References: Message-ID: On Fri, 21 Nov 2003 09:56:07 -0500, "campbell95" wrote: >This is what I get when I test it. Why does not return the >value of ? is obvious that has a value. I fear this >is a simple oversight but I've racked my brain for hours looking at online It is. ;-) >doc's and examples. Thanks for any help!! > >>Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on >win32 >>Type "copyright", "credits" or "license()" for more information. >>**************************************************************** >>IDLE 1.0 ==== No Subprocess ==== >>>>> >>>>> x = Test("Microsoft Sucks") >>>>> x.getSomething >>> Remember, this isn't VB: you can't leave the parens off when calling a method. There's no difference between subs and functions in Python, and you must include the parens if you want to _call_ the function and get the value. Otherwise you get the function. It makes sense, it just that you're used to the peculiar MS-way of doing things. Your mind will heal, don't worry. ;-) From jzgoda at gazeta.usun.pl Sun Nov 9 11:36:35 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 9 Nov 2003 16:36:35 +0000 (UTC) Subject: Ay Karamba! References: Message-ID: Lee Harr pisze: > Have you seen SuperKaramba for KDE? Wow! Yes, nearly a year ago... And my reaction was similar. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From aleax at aleax.it Thu Nov 13 10:58:49 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Nov 2003 15:58:49 GMT Subject: case-sensitivity References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> Message-ID: Ron Adam wrote: ... > 4: The editor or IDE matches what I enter to the names and then > substitutes the proper case of the name at some definitive point. > This ensures that the case is correct and the program compiles and > runs normally. If I choose a different editor then see #1 or #2. ... > correcting while editing. Number 4 is possible to do now, but I > don't know of any editors that currently do it. It would be a nice > option to include in one I think. Yes, looks like a nice idea for a middling-difficulty project with IDLE, and it would be useful even if made _particularly_ unintrusive (spelling correction would be done only on specific request, and only when feasible without ambiguity regarding e.g. standard library modules and names therein -- a really minimal part of [4], yet it would STILL save quite some trouble/hassle to those using it...). Alex From ods at strana.ru Fri Nov 28 13:24:30 2003 From: ods at strana.ru (Denis S. Otkidach) Date: Fri, 28 Nov 2003 21:24:30 +0300 (MSK) Subject: compile(unicode) & source encoding In-Reply-To: Message-ID: On Fri, 28 Nov 2003, Just wrote: J> > 2. Why there is now option to define encoding of source J> passed to J> > compile function? Yes, I can define encoding by prefixing J> my J> > code with '# -*- coding: %s -*-\n' % encoding, but it's not J> > handy. J> J> You can just pass a unicode string (in 2.3 at least), so you J> can do the J> decoding yourself. There is a big difference bitween oridinal (one byte per character) encoding and utf-8, so this breaks code dealing with 8-bit strings. -- Denis S. Otkidach http://www.python.ru/ [ru] From max at alcyone.com Fri Nov 7 06:35:53 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 07 Nov 2003 03:35:53 -0800 Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> Message-ID: <3FAB8399.687F2021@alcyone.com> Alex Martelli wrote: > Yeah, I know, speed isn't everything. But when the speed of a > perfectly > analogous operation drops by two times (from reduce to sum) or even > more when it drops by 50 times (from reduce on a list to Numeric.add. > reduce on a Numeric.array) one _does_ get a sense of when one's using > a language "reasonably idiomatically" -- within the design space of > that > language, within the pathways most often taken by the language's best > practitioners and therefore most likely to be solid and optimized. But reduce isn't simply intended for adding up numbers. It's for doing any kind of reduction. Yes, I'm sure specific reductions based on summing are faster than using reduce. But that goes without saying. Furthermore, Numeric is not builtin to Python, so that seems a red herring to me. Either you should compare builtins to builtins, or not. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Every time a friend succeeds, I die a little. \__/ Gore Vidal From try_vanevery_at_mycompanyname at yahoo.com Sat Nov 15 01:12:04 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Fri, 14 Nov 2003 22:12:04 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> <84fc4588.0311140319.3778de15@posting.google.com> Message-ID: "Emile van Sebille" wrote in message news:bp45ee$1ke39f$1 at ID-11957.news.uni-berlin.de... > > Hmmm... > > That 8% sounds familiar... something about Apple's market share in > PCs 10-15 years ago or Sony's in TVs about the same time. Python > should be as much a has-been in 10-15 years. Apple almost went under and is a decided minority computing platform today. The demand for Mac developers is way smaller than the damand for Windows developers. Can't comment on Sony TVs, I haven't shopped for TVs lately. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA Brandon's Law (after Godwin's Law): "As a Usenet discussion grows longer, the probability of a person being called a troll approaches one RAPIDLY." From aleax at aleax.it Tue Nov 11 06:17:21 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 11 Nov 2003 11:17:21 GMT Subject: Tinkering with builtins (was: Re: True, False, None) References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311110003.567dc235@posting.google.com> Message-ID: <5z3sb.5974$hV.297741@news2.tin.it> Michele Simionato wrote: > "John Roth" wrote in message news: >> There's a movement >> to make just about everything in the built-in scope immutable and >> not rebindable at any lower scope for performance reasons. > > I am a bit worried by this movement. While I have found no reason to twick > the builtins in production code, I have found specific situations where > the ability of tinkering with the builtins is extremely convenient. > Typically this happens in the debugging phase. For instance I have used > tricks such as modifying the `object` class to induce tracing capabilities > on all my classes, withouth touching my source code. > > So, I would be happy with the following: > > 1. by default builtins cannot be changed, resulting in a performance > benefit; > > 2. nevertheless, it is possible to use a command line switch to revert > to the current behavior. > > If the project is to kill option 2, then I would be unhappy :-( Sounds reasonable to me. If nailing down built-ins is seen as good _only_ for performance, then perhaps the same -O switch that already exists could be used. Personally, I think nailing down built-ins may also be good for clarity in most cases, so I would prefer a more explicit way to request [2]. However, we would then need a third file-extension besides .pyc and .pyo -- clearly you would not want the same bytecode for the "builtins nailed down" and "builtins can be modified" modes; and that might pose some problems -- so perhaps sticking to -O would be better overall. I think that discussing the possibilities here is productive only up to a point, so you might want to come to python-dev for the purpose, at least when some clarification of possibilities has been reached. Alex From joconnor at cybermesa.com Thu Nov 27 13:04:55 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Thu, 27 Nov 2003 11:04:55 -0700 Subject: if - else In-Reply-To: <871xrtr8yb.fsf@pobox.com> References: <871xrtr8yb.fsf@pobox.com> Message-ID: John J. Lee wrote: >Duncan Booth writes: > > > >>Jeff Wagner wrote in >>news:oanasvs703tipmup24qgc5toggte8uh67n at 4ax.com: >> >> >[...] > > >>> if SumOfNumbers = 10: >>> #If SumOfNumbers = 10, then set it's value to 1 >>> SumOfNumbers = 1 >>> >>> >[...] > >Classic example of a worse-than-useless comment: it just repeats the >code (even experienced programmers frequently fall into this trap, >though they're not usually quite so blatant about it ;-). > True, also someone's being careless with their code. if SumOfNumbers = 10: SumOfNumbers = 1 What happens with that? :) From peter at engcorp.com Tue Nov 11 10:11:05 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Nov 2003 10:11:05 -0500 Subject: Conversion of 24bit binary to int References: Message-ID: <3FB0FC09.BEFB0D95@engcorp.com> Idar wrote: > > Is there an effecient/fast way in python to convert binary data from file > (24bit hex(int) big endian) to 32bit int (little endian)? Have seen > struct.unpack, but I am unsure how and what Python has to offer. Idar I think the question is unclear. You say you've seen struct.unpack. So what then? Don't you think struct.unpack will work? What do you mean you are unsure how and what Python has to offer? The documentation which is on the web site clearly explains how and what struct.unpack has to offer... Please clarify. -Peter From bobx at linuxmail.org Sat Nov 8 14:53:45 2003 From: bobx at linuxmail.org (Bob X) Date: Sat, 08 Nov 2003 19:53:45 GMT Subject: Sleepycat DBXML included? References: Message-ID: "A.M. Kuchling" wrote in message news:K6udnWPoj7j42jCiRTvUqA at speakeasy.net... > On 08 Nov 2003 14:33:57 +0100, > Martin v. L?wis wrote: > > Where did you read that? > > http://www.sleepycat.com/company/releases/030724zope.shtml is a press > release, but it doesn't mention dbXML, only Berkeley DB. The original > poster must have misremembered. > > --amk > My mind is not what it used to be! : ) Bob From adalke at mindspring.com Tue Nov 18 01:12:51 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 18 Nov 2003 06:12:51 GMT Subject: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <7xoevcf1u2.fsf@ruckus.brouhaha.com> <7x7k1zc0si.fsf@ruckus.brouhaha.com> <61Ztb.3481$sb4.1708@newsread2.news.pas.earthlink.net> <7xk75ysycx.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin: > The change was that native lists will implement stable sort. My gripe > is that if native lists are required to sort stably and list-alikes > can sort unstably, then list.sort and listalike.sort act differently > in a way that can lead to subtle bugs. ... > > That's a statement only that list.sort shall be stable and > > not that all .sort() methods must be stable. > > It would be icky if some .sort() methods are required to be stable but > others are not. I've been thinking about this. I'm of two minds about it, both for and against. The 'for' side, which dominates, says that the only extra work is for those people who implement a version of Python. There will only be few of these, and the work needed to implement at least a rough cut at a stable sort is pretty minimal. Any user of a list-alike sort who is concerned about its stability or wants the code to work for pre-2.3 will use the DSU idiom. People who don't know about differences in how sort algorithms handle ties will have their sorts work "as expected". The 'against' side says, as you do, that having list.sort required to be stable now places an extra barrier to anyone else who implements a list-alike sort, because that sort should now also be stable. What mollifies the latter view is that some user-defined sorts won't have ties, so there will never be a problem. And some user-defined sorts will want a stable sort -- anything which sorts rows based on a column in a grid display must be stable. So there are only going to be a relatively few cases where this will be a problem. Besides, what I really want is a set of algorithms implemented independent of the container so that I can have a generic 'sort' function work on a user-defined container. At that point it would be trivial for a user-defined list-alike to implement its .sort() method as a call to the stable-sort algorithm, which further reduces the number of times when the expectation of a stable sort causes a problem. Hmmm.. To do this nicely would seem to require a 'swap' method on lists as otherwise there's a lot of movements when swapping two items in a list. > Note that the most obvious way to implement sort() in C is to call the > standard C library qsort function, which is unstable. And again I note that I've seen commercial software which made the expectation that C's qsort(3C) was ... well, not stable, but it assumed it would give the same results on different machines. That error was fixed by implementing their own sort algorithm. (It wasn't caught for years because there are very few ties in their data and even fewer people moved data from one platform to another.) My preference is for a stable sort. It works the right way for most cases, and no sort algorithm is going to do the right thing for all cases. (Hence the explosion of sort variants you rightly pointed out.) Andrew dalke at dalkescientific.com From CousinStanley at hotmail.com Sun Nov 9 10:04:15 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Sun, 9 Nov 2003 08:04:15 -0700 Subject: Get more from Google (was: programming languages (etc) "web popularity" fun) References: <9Vvob.74272$e5.2721707@news1.tin.it> Message-ID: | *Google Pocket Guide* is for civilians, | *Google Hacks* for programmers. | .... Perhaps in the future we can look forward to Google dot Net for the Masses .... http://www.pcworld.com/news/article/0,aid,113209,tk,dn103103X,00.asp -- Cousin Stanley Human Being Phoenix, Arizona From jeder at earthlink.net Fri Nov 28 03:51:53 2003 From: jeder at earthlink.net (Ryan Spencer) Date: Fri, 28 Nov 2003 08:51:53 GMT Subject: Blinky Program Message-ID: Hello again Everyone, I spent a small amount of time recently writing a program that "blinks" text. I did it by first having a user input a string, sys.stdout.write-ing the string, then backing up judging by the number of characters the string has, re-stdout's over it with blank spaces (judged again by it's character count), and then backs up again in a never ending while loop. It keeps each blink .5 seconds spaced as well, and all in the same position. Here is the code. [start code] #blinky.py #Make a blinking user inputed (strings) character by using self made "blinky" #function. strings = raw_input("Please enter something to blink: ") #blinky(string_argument, time_pause) def blinky(strings1, pause): import string,time,sys string_length = len(strings1) replacement = string.replace(strings1,strings1," ") float(pause) while 1: sys.stdout.write(strings1) sys.stdout.flush() time.sleep(pause) sys.stdout.write("\b"*string_length) sys.stdout.write(" "*string_length) sys.stdout.flush() time.sleep(pause) sys.stdout.write("\b"*string_length) blinky(strings, .5) [end code] My question is that I was recently informed by someone that I could help free up some memory usage by alleviating the sys.stdout.flush's in the code, but I need those in order to keep the "blinking" text in place. Is there any way I can actually free up memory usage in the terms of the sys.stdout.flush that any of you can notice? I'm simply curious now after being informed. Thanks again, ~Ryan From bwm at acm.org Mon Nov 24 19:38:23 2003 From: bwm at acm.org (Bernhard Mulder) Date: Tue, 25 Nov 2003 00:38:23 GMT Subject: Leo problems ... In-Reply-To: References: Message-ID: <2wxwb.51928$T8.37611@newssvr25.news.prodigy.com> 1. Look at the installation directory for src\leo.py. Use a DOS box to start the python interpreter (for the regular install it is c:\python23\python.exe) with leo.py as the first argument. If LEO does not come up, you should have a stack trace which should help identify the source of your problem. The install starts pythonw.exe if you double click an icon. This does not open a DOS window. Not sure if the traceback just disappears, or how to get a hold of it in this case. 2. Most LEO problems are reported in (the general) discussion forums of leo.sourceforge.net. For error reports, the author is normally quite responsive. Jeff Wagner wrote: > Hello, > > I tried to send this message to the author of Leo and kept getting a ChoiceMail message telling me > that I had to reply to that message to get my message read. I did that four times but it doesn't > seem to be working (I keep getting the same stupid message from ChoiceMail). Therefore, I will post > my question here in hopes that someone may have an answer. > > I just installed Leo on my WinXP Pro machine to try it out and it won't run. I first tried the > latest version 4.1b2 then tried 4.04. It installs ok but when I try to run it using the Icon (doulbe > click on icon link), I get the hour-glass icon then it goes away ... like nothing happened. > > I have ActiveState Python2.3 installed. Any idea why this program won't come up? > > Thanks From jkrepsBEAR at FISHneb.rr.com Sat Nov 1 13:55:18 2003 From: jkrepsBEAR at FISHneb.rr.com (GrayGeek) Date: Sat, 01 Nov 2003 18:55:18 GMT Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <8nlnpvcsgodtmlpfng7rtf27r1s7hi56ph@4ax.com> <87d6cjope5.fsf@pobox.com> <87he1vsopi.fsf@pobox.com> <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> Message-ID: Andrew Dalke wrote: > Anton Vredegoor" : >> The more territory modern science covers, the more it becomes clear >> that the known parts of the universe are only a small part of what is >> "out there". > > But as Stephen pointed out, the new things we find are new > in terms of arrangement but still following the same laws of physics > we see here on Earth. (There *may* be some slight changes in > cosmological constants over the last dozen billion years, but I > haven't followed that subject.) These arrangements may be > beyond our ability to model well, but there's little to suggest > that in principle they couldn't be. (Eg, QCD could be used to > model the weather on Jupiter, if only we had a currently almost > inconceivably powerful computer. Running Python. ;) Probably not even with Python! :-( Weather (3D fluid dynamics) is chaotic both here on Earth and on Jupiter. As Dr. Lorenz established when he tried to model Earth's weather, prediction of future events based on past behavior (deterministic modeling) is not possible with chaotic events. Current weather models predicting global or regional temperatures 50 years from now obtain those results by careful choices of initial conditions and assumptions. In a chaotic system changing the inputs by even a small fractional amount causes wild swings in the output, but for deterministic models fractional changes on the input produce predictable outputs. > >> So "objectively" science gains more knowledge, but >> relatively speaking (seeing it as a percentage of that what is >> currently known to be not known, but knowable in principle) science is >> loosing ground fast. Also an even greater area of the universe is >> supposed to exist that we will not even have a chance *ever* to know >> anything about. Exactly. Even worse, the various peripherals of Physics and Math are getting so esoteric that scholars in those areas are losing their ability to communicate to each other. It is almost like casting chicken entrails. > > That's a strange measure: what we know vs. what we know we > don't know. Consider physics back in the late 1800s. They could > write equations for many aspects of electricity and magnetism, but > there were problems, like the 'ultraviolet catastrophe'. Did they > consider those only minor gaps in knowledge or huge, gaping chasms > best stuck in a corner and ignored? > > Is the gap between QCD and general relativity as big? Hmmmm... > >> Trough out the centuries there has been evidence placing humanity >> firmly *not* in the center of the universe. First the earth was proven >> to rotate around the sun and not the other way around, next our sun >> was not in the center of the galaxy and so on. > > You use this as an argument for insignificance. I use it to show > that the idea of "center of" is a meaningless term. If I want, I can > consider my house as the center of the universe. I can still make > predictions about the motion of the planets, and they will be > exactly as accurate as using a sun-centered model. The only > difference is that my equations will be a bit more complicated. > >> Maybe now it is time to accept the fact that all the things we know >> taken together are only a small fraction of what can be known, and >> even more that that fraction is not even in a central position in the >> larger universe of the knowable, and that the knowable is just >> disappearingly small compared to the great abyss of the unknowable >> where everything is embedded in. > > Why? I mean, it's true, but it seems that some knowledge is > more useful than others. It's true because even if there were > a quadrillion people, each one would be different, with a unique > arrangement of thoughts and perceptions and a unique bit of > knowledge unknowable to you. > >> How come then that the sciences have been so uncanningly effective >> given that they are such an arbitrary choice within the knowable? The >> answer is of course that there are a lot of other possible sciences, >> completely unrelated to our own that would have been just as effective >> as -or even more effective than- our current sciences, had they been >> pursued with equal persistence during the same amount of time over a >> lot of generations. > > I don't follow your argument that this occurs "of course." > > It's not for a dearth of ideas. Humans did try other possible > sciences over the last few millenia. Despite centuries of effort, > alchemy never became more than a descriptive science, and > despite millenia of attempts, animal sacrifices never improved > crop yields, and reading goat entrails didn't yield any better > weather predictions. > > On the other hand, there are different but equivalent ways to > express known physics. For example, Hamiltonian and Newtonian > mechanics, or matrix vs. wave forms of classical quantum mechanics. > These are alternative ways to express the same physics, and some > are easier to use for a given problem than another. Just like a > sun-centered system is easier for some calculations than a "my house" > centered one. > > On the third hand, there are new theoretical models, like string > theory, which are different than the models we use. But they are > not "completely unrelated" and yield our standard models given > suitable approximations. > > On the fourth hand, Wolfram argues that cellular automata > provide such a new way of doing science as you argue. But > my intuition (brainw^Wtrained as it is by the current scientific > viewpoint) doesn't agree. > >> The effectiveness of the current natural sciences is a perceptual >> artifact caused by our biased history. From a lot of different >> directions messages are coming in now, all saying more or less the >> same: "If asking certain questions, one gets answers to these >> questions in a certain way, but if asking different questions one gets >> different answers, sometimes even contradicting the answers to the >> other questions". >> >> This might seem mystic or strange but one can see these things >> everywhere, if one asks that kind of questions :-) > > Or it means that asking those questions is meaningless. What's > the charge of an electron? The bare point charge is surrounded > by a swarm of virtual particles, each with its own swarm. If you > work it out using higher and higher levels of approximation you'll > end up with different, non-converging answers, and if you continue > it onwards you'll get infinite energies. But given a fixed > approximation you'll find you can make predictions just fine, and > using mathematical tricks like renormalization, the inifinities cancel. The charge of an Electron is a case in point. Okkam's Razor is the justification for adopting unitary charges and disregarding fractional charges. But, who justifies Okkam's Razor? > > For a simpler case .. what is the center of the universe? All locations > are equally correct. Is it mystic then that there can be multiple > different answers or is simply that the question isn't well defined? "All locations are equally correct" depends on your base assumptions about the Cosmological Constant, and a few other constants. Event Stephen Hawkings, in "A Brief History of Time" mentions the admixture of philsophy in determining the value of A in Einstein's Metric. > >> One example would be the role the observer plays in quantum mechanics, >> but something closer to a programmer would be the way static or >> dynamic typing influence the way one thinks about designing a computer >> program. > > The latter argument was an analogy that the tools (formalisms) affect > the shape of science. With that I have no disagreement. The science > we do now is affected by the existance of computers. But that's > because no one without computers would work on, say, fluid dynamics > simulations requiring trillions of calculations. It's not because the > science is fundamentally different. > > And I don't see how the reference to QM affects the argument. Then > again, I've no problems living in a collapsing wave function. > >> In a certain sense all science reduces the world to a view of it that >> leaves out more than that it describes, but that doesn't preclude it >> being effective. For a last example, what about the mathematics of >> curved surfaces? Sciences have had most of their successes using >> computations based on straight lines, and only recently the power of >> curves is discovered as being equal or more predictive than linear >> approaches. > > Yes, a model is a reduced representation. The orbit of Mars can be > predicted pretty well without knowing the location of every rock on > it surface. The argument is that knowing more of the details (and > having the ability to do the additional calculations) only improves the > accuracy. And much of the training in science is in learning how to > make those approximations and recognize what is interesting in the > morass of details. > > As for "straight lines". I don't follow your meaning. Orbits have > been treated as curves since, well, since before Ptolomy (who used > circles) or since Kepler (using ellipses), and Newton was using > parabolas for trajectories in the 1600s, and Einstein described > curved space-time a century ago. > >> Abstractness doesn't preclude effectiveness, but to try to use >> abstractions to understand the world is foolish since it doesn't work >> the other way around. > > You have a strange definition of "effectiveness." I think a science > is effective when it helps understand the world. > > The other solution is to know everything about everything, and, well, > I don't know about you but my brain is finite. While I can remember > a few abstractions, I am not omnipotent. > > Andrew > dalke at dalkescientific.com -- - GrayGeek From prochak at netzero.net Tue Nov 4 01:13:56 2003 From: prochak at netzero.net (Erik Lechak) Date: 3 Nov 2003 22:13:56 -0800 Subject: Can't get wxGrid to work References: Message-ID: <1f0bdf30.0311032213.3c84c900@posting.google.com> Hello, > self.gridPart2 = wxGrid(id=wxID_WXHAP2004GRIDPART2, name='gridPart2', > parent=self.pnlPersInfo, pos=wxPoint(280, 104), size=wxSize(112, > 176), style=wxSIMPLE_BORDER) Don't forget to self.gridPar2.CreateGrid(rows,cols) wxGrid isn't as dynamic or intuitive or whatever you want to call it. You have to explicitly tell it how many rows and cols you have. Look at AppendRows, AppendCols, DeleteRows, and DeleteCols. Dont try to CreateGrid more than once. Hope this helps, Erik Lechak From alanmk at hotmail.com Mon Nov 10 06:00:45 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 10 Nov 2003 11:00:45 +0000 Subject: Status of JPE (Java-Python Extension)? References: <87fzgxfpv3.fsf@pobox.com> <1068405973.1203.11.camel@emilio> <3faec862$0$58708$e4fe514c@news.xs4all.nl> Message-ID: <3FAF6FDD.EF94BD47@hotmail.com> [Irmen de Jong] > Jython has had (or still has) some problems that makes full > Pyro support impossible. For instance there is no "select" > like function in Jython (or rather, Java), and Pyro depends > on that for Pyro servers. So you're restricted to *clients* > in Jython: you can only call other Pyro objects, but you cannot > be called yourself. Irmen, As you noted yourself at the bottom of your message, Java 1.4 supports non-blocking IO and select calls. http://java.sun.com/j2se/1.4.2/docs/guide/nio/index.html If you need some assistance with getting Pyro running server side in Jython (java 1.4 only), get in touch with me. > Furthermore there were some bugs in Jython's implementation > that were triggered by certain Python code fragments in > Pyro, and I haven't really tried to work around them. > Dunno what Jython's up to at the moment, so YMMV. Jython 2.1 is exceedingly stable, and extremely useful. There is a comment on the jython.org page to the effect that "2.1 has become our 1.5.2". If you have any specific problems getting stuff running with jython, try me: I might be able to help. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From pwmiller1 at adelphia.net Wed Nov 12 01:59:08 2003 From: pwmiller1 at adelphia.net (Paul Miller) Date: 11 Nov 2003 22:59:08 -0800 Subject: Custom exceptions -- inherit from exceptions.Exception? Message-ID: <2e363c08.0311112259.549aa79@posting.google.com> Is there any particular good reason to inherit from exceptions.Exception? I've never seen any code that depends on what the base class(es) of a raised exception is (are). My use case is in a game I am writing. The code for my Game class contains the following: class Game (object): def start (self): try: self.players[1] except IndexError: raise NotEnoughPlayers where NotEnoughPlayers is really just an empty classic class suitable for raising. Is there any benefit to importing exceptions and inheriting from exceptions.Exception, other than maybe theoretical purity? Thanks! From sombDELETE at pobox.ru Sun Nov 23 19:51:39 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Mon, 24 Nov 2003 03:51:39 +0300 Subject: Redirecting Python stdout ,stderr and stdin References: Message-ID: "Alexander Schmolck" wrote in message news:yfssmke8vl0.fsf at black132.ex.ac.uk... > Jan Knop writes: > > > Hello > > > > I am writing a Windows application where I need to redirect stdin, > > stdout and stderr from Python. to my application > > Is it a simple way of do it ? > > import sys > sys.stdin, sys.stderr, sys.stdout = map(open, 'in.txt err.txt out.txt'.split(), > 'r w w'.split()) That is why map should be deprecated asap ;) sys.stdin = open("in.txt") sys.stdout = open("out.txt","w") sys.stderr = open("err.txt","w") -- Serge From a.schmolck at gmx.net Sun Nov 23 21:16:55 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 24 Nov 2003 02:16:55 +0000 Subject: code blocks in Python References: <8ef9bea6.0311221215.804bdb3@posting.google.com> <8ef9bea6.0311221913.427cb53e@posting.google.com> <8ef9bea6.0311231634.1ca497ac@posting.google.com> Message-ID: hungjunglu at yahoo.com (Hung Jung Lu) writes: > I still have yet to hear any difficulties/complaints. OK: 1. the semantics of your proposed extension remain somewhat nebulous 2. the extension appears pretty useless (AFAICT, given 1.) 3. you still haven't provided an example that would demonstrate otherwise (i.e. something interesting that could be more easily written with python + your extension than with python now). 'as From peter at engcorp.com Mon Nov 10 15:18:12 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Nov 2003 15:18:12 -0500 Subject: make order of function definitions irrelevant References: Message-ID: <3FAFF284.8EA7AEFB@engcorp.com> anton muhin wrote: > > As was said, you usually don't need such a thing. If you desperatly > looking for it, something like this might work: > > func = None > > def caller(): > assert func, 'func is None' > return func() > > def foo(): > return 'foo' > > def bar(): > return 'bar' > > func = foo > > print func() > > Of course, in this case you'd better pass an actual function as a > parameter. But, again, almost for sureit's a flaw in your design. As it stands, the first line in the above code is still redundant, and can be removed with no ill effects, as "func" is not actually called until it is bound to a real function. -Peter From ad at ad.nl Wed Nov 12 18:08:50 2003 From: ad at ad.nl (DD) Date: Thu, 13 Nov 2003 00:08:50 +0100 Subject: Access sql with python, please. I'm desperate Message-ID: Hello, Could anyone please help me?? Is there somebody who could explain me how to make a connection to a access database with a python cgi script. I would like to use common sql commands in my python scripts as I can with MySQLdb. But I cannot even connect to the access database (see below). Could anyone explain it to me as simple as possible please. I'm using Windows XP, ActivePython 2.3.2 build 230 and Microsoft access(XP?) I normally use Linux, but this has to be in MS office >>> import win32api >>> import win32com.client >>> engine = win32com.client.Dispatch("DAO.DBEngine.35") Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\Lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python23\Lib\site-packages\win32com\client\dynamic.py", line 84, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python23\Lib\site-packages\win32com\client\dynamic.py", line 72, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147221230, 'Klasse is niet gelicenseerd voor gebruik', None, None) thank in advance, Arjen From bignose-hates-spam at and-benfinney-does-too.id.au Fri Nov 14 17:49:36 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 15 Nov 2003 09:39:36 +1050 Subject: Python busting out References: Message-ID: On Fri, 14 Nov 2003 15:53:49 GMT, Vepxistqaosani wrote: > At my firm -- which must remain anonymous, I guess -- I'm the only > Pythoneer. We are strongly encouraged to use only "Approved > Technologies". > [...] > They still want me to figure out how to do this with [existing > Approved Technology], but they're so happy with the Python solution, > they've forgotten to pressure me on the issue. Your task is not complete. One important step remains: exert pressure, via this sterling example and any others you can find, that Python should *be* an Approved Technology for the company. -- \ "When we call others dogmatic, what we really object to is | `\ their holding dogmas that are different from our own." -- | _o__) Charles Issawi | Ben Finney From a_bogdan_marinescu at yahoo.com Mon Nov 17 02:42:09 2003 From: a_bogdan_marinescu at yahoo.com (Bogdan Marinescu) Date: Sun, 16 Nov 2003 23:42:09 -0800 (PST) Subject: Digest Number 5208 In-Reply-To: <1068973058.832.3634.m11@yahoogroups.com> Message-ID: <20031117074209.816.qmail@web21201.mail.yahoo.com> Message: 15 ?? Date: Sun, 16 Nov 2003 13:12:34 +1100 ?? From: Mark Hammond Subject: Re: Strange Python COM behaviour > strange errors. Specifically, I try to use a COM object that supports > events, and I'm instantiating it like this: > >?? eventobj = win32com.client.DispatchWithEvents( crtthread, > DebuggerThreadEvents ) > >???? It seems that events_class's type is str ( as returned by > getevents() function in __init__.py file from win32com/Client > directory) instead of 'classobj' as it is supposed to be. event_class > is actually a simple string showing a CLSID. I'm new to COM and I > can't understand why this is happening. Please help me if you can. >???? Regards, > It looks to me as if this error could occur if the event interface you > are trying to implement is not based on IDispatch.? It looks like a bug > in win32com - what is the object you are trying to use? Thank you very much for your reply. This is crtthread: ? ? This is the signature of the interface as returned by OLE/COM Object Viewer: ? interface ICodeWarriorDebuggerThread : IDispatch { And this is the signature of the events interface: interface ICodeWarriorDebuggerThreadEvents : IUnknown { This is the declaration of my events class: class DebuggerThreadEvents: """ Handle events generated by the ICodeWarriorDebuggerThreadEvents object """ def ThreadDied( self, thread ): print '1' def ThreadStepped( self, thread, stepMode ): print '2' ...................................... By the way, thank you for Win32 extensions, they are GREAT! :) __________________________________ Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard http://antispam.yahoo.com/whatsnewfree From P at draigBrady.com Tue Nov 4 06:32:04 2003 From: P at draigBrady.com (P at draigBrady.com) Date: Tue, 04 Nov 2003 11:32:04 +0000 Subject: duplication of logic In-Reply-To: References: Message-ID: <3FA78E34.4050502@draigBrady.com> John Roth wrote: > "George Trojan" wrote in message > news:bo6oaf$vfq$1 at news.nems.noaa.gov... > >>Is time.strptime() intrinsically slow and should be avoided whenever >>possible? I have the following code in my application: > > > According to the "what's new in Python" for 2.3, the strptime > implementation was switched from a lightweight wrapper > around the frequently buggy and incompatible C library > to a portable pure Python implementation. > > Yes, it's going to be a lot slower. This duplication of logic looks like a trend? For e.g. locale.format is very simplistic (in 2.2.2 at least) It groups %s items as numbers: locale.format("%s",1234,1) -> '1,234' and treats non numbers as numbers: locale.format("%s\n",1234,1) -> '12,34\n' This should be fixed, or changed to just taking an int and returning a string or better using the glibc facility of the ' modifier. e.g "%'d" This applies to any decimal conversion (i,d,u,f,F,g,G) You wouldn't have to use it directly, just in locale.format() you could add in a ' in the appropriate places. Note this is SUSV2 not just glibc Another e.g. where glibc functionality should be used rather than reimplementing in python is the parsing of mo files. Note Solaris mo files are not supported currently anyway. I know python has to be cross platform, but automatically setting things up to use the system libraries where appropriate would be a benefit to performance and functionality IMHO. P?draig. From johan at weknowthewayout.com Fri Nov 21 10:31:37 2003 From: johan at weknowthewayout.com (Johan Holst Nielsen) Date: Fri, 21 Nov 2003 16:31:37 +0100 Subject: Analyse of PDF (or EPS?) In-Reply-To: References: <3fbcc67e$0$9836$edfadb0f@dread14.news.tele.dk> <3fbe01cf$0$95037$edfadb0f@dread11.news.tele.dk> Message-ID: <3fbe2ffd$0$9722$edfadb0f@dread14.news.tele.dk> Grzegorz Makarewicz wrote: > Johan Holst Nielsen wrote: > [...] > > > Not Found > > The requested URL /~mak/wxpdf.zip was not found on this server. > > > > Can you please try to upload it again? > > > > Johan > > > > Sorry for the missing link, this one works: > > http://www.trisoft.com.pl/mak/wxpdf.zip Thanks Grzegorz, I will look at it in next week. If you want an reply about if I can use - please send a message to me at tcr480 ( a t ) yahoo.dk Regards, Johan From anton at vredegoor.doge.nl Mon Nov 3 14:15:58 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Mon, 03 Nov 2003 20:15:58 +0100 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <87he1vsopi.fsf@pobox.com> <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> <2259b0e2.0311012219.73aa445f@posting.google.com> Message-ID: bokr at oz.net (Bengt Richter) wrote: >Now consider the experience of being "convinced" that a theory "is true." What does that mean? > >Does our experience-medium get shaped repeatedly through layers and layers of abstraction and >re-representation to where some bit of memory is sensed to have a comfortable stability w.r.t. >sensations derived from a series of experiemnts, and we are satisfied by some pleasure-connect >with this state of brain? Is it pain and pleasure at bottom, tied to subtle internal state >sensations? Do we form theories like patterns of sand form on a vibrating membrane at quiescent >spots for a given mode of vibration? Do internal cognitive dissonances drive the "sand" away >from untenable positions in patterns of theory? Is our conscious experience-medium passive in >being shaped by the transducer, or does it have its own properties? E.g., is our sense of >connected-ness of a broken line in our visual conscious experience due to shaping of a field? >I.e., due to our very experience medium having field-nature and naturally taking some form >across gaps between features due to its own properties? >From what I know about neurons (the cells that transport information using long wire like connections) there are only two states they can be in: "firing" or "not firing". If they're firing a chemical imbalance travels down the wire and causes a release of neuro transmitters when it reaches a synapse (the connection with another neurons receiving end). After firing there is an obligatory pause in which the transmitters are reabsorbed and the chemical balance of the transporting wire is restored. The neurons are not connected one to one, but many neurons work together to make another one fire. And this firing neuron sends *its* signal to a lot of others too. Contrary to what one might expect after reading this, the neurons do not use a binary information transmission scheme if looked at from a somewhat higher level. Information is transported by changes in the *frequency* in which neurons fire. We are convinced that a theory is true if there are certain groups of neurons firing in a frequency pattern that corresponds to the theory. So essentially we are looking for harmony, which means that no single observational fact is enough for determining truth. That's why we not only need to hear someone say "yes" but we also need to see their face while they're saying it and we also take into consideration countless little details of the overall situation when forming the theory: "this person is agreeing to something". A practical application of this theory could also be possible. Consider a kind of device that has countless little movable pins where one could lay ones hands on in order to feel the activation patterns. Like some braille device but bigger, and instead of just conveying letters it would convey complete "meanings" by vibrating or alternating in a certain way. Since this device would be close to the way our brain works (frequency patterns activating the tactile cells in our hands) it would possibly be more effective than a computer screen to transfer a certain category of messages. I don't know which kind of messages though, but I suspect there are things that cannot be conveyed any other way, like there is no natural way to convey sound messages using a computer screen. If it were a two way real time system one could have some weird conversations with distant people "over the teletactile line"! Of course in order to convey some more detailed information one would have to program the thing using Python :-) Anton From mwilson at sarcastic-horse.com Tue Nov 18 12:11:40 2003 From: mwilson at sarcastic-horse.com (Matthew Wilson) Date: Tue, 18 Nov 2003 17:11:40 GMT Subject: recommendations for python web programming tools References: Message-ID: In article , Dennis Lee Bieber wrote: > I'm not an expert, but have you looked at Zope? I looked a little at Zope, and it looks like it has a huge learning curve. Is that true? How long would it take for a person that's written lots of CGI scripts to get up to speed on Zope? Maybe I *should* take a look at Zope. From lliabraa at isrparc.org Mon Nov 3 11:06:14 2003 From: lliabraa at isrparc.org (Lane LiaBraaten) Date: Mon, 3 Nov 2003 16:06:14 +0000 Subject: Pygame and TKinter In-Reply-To: References: Message-ID: <200311031606.14103.lliabraa@isrparc.org> On Monday 03 November 2003 07:00 pm, Matthew Wilson wrote: > In article , Lane > > LiaBraaten wrote: > > Does anyone know a way to insert a pygame surface into a tkinter gui? > > I am writing a program similar to a mpeg player, i.e. i need the mpeg > > playing capabilities of pygame and the gui stuff from tkinter. > > > > TIA, > > LGL > > There's a limited gui interface available with pygame. You could also > always make your own button icons and have them respond to button > clicks. What Tkinter widgets do you want to use in particular? I need buttons, text inputs, and scrolling text output. All I've found is the text input from the pygame code repository site. Rather than make my own widgets I am planning to have one window for the mpeg viewer and one for the rest of the GUI (although one window would be better). Can you point me to any source code for buttons, or a scrolling textbox? Also, as time is a factor, which design is likely to be faster (at run time, not development): 1. Totally pygame interface with custom widgets (one window), or 2. pygame only for mpeg playing, and tkinter for the rest (2+ windows) TIA, LGL From michele.simionato at poste.it Fri Nov 28 13:52:31 2003 From: michele.simionato at poste.it (Michele Simionato) Date: 28 Nov 2003 10:52:31 -0800 Subject: Unbound methods and functions References: <3fc5f1a7$0$27472$afc38c87@news.easynet.co.uk> <3fc60223$0$27468$afc38c87@news.easynet.co.uk> Message-ID: <95aa1afa.0311281052.3591d4d6@posting.google.com> Ben wrote in message news:<3fc60223$0$27468$afc38c87 at news.easynet.co.uk>... > > Arrgh, forgot to ask the question that was the entire point of the post > > Is there any real difference between an unbound method, and a function, > apart from the scoping differences. I.e would it make any difference in the > get descriptor for a function, when called on a type, returned the function > instead of an unbound method? > > Cheers > > Ben > --- I do not really understand your question. Of course an unbound method is different from a function, even if you can convert one in the other. For instance, if you are inspecting code (for automatic generation of documentation, or for metaprogramming purposes) the two things are different: you get one with inspect.isfunction, the other with inspect.ismethod. There are other differences too. Look at the source code of the inspect module for more. I think you already know the standard reference on descriptors: http://users.rcn.com/python/download/Descriptor.htm From ramen at lackingtalent.com Tue Nov 11 20:12:15 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 12 Nov 2003 01:12:15 -0000 Subject: True, False, None References: <20031110065915.07735.00000461@mb-m07.aol.com> Message-ID: In article , Andrew Dalke wrote: > Douglas Alan: >> Can someone remind me as to why [None, True, False] are >> capitalized? They clash annoyingly with the common coding >> convention that capitalizes only classes. > > Here's a conjecture -- those are singletons, and note that classes > are singletons too. And so are modules... ;) -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From fBechmann at web.de Sun Nov 9 04:42:04 2003 From: fBechmann at web.de (Frank Bechmann) Date: 9 Nov 2003 01:42:04 -0800 Subject: enumerate drive names on windows Message-ID: yes, that's the simple question: is there some python standard or 'Python for Windows Extensions' functionality to iterate or list-return the available drives ('A:', 'B:', 'C:', ...) on a machine running windows? Thx in advance. From bokr at oz.net Sat Nov 15 14:30:42 2003 From: bokr at oz.net (Bengt Richter) Date: 15 Nov 2003 19:30:42 GMT Subject: reading piped input in Windows References: <95ocrv0gts1dn66dvgn84n9j7rcthbdglf@4ax.com> Message-ID: On Sat, 15 Nov 2003 18:27:22 +0100, Patrick Useldinger

wrote: >Hi, >I am writing a filter, i.e. a program that reads from stdin and writes >to stdout. It works ok when run on its own, but does not work when I try >to use another program's output. > >- The producer program (t1): >print "a b c" >print "d e f" > >- The filter program (t2): >import sys >r = sys.stdin.readlines() >for i in r: > print '<',i,'>' > >When i connect them using 't1 ? t2', I get the following error message: >Traceback (most recent call last): > File "[...]", line 2, in ? > r = sys.stdin.readlines() >IOError: [Errno 9] Bad file descriptor > >The same programs work correctly under Linux, so I suppose that Windows >handles redirectionned input differently from 'normal' console input. >Can anyone point me to a portable solution that works both under Windows >and Linux? > Some versions of windows have a bug in i/o redirection for programs started via data/script file extension association (if you have perl on your machine you will have the same problem piping to/from perl scripts started by extension association). It is probable that running the interpreter directly would make it work, e.g., python t1.py | python t2.py But you probably want to spell it t1|t2. On windows, t1 and t2 will have to be executables to do that reliably across windows versions. Executables are generally associated with the usual extensions .exe, .com, .bat, and .cmd, so one way to solve the spelling problem is to provide a t1.bat or t1.cmd that runs python explicitly with t1.py as arg, as you would do it from the command line, e.g., a t1.cmd whose single line content is @python t1.py This will be slower than also supplying the absolute path to python, but you won't have to change it when you upgrade and python winds up in c:\python24 instead of c:\python23. OTOH, if you need a specific version of python to interpret your script, supplying the full path will lock it in. Note that a .bat or .cmd invocation of python also gives you the opportunity to pass a command line option, e.g., python -u drive:\your\path\t1.py to run with unbuffered binary stdout and stderr. Regards, Bengt Richter From bucodi at ahoo.fr Fri Nov 28 03:24:37 2003 From: bucodi at ahoo.fr (Rony) Date: Fri, 28 Nov 2003 09:24:37 +0100 Subject: [OT] Spambays question References: Message-ID: Tony Meyer wrote on Fri, 28 Nov 2003 18:53:48 +1300 in : > > This is a litle bit out of topic, but i suppose that a lot of > > python users, use the spanbays spam filter. > > As well as the spambayes mailing list already mentioned, you might want to > try the spambayes website , FAQ > , and wiki . > > > I must admit it works great, after a month testing with it, > > it made no errors and catch 100% of spam. The only (litle) > > problem I see is that it puts all spam in a spam folder. I > > think, that now i'm confident with it, it would be great if > > you could simple delete automaticly the spam without putting > > it in a spam folder. > > > > Perhaps somebody managed to do that ? > > FAQ 3.9 has your answer: > > delete-spam-rather-than-moving-it>. > > (This assumes you are using the Outlook plug-in - if not, then just alter > whatever rule you created in your mail client). > > =Tony Meyer > > Thanks for the answer. Altough I must say that I'm a little pissed that I didn't find it myself, I hate to ask stupid question ;) Rony From skip at pobox.com Tue Nov 25 10:04:08 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 25 Nov 2003 09:04:08 -0600 Subject: How can I reach webmaster@python.org? In-Reply-To: References: Message-ID: <16323.28520.856804.770977@montanaro.dyndns.org> Steve> It looks as if no-one is picking up e-mail addressed to the Steve> webmaster, so the mailbox is full. I sent e-mail to Steve> webmaster at python.org on Saturday and got the following reply: ... That message tells you that Kirby Urner's disk quota was exceeded: Steve> : Steve> Disk Quota Exceeded. Steve> Sorry, your message cannot be delivered because the recipient has Steve> exceeded their disk space limit for email. He's just one of several people who get copies of mail sent to webmaster at python.org. Skip From jjl at pobox.com Sun Nov 30 10:25:19 2003 From: jjl at pobox.com (John J. Lee) Date: 30 Nov 2003 15:25:19 +0000 Subject: Status of PyRange_New? References: Message-ID: <87y8txq3og.fsf@pobox.com> "Edward C. Jones" writes: > In Python 2.3.2, PyRange_New and PyRange_Check are undocumented. Are > range objects and these functions going to disappear in the future? Maybe this is one for python-dev? John From http Tue Nov 18 17:53:50 2003 From: http (Paul Rubin) Date: 18 Nov 2003 14:53:50 -0800 Subject: rotor alternative? References: <7x8ymd4hwf.fsf@ruckus.brouhaha.com> Message-ID: <7x3cclwao1.fsf@ruckus.brouhaha.com> Robin Becker writes: > > http://www.nightsong.com/phr/crypto/p3.py > Thanks for the kind offer, but I'm getting permission errors with that > URL. Oops, try again now. From amaury.forgeotdarc at ubitrade.com Wed Nov 26 07:17:03 2003 From: amaury.forgeotdarc at ubitrade.com (Amaury Forgeot d'Arc) Date: 26 Nov 2003 04:17:03 -0800 Subject: Newbi q: show prog References: Message-ID: <1c9a4fe8.0311260417.60606ac9@posting.google.com> christoffer81 at mail.dk (Christoffer T) wrote: > I have tried to write "python file.py" in run, but it just very fast > open and close dos window. So what should I do to get to show the > program. Try "python -i file.py" This will force python to enter interactive mode after running your script. Hit and to exit. Alternatively, you can open a command prompt ("cmd.exe") and run python from there. The python program will exit, but the command window will stay and show the output of the program. Amaury. From prouleau at impathnetworks.com Sat Nov 15 14:18:23 2003 From: prouleau at impathnetworks.com (Pierre Rouleau) Date: Sat, 15 Nov 2003 14:18:23 -0500 Subject: Is RAII possible in Python? Message-ID: <4_utb.21936$IK2.1678737@news20.bellglobal.com> As much as I love Python, I sometimes find myself wishing Python supported the RAII idiom (resource acquisition is initialization) that is available in C++, the emerging D language, and others. In some situations (like controlling non-memory resources) it is nice to be able to create an object that will execute some code on its destruction. For example, an object that controls access to a critical section: the creation of the object calls the function required to enter the critical section, and the __del__() calls the function required to exit the critical section. If an exception occurs while the code is insinde the critical section managed by the object, the the object's __del__() is automatically called and the critical section exited. AFAIK, the call of __del__() method on object destruction is not garanteed to be called when the interpreter exists. Is this true? Is the __del__() mehod of an object garanteed to be called when a function exists normally or is forced to exit by an exception? Is RAII available in Python? Thanks Pierre From theller at python.net Sat Nov 1 06:50:32 2003 From: theller at python.net (Thomas Heller) Date: Sat, 01 Nov 2003 12:50:32 +0100 Subject: ANN: ActivePython 2.3.2 & ActivePython 2.2.3 References: Message-ID: Trent Mick writes: > [Matthew wrote] >> Trent Mick wrote ... >> > We are pleased to announce that versions 2.3.2 and 2.2.3 of ActivePython >> > are now available for download from: >> > http://www.ActiveState.com/ActivePython >> > ActivePython 2.3.2 is the first ActivePython release for the Python >> > 2.3.x series. ActivePython 2.2.3 is a bugfix release for, and >> > supercedes, ActivePython 2.2.2. >> >> The ActiveState web site says that the version of PyWin32 is build >> 146, which is fairly old. >> >> Does anyone know if that's correct, or is it just the documentation >> that's out of date? > > The docs are just out of date. I hope to have a fix for the doc up early > next week. The actual PyWin32 versions are as follows: > ActivePython 2.3.2 build 230: PyWin32 b159 > ActivePython 2.2.3 build 225: PyWin32 b158 > These are the latest "stable" PyWin32 build numbers. Which is a pity, since the upcoming py2exe (for python 2.3) requires win32all build 161 or later, if win32all is used. Thomas From bdesth.nospam at removeme.free.fr Wed Nov 26 05:41:46 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Wed, 26 Nov 2003 11:41:46 +0100 Subject: [OT] Treestructure in SQL In-Reply-To: References: Message-ID: <3fc47f7e$0$18427$626a54ce@news.free.fr> Peter Otten wrote: (snip core and code) > > PS: In the spirit of "It's easier to ask forgiveness than permission", is > there a generally agreed upon upper size limit for usenet posts? > I don't know of any formal size limit, but I don't think anyone would complain about the size of that one. From usenet_spam at janc.invalid Thu Nov 6 23:06:03 2003 From: usenet_spam at janc.invalid (JanC) Date: Fri, 07 Nov 2003 04:06:03 GMT Subject: Python on Powerpc References: <221d8dbe.0311060007.54db50d1@posting.google.com> Message-ID: srijit at yahoo.com schreef: > Has anyone ported Python on powerpc(ppc8xx) with Linux? AFAIK there are Linux/PPC packages from Debian? -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From shalabh at gameboard.org Tue Nov 25 23:49:34 2003 From: shalabh at gameboard.org (Shalabh Chaturvedi) Date: 25 Nov 2003 20:49:34 -0800 Subject: In a bit of a pickle here :) References: <5777svgdl2kchbvg8idbm8kdefoan88o9j@4ax.com> Message-ID: > I have one other question about the pickle system. If I add new > attributes to an object and try to unpickle an old version will it > work? How do you handle versioning of objects with pickle? Your unpickle will succeed but any new attributes will not be present. The object will get unpickled with exactly the same attributes it had when it was pickled. Look at __getstate__() and __setstate__() in the Python docs - you might be able to fix the unpickled object by overriding __setstate__(). > So I came up with the idea of just > storing all of the python objects in the postgres database pickled in > a blob field. Im sure about ten thousand other people came up with > this idea before me. The only other data stored in the table will be > the id of the object and the last time the object was modified. What kind of attributes do your objects have? If they point to each other, or to common objects, then pickling and unpickling can lead to all sorts of undesirable effects, and you might be better of using a different solution. You might want to look at the following (some of which I have never looked at myself): 1. ZODB (object database of http://www.zope.org/ ) 2. MiddleKit in Webware (http://webware.sourceforge.net/ ) 3. Twisted (http://www.twistedmatrix.com/ ) 4. Metakit (http://equi4.com/metakit.html ) -- Shalabh From amk at amk.ca Tue Nov 11 07:47:21 2003 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 11 Nov 2003 06:47:21 -0600 Subject: colorsys: RGB to YIQ transform matrix References: Message-ID: On Mon, 10 Nov 2003 22:53:58 -0500, Edward C. Jones wrote: > Why does colorsys use a 2 decimal place wersion of the array? What is > the actual definition of the RGB to YIQ transform? I'll wager there's no technical reason. Maybe whoever wrote the module used a reference that only quoted the matrix to two places. You could submit a patch on SourceForge to correct this. (Hm, looks like there's no test suite for the module. That would be worth fixing.) --amk From see_signature__ at hotmail.com Tue Nov 18 01:06:27 2003 From: see_signature__ at hotmail.com (Georgy Pruss) Date: Tue, 18 Nov 2003 06:06:27 GMT Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: "Steve Lamb" wrote in message news:slrnbrio3f.s51.grey at dmiyu.org... | <..> | Because as much as it helps when reading the code to only have to learn a | minimal set of controls the same applies to writing code as well. When I | approach a problem I don't have to agonize over "well, should I do a | do...until(), a for(;;), a while(), or something else?" It breaks down to | this. I can't agree here. I NEVER wondered which of constructions should I use in any particular case. I just solved the problem and wrote its solution in that language and the language HELPED me to express myself clearly. | Is it a sequence? For. Is it a condition to be met? While. There, | done, move along. Aha. Half of all the conditions in real Python programs are 1 or True. :-) | -- | Steve C. Lamb | I'm your priest, I'm your shrink, I'm your | PGP Key: 8B6E99C5 | main connection to the switchboard of souls. | -------------------------------+--------------------------------------------- -- Georgy Pruss E^mail: 'ZDAwMTEyMHQwMzMwQGhvdG1haWwuY29t\n'.decode('base64') From skip at pobox.com Tue Nov 11 16:53:09 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 11 Nov 2003 15:53:09 -0600 Subject: Emacs python mode equivalent to c-tab-always-indent In-Reply-To: References: Message-ID: <16305.23109.260391.302535@montanaro.dyndns.org> Gary> Rather than waiting around for an answer, I went ahead and made my Gary> modifications to python-mode.el. Can you submit your patch to the python-mode project on SF: http://sf.net/projects/python-mode ? Thx, Skip From hans at zephyrfalcon.org Tue Nov 4 13:08:03 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Tue, 04 Nov 2003 13:08:03 -0500 Subject: breaking iteration of generator method In-Reply-To: References: Message-ID: <3FA7EB03.4040907@zephyrfalcon.org> Brian wrote: > Hello; > > What happens when a program breaks (think keyword 'break') its iteration > of a generator? Is the old state in the generator preserved? > > Ex: > > # .gen() is generator method. > > for i in myObject.gen(): > if i == specialValue: > break > > Do subsequent calls to .gen() start off with new locals? Or, would > the iteration begin after the yielded 'i' that caused the for-statement > to exit? It's easy to find out... :-) >>> def g(): ... for i in range(10): ... yield i ... >>> gen = g() >>> for x in gen: ... if x == 4: ... break ... else: ... print x, ... 0 1 2 3 >>> for x in gen: ... print x, ... 5 6 7 8 9 >>> However, if you use g() rather than an existing generator object, a new generator will be created: >>> for x in g(): ... if x == 4: ... break ... else: ... print x, ... 0 1 2 3 >>> for x in g(): ... print x, ... 0 1 2 3 4 5 6 7 8 9 >>> HTH, -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From __peter__ at web.de Sun Nov 23 18:36:55 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Nov 2003 00:36:55 +0100 Subject: Help with script with performance problems References: Message-ID: Peter Otten wrote: > However, it took 143 seconds to process 10**7 lines generated by I just downloaded psycho, oops, keep misspelling the name :-) and it brings down the time to 92 seconds - almost for free. I must say I'm impressed, the psycologist(s) did an excellent job. Peter #!/usr/bin/python -u import psyco, sys psyco.full() def main(): clients = {} queries = {} lineNo = -1 threshold = 100 pointmod = 100000 f = file(sys.argv[1]) try: print "Each dot is %d lines..." % pointmod for lineNo, line in enumerate(f): if lineNo % pointmod == 0: sys.stdout.write(".") try: month, day, timestr, stype, source, qtype, query, ctype, record = line.split() except ValueError: raise Exception("problem splitting line %d\n%s" % (lineNo, line)) source = source.split('#', 1)[0] clients[source] = clients.get(source, 0) + 1 queries[query] = queries.get(query, 0) + 1 finally: f.close() print print lineNo+1, "lines processed" for numclient, count in clients.iteritems(): if count > threshold: print "%s,%s" % (numclient, count) for numquery, count in queries.iteritems(): if count > threshold: print "%s,%s" % (numquery, count) import time starttime = time.time() main() print "time:", time.time() - starttime From wmgill at wmgill.com Sun Nov 2 18:19:06 2003 From: wmgill at wmgill.com (WmGill) Date: Sun, 2 Nov 2003 18:19:06 -0500 Subject: form processing question References: <423f3$3fa58837$42a655ea$20950@msgid.meganewsservers.com> <87ism2754c.fsf@pobox.com> Message-ID: <6bd64$3fa590f3$42a655ea$21185@msgid.meganewsservers.com> Like I said, I'm experimenting. I was thinking of using the standard cgi module. but I'm open to suggestions. Bill "John J. Lee" wrote in message news:87ism2754c.fsf at pobox.com... > "WmGill" writes: > > > I am experimenting with Python, and want to convert some of my PHP scripts > > to python cgi scripts. In PHP I use PHP_SELF for the action target. This > [...question snipped...] > > Which web framework / library are you using? > > Or are you just using the standard library cgi module (most Python web > programmers use something more than that)? > > > John From uche at ogbuji.net Sat Nov 22 21:59:15 2003 From: uche at ogbuji.net (Uche Ogbuji) Date: 22 Nov 2003 18:59:15 -0800 Subject: jython lacks working xml processing modules? References: Message-ID: "Diez B. Roggisch" wrote in message news:... > Jane Austine wrote: > > I'm trying to parse an xml file with jython (not through java parsers > > like xerces). > > > > I tried minidom in jython 2.1 and 2.2a but all failed. > > > > What can I do? The last resort would be using java parsers. Then how > > can I use them like python xml parsers? It seems like javadom and > > javasax has something to do, but I don't know how. > > There is a really goog xml toolkit wich even covers xslt and some other > fancy stuff. Its called 4suite, and you can get it here: > > http://www.4suite.org/ > > One of the authors, Uche Ogbuji, has some tutorials on working with it > on developerworks. Thanks for the plug, but 4Suite has a lot of C code in it and is probably not an option for use in Java without some porting work. -- Uche http://uche.ogbuji.net From aleax at aleax.it Wed Nov 5 13:23:59 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 05 Nov 2003 18:23:59 GMT Subject: reduce() anomaly? References: Message-ID: <3fbqb.97878$e5.3584611@news1.tin.it> Stephen C. Waterbury wrote: > This seems like it ought to work, according to the > description of reduce(), but it doesn't. Is this > a bug, or am I missing something? the latter. > Python 2.3.2 (#1, Oct 20 2003, 01:04:35) > [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> d1 = {'a':1} > >>> d2 = {'b':2} > >>> d3 = {'c':3} > >>> l = [d1, d2, d3] > >>> d4 = reduce(lambda x, y: x.update(y), l) the update method returns None. > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1, in > AttributeError: 'NoneType' object has no attribute 'update' right. > >>> d4 = reduce(lambda x, y: x.update(y), l, {}) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1, in > AttributeError: 'NoneType' object has no attribute 'update' same issue. If you want to abuse reduce at all costs for this purpose, reduce(lambda x, y: x.update(y) or x, l) might work. Alex From 3seasA at Tthreeseas.DOT.not Sat Nov 15 10:57:45 2003 From: 3seasA at Tthreeseas.DOT.not (3seas) Date: Sat, 15 Nov 2003 15:57:45 GMT Subject: OT Re: Matrix - Metaphors, Analogies and the REAL References: <9447377298731260.NC-1.60.joobs@news.free-online.net> <944913851691266.NC-1.61.joobs@news.free-online.net> <1Ihtb.1378$Wy4.787@newsread2.news.atl.earthlink.net> Message-ID: RaYzor wrote: . . . > Matrix films suck. Its not real. Get a life. > > RaYzor This last post of mine was not supposed to go in the python newsgroup. I thought I had checked it, but knode is new to me. Follow up should now be to the comp.sys.amiga.misc newsgroup, Where teh last post of mine was intending to only go to. -- 3 S.E.A.S -- Virtual Interaction Configuration (VIC) Changing how we preceive and use computers email @ translate not to net, remove capitol letters, one . web @ http://threeseas.net From janeaustine50 at hotmail.com Tue Nov 18 10:37:26 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 18 Nov 2003 07:37:26 -0800 Subject: Memory exception with Tkinter root.quit References: Message-ID: bokr at oz.net (Bengt Richter) wrote in message news:... > On 17 Nov 2003 18:08:01 -0800, janeaustine50 at hotmail.com (Jane Austine) wrote: > > >>Jane Austine wrote: > >>>>>from Tkinter import * > >>>>>>r=Tk() > >>>>>>b=Button(r,text='Quit',command=r.quit) > >>>>>>b.pack() > >>>>>>r.mainloop() > >>> > >>> > >>> And when I press the "Quit" button the mainloop exits. After that, > if > >>> I finish the python shell, a memory exception occurs. > >>> > >>> This is Windows XP machine with Python 2.3. > >> > >> Not much of a help, but I've tried it here: no problems... (python > >> 2.3.2, win xp). Can it be a Python 2.3.0 issue that has been fixed in > >> 2.3.1 or 2.3.2 ? > >> > >> --Irmen > > > >I tried it with 2.3.2, but it doesn't work either. > > > >The crash message is: > > > >python.exe -- application program error > > > >the command from "0x77f7e22a" referenced the memory at "0x00000028". > >The memory couldn't be "read". > > Another data point: > > For me it ran seemingly ok in an NT4 console window, but with idle it acted weird, > and I couldn't capture the session screen (oops, maybe Ctl-C is no good for that there) > Anyway, the Quit button changed to depressed look, and then was stuck visible but not responding. > I had to kill it with task manager. Then idle printed a -----restart----- line. > > Regards, > Bengt Richter It's very strange but it works perfect when I rename python.exe into something else and run with it. Has it something to do with previous versions installed? I had Python2.3bx and 2.3c1 installed on this machine and didn't uninstall them before I installed Python 2.3.2. Why does this happen? How can I solve this problem? From alanmk at hotmail.com Mon Nov 3 07:59:39 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 03 Nov 2003 12:59:39 +0000 Subject: Microsoft Access read from linux python References: <3FA63F06.9739C80F@hotmail.com> Message-ID: <3FA6513B.57435443@hotmail.com> [Alan Kennedy] >> There is a completely free (in all senses of the word) and >> open-source ODBC module for python: It is Brian Zimmer's/Ziclix >> zxJDBC. [Paul Rudin] > There's also an odbc module with the win32all thing, which is free. Thanks Paul, I wasn't previously aware of that. So it seems the only people without access to a free (in all senses of the word) python ODBC driver are those who won't use Windows or Java ....... regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From JTesser at nbbc.edu Fri Nov 21 14:59:22 2003 From: JTesser at nbbc.edu (Jason Tesser) Date: Fri, 21 Nov 2003 13:59:22 -0600 Subject: [GENERAL] linking postgre to AD Message-ID: <04875CB4331F0240A0AD66F970978651011376B9@paul> ok so what would prevent users from using SQL tools to connect to the database and browse data? > As far as AD is concerned, I think Bruno Wolff described what to do best: > 1) Configure PostgreSQL to authenticate via PAM (pam_ldap) > 2) Create a table of appgroups & groupmembers that defines the application groups and their members, respectively > 3) Create views over the actual data that test for the appropriate group membership. > You can write your own function to simply the task: > CREATE FUNCTION isMember(text, text) RETURNS bool AS ' SELECT true FROM appgroups, groupmembers WHERE appgroups.name = $1 AND appgroups.appgroup = groupmembers.appgroup AND groupmembers.userid = $2; ' LANGUAGE 'sql'; > 4) Now, if you only want people in the 'Administration' group to view salaries: CREATE VIEW v_salaries AS SELECT * FROM salaries WHERE isMember('Administration', CURRENT_USER); > Or you could do the join against the base table for row-level security: CREATE VIEW v_salaries AS SELECT * FROM salaries, groupmembers WHERE salaries.appgroup = groupmembers.appgroup AND groupmembers.userid = CURRENT_USER; > 5) REVOKE SELECT on salaries from the public and GRANT select on v_salaries to the public. HTH, There is a security problem here if users are able to create their own functions: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=3D02B372.B6A4EFB6%40mascari.com HTH, Mike Mascari mascarm at mascari.com From newsgroups at jhrothjr.com Thu Nov 6 15:07:22 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 6 Nov 2003 15:07:22 -0500 Subject: prePEP: Decimal data type References: Message-ID: "Tim Peters" wrote in message news:mailman.487.1068133912.702.python-list at python.org... > [Aahz] > > Well, sure. And it won't be hard to add given that Decimal will > > already need to track thread-specific Context. But modules changing > > Context will still need to explicitly push and pop Context because > > usually you will just want to replace the current Context. > > They have another choice, because Guido had a brilliant idea: the > arithmetic operations in Eric's implementation are methods *of* a context > object (because Guido suggested that). So a maximally robust library > doesn't *have* to change the thread context at all: it can create whatever > private context object(s) it needs, and spell arithmetic as explicit method > calls on its private context object(s), so that the default thread context > object is neither consulted nor modified. This is very robust, and in small > doses is quite bearable. I think I agree: Guido committed a brilliancy there. Having had to deal with monetary calculations and the weird rounding mandated by various laws, regulations and way out of it PHB accountants, I don't see how simple expression syntax is ever going to do what is needed. AFAICS, there are only two solutions: .add(, []) and .add(, ) The difference is in where you put the various factors. I think they both come out to roughly the same number of keystrokes, especially if you assume that can be a variety of different things, including a full blown context object. John Roth > > From gerrit at nl.linux.org Sun Nov 16 04:13:39 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 16 Nov 2003 10:13:39 +0100 Subject: datetime and strptime In-Reply-To: References: Message-ID: <20031116091339.GA23936@nl.linux.org> Magnus Lie Hetland wrote: > In article , Gerrit > Holl wrote: > >Hi, > > > >it seems the datetime library does not have a .strptime class method. > [snip] > > Have a look at PEP 321: > > http://www.python.org/peps/pep-0321.html Ah, yes... Thanks for the link! yours, Gerrit. -- 167. If a man marry a wife and she bear him children: if this wife die and he then take another wife and she bear him children: if then the father die, the sons must not partition the estate according to the mothers, they shall divide the dowries of their mothers only in this way; the paternal estate they shall divide equally with one another. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From aaron at reportlab.com Tue Nov 18 14:13:03 2003 From: aaron at reportlab.com (Aaron Watters) Date: 18 Nov 2003 11:13:03 -0800 Subject: rotor alternative? References: Message-ID: <9a6d7d9d.0311181113.3bf45ec8@posting.google.com> Robin Becker wrote in message news:... > Is an alternative to rotor planned? Dunno, but I've been using this in my own experimental development (private key, synchronous communication). http://athos.rutgers.edu/~aaron/python/pulver.py I don't know how strong it is, but I rashly guess that it might be pretty strong. -- Aaron Watters ps: [off topic] go http://www.cs.rutgers.edu/~aaron/img/ for pictures of my new niece. === nothing exceeds like excess From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Nov 1 17:53:14 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 01 Nov 2003 23:53:14 +0100 Subject: simple echo server In-Reply-To: <3FA4284A.6010701@zg.htnet.hr> References: <3fa3fab9$0$58702$e4fe514c@news.xs4all.nl> <3FA4284A.6010701@zg.htnet.hr> Message-ID: <3fa4395a$0$58698$e4fe514c@news.xs4all.nl> Haris Bogdanovic wrote: > Irmen de Jong wrote: > >> Haris Bogdanovic wrote: >> >>> When client is trying to connect to the server everything works fine >>> but when server tries to echo what it receieved from client I get >>> access denied error. >>> Why is that happening ? >> >> >> >> Because the server has no access? >> This was *important*: >> No really-- you have to give much more detailed information. >> Preferrably the exact code fragment and exact error message >> that you're getting. >> >> --Irmen Now, where is this extra information? >> > It's the example from python docs (socket section). If you have > somewhere your personal user account you can try it aswell. > Tell me what you managed to do. I managed to get it to work just fine. And what do you mean with 'have your personal user account' ???? --Irmen From gh at ghaering.de Fri Nov 21 07:14:22 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 21 Nov 2003 13:14:22 +0100 Subject: list of all functions defined in the current module In-Reply-To: References: Message-ID: <3FBE019E.8080905@ghaering.de> Fernando Rodriguez wrote: > Hi, > > How can I get the list of all the functions defined in the current module? If you have def getfunctions(module): import types l = [] for key, value in module.__dict__.items(): if type(value) is FunctionType: l.append(value) return l Then you can call this function with getfunctions(sys.modules[__name__]) to get a list of functions in the current module. Perhaps you could also use the builtin 'inspect' module for this task. -- Gerhard From newsgroups at jhrothjr.com Tue Nov 4 17:40:46 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 4 Nov 2003 17:40:46 -0500 Subject: prePEP: Decimal data type References: Message-ID: "Batista, Facundo" wrote in message news:mailman.445.1067979491.702.python-list at python.org... > John Roth wrote: > > #- I can see how what I said could be interpreted that way, but > #- I certainly > #- didn't mean it for strings. > > If you understand one thing and I understand another, one of both of us is > wrong, :p. Who? In my last example, what do you think that happens? I usually think that determining who was right or wrong is a waste of effort that could be better spent on finding a mutually satisfactory solution. I don't remember the exact example, so I'm guessing that the underlying issue is the one of not having an unambiguous decimal literal. As currently defined, Decimal(1.1) and Decimal("1.1") go through the same process: 1.1 first gets converted to a float, and then converted a second time to a Decimal. I'd rather not have even the potential for confusion. Part of the reason for wanting a type (rather than a class) is that it's much easier to justify a specific literal for a built in type. And it would not be that hard to do either, 1.1D is quite natural, and not all that easy to mistake for a float (the D isn't part of the float syntax in Python, although it is in other languages.) > #- It is. I was thinking in terms of a type, not a class. All > #- the builtin > #- types start with lower class names. > > OK, so it stays uppercase (as long it's a class). > > > #- What you propose? > #- > #- - the configuration (precision, flags, etc) is on by-instance basis > #- - you have different contexts, and a group of instances with each > #- context. > #- > #- [John Roth] > #- More likely the second. My concern here is the usual one with > #- singletons and globals. Processing gets very messy when you > #- have to operate in several different modes or areas. See the > #- difficulties people get into with internationalization when they > #- have an application that has to operate in several different > #- jurisdictions at once, etc. > > In another mail, Aahz explains (even to me) that the idea is to have a > "context per thread". So, all the instances of a thread belongs to a > context, and you can change a context in thread A (and the behaviour of the > instances of that thread) without changing nothing on the thread B. I saw his comment. I believe the reason why it needs to be thread local has more to do with data integrity than a desire to provide for multiple contexts, but if that's all that's possible, then that's what we'll get. > So, I think your proposal has future, as long I could finish the Aahz work, > ;) > > > #- So we're planning > #- on doing a software implementation of a *draft* standard, > #- including very complicated facilities that I most > #- respectfully think are going to be of marginal > #- utility. > > But is that or is making a Money data type and reinventing the wheel for all > its arithmetic behaviour. > > I can't assure you if somebody ever will use the "not a number" capabilities > of Decimal (I think a lot of people will). But that's the specification, :p The trouble is that we're trying to get two rather different things out of one implementation. The reason I say that they're rather different is that floating point and fixed point have very different application domains. Floating point is for continuous measurements of the kind that occur in the natural world, fixed point is for counting discrete entities, like coins. Floating decimal is better than floating binary in one respect, but it's still forcing two different things together. My personal opinion in the matter is that setting the precision high enough so that you won't get into trouble is a hack, and it's a dangerous hack because the amount of precision needed isn't directly related to the data you're processing; it's something that came out of an analysis, probably by someone else under some other circumstances. Given a software implementation, there's a performance advantage to setting it as low as possible, which immediately puts things at risk if your data changes. Fixed precision is also counter to the infinite precision we're moving toward with the integers; and integers are a more comfortable metaphor for money than floats. The natural implementation for fixed decimal is much simpler than for floating decimal. And I frankly don't think that floating decimal is going to get that much use outside of an accounting context, given that I think it's going to be a *lot* slower than built-in binary floating point. Especially if PyPy succeeds in their dream of creating a JIT for Python. John Roth > > . Facundo > From radam2 at tampabay.rr.com Wed Nov 12 16:00:46 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Wed, 12 Nov 2003 21:00:46 GMT Subject: case-sensitivity References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FB2738E.2B8C13FE@engcorp.com> <3fb275b2.55356282@news.cybermesa.com> Message-ID: <7075rv0d1thucjc617gibn4te7uoumh71c@4ax.com> On Wed, 12 Nov 2003 18:04:54 GMT, joconnor at cybermesa.com (Jay O'Connor) wrote: >On Wed, 12 Nov 2003 12:53:18 -0500, Peter Hansen >wrote: > >>Douglas Alan wrote: >>> >>> I agree with Alex. Case sensitivity is evil! When color monitors >>> started becoming common, I began to worry that programming languages >>> would come to allow you to have blue variable names, and red and green >>> variables names, and they would all be different. Or maybe even >>> variable names in mixed color! Then in mixed color and font. I >>> better be quiet now, lest I give anyone ideas. >> >>Not a bad idea... although the implementation would probably require >>something like using a special suffix to represent the colour, so the >>file could still be saved as ASCII. The editor would of course have >>to be smart enough to translate this suffix into the appropriate colour, >>and then suppress the suffix. I'm sure vi and that other editor, >>whatever it's called, could do that. > >There's a guy named Roedy Green, I believe, who hangs out in >comp.lang.somethingorother who has been advocating something pretty >close to this for a while. Except that he advocates using a database >based code management so you could store more meta information about >the code in the DB along with the text. This shows up onc.l.smalltalk >occasionally because most Smalltalk implementations do not use >text-file based code management so it fits in well with Smalltalk >schemes already Sounds a bit like the windows registry. Since it's there, why not put a bunch of other stuff in it. Wouldn't that just be fantastic. Then we could have everything in one convenient place! I hope nobody is thinking of that approach seriously. It may work well in places where the use is naturally limited in both scope and degree, but it becomes unmanageable when the size and content are allowed to grow with no limits on them. _Ron Adam From fms27 at cam.ac.uk Sun Nov 2 07:30:41 2003 From: fms27 at cam.ac.uk (Frank Stajano) Date: Sun, 02 Nov 2003 12:30:41 +0000 Subject: Tkinter pack bug in Python 2.3 Message-ID: <5.2.0.9.1.20031101223144.020511c0@localhost> The compact form of pack behaves differently (and I believe incorrectly) compared to the long form. The following two scripts demonstrate it, at least on this interpreter: Python 2.3.2 (#1, Oct 9 2003, 12:03:29) [GCC 3.3.1 (cygming special)] on cygwin # First script, no bug # I want a canvas inside a frame inside a toplevel, with the canvas # filling the toplevel even as I resize the window. This does it. from Tkinter import * root = Tk() frame = Frame(root, bg="lightBlue") frame.pack(side=TOP, expand=1, fill=BOTH) canvas = Canvas(frame, bg="lightGreen") canvas.pack(side=TOP, expand=1, fill=BOTH) mainloop() # Second script, bug # I want a canvas inside a frame inside a toplevel, with the canvas # filling the toplevel even as I resize the window. This doesn't do # it, and instead makes the canvas a sibling of the frame, instead of # a child. (Try resizing the toplevel and you'll see.) Why? from Tkinter import * root = Tk() frame = Frame(root, bg="lightBlue").pack(side=TOP, expand=1, fill=BOTH) canvas = Canvas(frame, bg="lightGreen").pack(side=TOP, expand=1, fill=BOTH) mainloop() Frank (filologo disneyano) http://www-lce.eng.cam.ac.uk/~fms27/ From davidb at mcs.st-and.ac.uk Tue Nov 25 15:58:13 2003 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 25 Nov 2003 12:58:13 -0800 Subject: Analyse of PDF (or EPS?) References: <3fbcc67e$0$9836$edfadb0f@dread14.news.tele.dk> <4de76ee2.0311201804.42d0c086@posting.google.com> <3fbe00e8$0$95070$edfadb0f@dread11.news.tele.dk> Message-ID: <4de76ee2.0311251258.2bcf8bea@posting.google.com> Johan Holst Nielsen wrote in message news:<3fbe00e8$0$95070$edfadb0f at dread11.news.tele.dk>... > David Boddie wrote: > > The full PDF specification is not exactly short, but it's fairly readable. > > Yep... I tried it... but there are no reason to do exactly the same - if > other people already have done that. And time is an issue too ;) Time is always an issue. How much of it do you have? ;-) > > I have a Python library which is able to identify a lot of the structure in simple > > documents, including basic text extraction, but I've become pretty disillusioned > > with it because so much work is required to extract more complex information. > > > > Maybe it's time to stick a license on it and upload it somewhere. > > Well, let me know ;) Maybe I could get an demo or something? That would > be nice :) You may be disappointed, but here it is: http://www.boddie.org.uk/david/Projects/Python/pdftools/ The core of the library was written in a hurry over two years ago; later refinements make it only slightly more robust. It was never really intended for anything other than exploring the structure of PDF files. Basic use: import pdftools file = "MyFile.pdf" doc = pdftools.PDFdocument(file) print "Document uses PDF format version", doc.document_version() pages = doc.count_pages() print "Document contains %i pages." % pages if pages > 123: page123 = doc.read_page(123) contents123 = page123.read_contents() print "The objects found in this page:" print print contents123.contents I've not really dealt with the coordinate system very well. Ideally, it would be trivial to extract all the device-independent positioning information but, whenever I start to look at this, I get distracted. :-) Have fun, and don't expect too much, David From huzzah at tampabay.rr.com Sat Nov 1 21:05:33 2003 From: huzzah at tampabay.rr.com (Todd Stephens) Date: Sun, 02 Nov 2003 02:05:33 GMT Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0310312008.ce341ea@posting.google.com> <87r80sdyb1.fsf@pobox.com> <7xn0bg6njb.fsf@ruckus.brouhaha.com> <7x7k2jpti9.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 01 Nov 2003 20:12:33 -0500, John Hall wrote: > The OP was about Rekall, not Kapital or BlackAdder. Rekall _IS_ in > Python. Sorry, typo on my part. I meant Rekall, and thank you for clearing it up. -- Todd Stephens From blk at srasys.co.in Sat Nov 29 03:26:51 2003 From: blk at srasys.co.in (bala) Date: Sat, 29 Nov 2003 13:56:51 +0530 Subject: How to Extract the Control Name in VB Application Using Python Message-ID: <004401c3b652$8ab754f0$440210ac@Bala> Iam using python....to invoke VBApplication...in the VBApplication contains lot controls...for Example 1.TextBox 2)CheckBox 3)Button 4)RadioButton 5)ComboBox 6)ListBox Outoff this six control....iam able to identify the Button,RadioButton and CheckBox Control...But iam not able to find the TextBox,Combobox and ListBox control name iam able to find the handle for all the control... Some of the Handle gives the Name and some of them is not giving the control name.... If you give solution for this problem...I will very thankfull to you Thanks&Regards Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhammond at skippinet.com.au Mon Nov 24 16:42:45 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 25 Nov 2003 08:42:45 +1100 Subject: instance of COM-server with Win32all In-Reply-To: References: Message-ID: Michel Claveau/Hamster wrote: > Hi ! > > I seek how to define a COM-server in "mono-instance". Do you know if there > are policies for that ? > I sought much, but did not find anything. And i had difficult with english. > > Python is great, Win32all is brilliant, but i am wedged in a corner. > > > * and sorry for my bad english * Babelfish was a great help * I think you are asking how to create a "singleton" using win32com. The simplest way is to *pretend* you have created one. Consider an object setup like this: class RealObject: def foo(self)... def bar(self)... realObject = RealObject() class COMOBject: _public_methods_ = "foo", "bar" def foo(self): realOBject.foo() def bar(self): realObject.bar() In this case, it doesn't matter how many "COMObject" objects are alive, as they will always delegate to the single "RealObject". If you want a true singleton, you will need to dig a little deeper into win32com, and create your own "policy". Mark. From FBatista at uniFON.com.ar Thu Nov 20 10:33:25 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 20 Nov 2003 12:33:25 -0300 Subject: regular expression to extract text Message-ID: Mark Light wrote: #- Hi I have a file read in as a string that looks like below. #- What I want to #- do is pull out the bits of information to eventually put in #- an html table. #- FOr the 1st example the 3 bits are: #- 1.QEXZUO #- 2. C26 H31 N1 O3 #- 3. 6.164 15.892 22.551 90.00 90.00 90.00 #- #- ANy ideas of the best way to do this - I was trying regular #- expressions but #- not getting very far. What is the exact result you're trying to reach for that example? . Facundo From haris.bogdanovic at zg.htnet.hr Sat Nov 1 16:53:37 2003 From: haris.bogdanovic at zg.htnet.hr (Haris Bogdanovic) Date: Sat, 01 Nov 2003 22:53:37 +0100 Subject: simple echo server In-Reply-To: <3fa3fab9$0$58702$e4fe514c@news.xs4all.nl> References: <3fa3fab9$0$58702$e4fe514c@news.xs4all.nl> Message-ID: <3FA42B61.7090103@zg.htnet.hr> Irmen de Jong wrote: > Haris Bogdanovic wrote: > >> When client is trying to connect to the server everything works fine >> but when server tries to echo what it receieved from client I get >> access denied error. >> Why is that happening ? > > > Because the server has no access? > > No really-- you have to give much more detailed information. > Preferrably the exact code fragment and exact error message > that you're getting. > > --Irmen > It's the example from python docs (socket section). If you have somewhere your personal user account you can try it aswell. Tell me what you managed to do. Thanks Haris From peter at engcorp.com Wed Nov 5 07:50:01 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 05 Nov 2003 07:50:01 -0500 Subject: Why no try-except-finally ? References: <20031105050706.29195.00000178@mb-m22.aol.com> Message-ID: <3FA8F1F8.62A0D382@engcorp.com> KefX wrote: > > For now I rewrote it like this, just a modified version of what you suggested: > > err_code = 0 > try: > game.Play() # was PlayGame() before > except: > err_msg = "FATAL ERROR: " + sys.exc_info()[0] > logger.critical(err_msg) > err_code = 1 > > DeInit() > return err_code Somewhat better style, generally, IMHO, would be to replace "err_code = 1" with "raise" in the above. Consider returning error codes to be a parallel (and somewhat obsolescent) way of communicating failures to calling code. Raising an exception should be generally preferred. Note, however, that doing this (re-raising the exception) brings you back to your original query as well, as DeInit() would not get called if it were not in a try/finally. A second style point: use a general try/except (without specifying the exceptions to be caught) is usually a Very Bad Idea. It's okay at the top level of a module, but it will mask all kinds of bugs at the lower levels. For example, in the above you might have misspelled Play() as play() and you would get an AttributeError, but would think that it was the call to Play() which had raised an exception and the "FATAL ERROR". Again, however, restricting the set of exceptions called means that in the case where one of the unhandled ones is raised (unhandled at this particular level, anyway), you still want a finally clause to ensure DeInit() is executed. I'd say, in response to the original question, that the nested try/except in the try/finally is the appropriate, preferred Pythonic idiom. -Peter From __peter__ at web.de Mon Nov 24 17:36:46 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Nov 2003 23:36:46 +0100 Subject: Newbie here... getting a count of repeated instances in a list. References: Message-ID: Amy G wrote: > I now have two dictionaries, each with domains and frequncies. I want to > have the domains which appear in both to be deleted from the first one. > > Is there an easy way to do this? >>> first = {"a": 10, "b": 20} >>> second = {"b": 5, "d": 7} >>> for dom in second: ... first.pop(dom, None) ... 20 >>> first, second ({'a': 10}, {'b': 5, 'd': 7}) >>> Peter From francisgavila at yahoo.com Mon Nov 10 02:38:37 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 10 Nov 2003 02:38:37 -0500 Subject: Bad docs for os.path.isabs() References: <3FAEB530.D67D27BC@engcorp.com> Message-ID: "Georgy Pruss" wrote in message news:n9Drb.105819$IA2.3757726 at twister.southeast.rr.com... > > "Peter Hansen" wrote in message news:3FAEB530.D67D27BC at engcorp.com... > >>> os.path.isabs("C:\\foo\\..\\bar") > True > >>> os.path.abspath("C:\\foo\\..\\bar") > 'C:\\bar' > > And both are right > G-: > > > (Or some variation on that... i.e. leave the actual specification > > to the nuts-and-bolts of the platform-dependent code, rather than > > trying to rewrite it in English and risk duplication/errors.) > > > > -Peter Ugh. "Return True if path is not relative to the current working directory." Better: "Return True if path is not a relative pathname." -- Francis Avila From jbublitzno at spamnwinternet.com Fri Nov 7 23:21:50 2003 From: jbublitzno at spamnwinternet.com (Jim Bublitz) Date: Sat, 08 Nov 2003 04:21:50 GMT Subject: ANN: PyKDE now does KDE plugins References: <87sml01hgc.fsf@pobox.com> Message-ID: John J. Lee wrote: > Jim Bublitz writes: > [...] >> required. This is the first in what's planned to be a number >> of extensions for PyKDE that allow plugins and related objects >> to be created entirely in Python; David Boddie is nearing >> release of modules for authoring KParts for export (PyKDE >> already imports KParts), KDE Control Center modules, and >> IOSlaves. >> >> Future plans include allowing QWidget subclasses created in >> Python to be imported into Qt Designer with complete >> functionality, and possibly Python scripting and plugins for >> KDE apps like KOffice and Kontact. The underlying mechanisms >> and code are similar in all cases. > [...] > > Wow, sounds like impressive stuff. How does it work? Is there > a standard .so proxy that can be used by all Python plugins? Basically yes - it's a little more convoluted than that. Panel applets need a .desktop file which specifies the .so lib to load. The .so specified is symlinked to the proxy, so it's filename is correct and unique, but still runs the proxy code. (There's a fake .la file in this case too, since the loader expects one) The .so proxy starts another .so that wraps the Python interpreter, and from the config file name that the plugin loader passes in it computes the name of the .py file. The .py file is loaded into the interpreter, and the Python factory function is located and called. That constructs the actual applet (from Python via PyKDE/PyQt). A PyObject is returned to the proxy .so which uses sip/PyKDE to convert it to a C++ pointer to the required type which is passed back to the loading app. The same scheme will work for almost any plugin - the major difference is that in some cases the plugin loader doesn't provide enough info to allow a proxy for the .so file (for example, to load "somePlugin" the loader might expect libsomePlugin with an init_somePlugin factory function in C++). For those cases, the plan is to autogenerate the plugin-specific .so file (naming is the only thing that varies), but it still requires a C++ 'make" step. For panel applets, there's an installer that does most of the work (except for actually writing the py file) and does things like validate and serve as a test harness. Plugins can be hard to debug, and a failed load rarely returns any error info, so t it's helpful to be able to run the plugin outside the loading app. It takes more lines than to describe than to implement - it really isn't much code. David Boddie, who did a lot of the development on panel applets has a bunch of other stuff coming soon - KParts (including a Wiki KPart), IOSlaves, KDE Control Center plugins. The same scheme will also work for styles, QtDesigner plugins and apps that take plugins. Quite a while ago I had a similar KSpread (KOffice spreadsheet) plugin working using a cruder version of the same basic idea. Apps require a Python wrapper for their API to be useful, but that's also pretty simple to write using sip (for a well-written app anyway). > What sort of memory footprint do these plugins have? The "Presidential" answer is: not very big at all. The real answer is that by the time you load PyQt and the necessary PyKDE modules you're up around 10MB or more I'd guess (plus other shared libs that will already have been loaded). The Python interpreter .so adds about another MB, the plugin code itself is in Python and only maybe 5KB to a few hundred KB depending on complexity. The proxy .so is very small too. My opinion is that this is great for prototyping, but some people are willing to spend that much memory to be able to do plugins in Python. I had one applet running for a few weeks, and I'd have to say that on a machine with 1GB of memory it isn't a big deal, but I still find it a little mind-boggling - maybe 20X what the original IBM PC came with just to run a 40x40 pixel panel applet. There's a couple places I find this really worthwhile though - if you're writing an app with PyQt/PyKDE in the first place or regularly have an app running based on those, the memory cost is minimal because it's all in shared libs. The other really useful place is a situation like the spreadsheet plugin I mentioned - it only took about 2MB total and allowed all kinds of stuff the app itself couldn't do (eg manipulate a spreadsheet in the background). That's based on a thin wrapper instead of a complete set of bindings and no GUI programming in the plugin (basically no PyQt or PyKDE). >> In some cases, specific .so libs will still be required >> (depends on the plugin loader), but the Python modules will >> include autogeneration of the necessary C++ code, along with >> installers to simplify the task of making the plugins >> available. > What makes the difference between all-Python and needing a bit > of C++ here? Just what the app loading the plugin expects to find. If the factory or init function of the plugin is uniquely named, there isn't a convenient way to intercept the call - well there probably is, but I haven't figured it out yet. If someone knows more about .so loading and structure than I do and sees a solution I'd be interested in hearing about it. I'm sure there must be a way to hack the .so's symbol table or some such, but it's beyond me at them moment. I suppose if the parameters passed to the plugin don't convey the necessary info, that would be another case, but I don't think that occurs in KDE or Qt. On the other hand, there's really no reason why a proxy wouldn't *always* work if C++ developers allowed for it - always call a factory function with the same name ("init", "create". whatever) and pass in an identifying string for locating the plugin. Probably makes C++ plugins a little harder to write though. Jim From peter at engcorp.com Sun Nov 23 09:28:04 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Nov 2003 09:28:04 -0500 Subject: Empty list as default parameter References: Message-ID: <3FC0C3F4.D1AABE06@engcorp.com> Stian S?iland wrote: > > * Robin Munn spake thusly: > > Look at this, for example: > > > > > > n = 5 > > def f(x = n): > > return x > > n = 3 > > > > print n # Prints 3 > > print f() # Prints 5 > > > > Note that the default argument to f() is the value of n when the def > > statement was executed, not the value of n when f() is called. > > Wouldn't it be more logical for a programmer that x should evaluate > to '3' inside f()? > > I can't see what is the purpose of binding default variables at > definition time instead of runtime. Purpose? Who needs a purpose? ... "def" is a *statement* in Python, so naturally the code in the argument list is mostly easily handled at definition time, when the def statement is being executed, rather than at run time. It also means that the default arguments don't have to be evaluated dynamically each time the function is called, which would in some cases be a performance nightmare... -Peter From missive at frontiernet.net Fri Nov 7 20:33:35 2003 From: missive at frontiernet.net (Lee Harr) Date: Sat, 08 Nov 2003 01:33:35 GMT Subject: try...finally is more powerful than I thought. References: <3faab4e8$0$559$b45e6eb0@senator-bedfellow.mit.edu> <3FAABC88.5A696162@engcorp.com> <3FAB1FB9.75E5A787@engcorp.com> Message-ID: On 2003-11-07, Peter Hansen wrote: > Lee Harr wrote: >> >> >>> def res(): >> ... print 1 >> ... try: >> ... print 2 >> ... return 3 >> ... print 4 >> ... finally: >> ... print 5 >> ... >> >>> res() >> 1 >> 2 >> 5 >> 3 >> >> interesting. > > Why? It just proves that "finally" works, and > executes when the return statement is encountered. > > (The point of my examples was to show that finally can > actually override the value that would otherwise have been > returned. I thought that was interesting, but unfortunately > I'm not sure what your example adds to the previous two posts. > Maybe I'm just missing the point...) > Yes. I just found the entire thread interesting. I know that people who are unfamiliar with the try ... finally syntax can easily fire up the interpreter and play around with it for themselves, but I thought the "basic functionality" example might make the rest of the thread more clear. I have written a lot of python code and have never used finally. From joconnor at cybermesa.com Wed Nov 26 12:51:39 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Wed, 26 Nov 2003 10:51:39 -0700 Subject: polymorphism in python In-Reply-To: <6bWwb.40604$Fv8.39489@twister01.bloor.is.net.cable.rogers.com> References: <6bWwb.40604$Fv8.39489@twister01.bloor.is.net.cable.rogers.com> Message-ID: martin z wrote: >A very interesting invention... does it work with parameter defaults? Oh, >and IIRC, the word you're looking for is "Function overloading" not >"polymorphism". Polymorphism refers to the ability to have completely >different objects that can be used the same way, which Python always has. > > > > "Function overloading" is still one form of polymorphism. Polymorphism as a concept can be approached in different ways, including function overloading, generic programming and inheritance. Languages like Python are Smalltalk are very good at implementing polymorphism based on sending a message to an object and as long as the object understands the message, it doesn't matter what the object is (part of their dynamic binding); but they are not as good at overloading based on argument types (how do you have two methods that have the same name but one takes a single integer argument and one takes a single string argument? answer, you have one function with an 'if' decision, or you have two functions with two different names, breaking the polymorphism, or for more complex objects you get doule-dispatch involved) . Languages like C++ and Java restrict polymorphism of objects to those within the hierarchy, but do allow for polymophism by function overloading; C++ and Ada also have polymopshim through generic programming (generics in Ada, templates in C++) From reply.in.the.newsgroup at my.address.is.invalid Fri Nov 14 14:53:17 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 14 Nov 2003 20:53:17 +0100 Subject: for what are for/while else clauses References: Message-ID: Diez B. Roggisch: >today I rummaged through the language spec to see whats in the for ... else: >for me. I was sort of disappointed to learn that the else clauses simply >gets executed after the loop-body - regardless of the loop beeing entered >or not. > >So where is an actual use case for that feature? To execute code only when the loop terminates normally, not when it terminates because of a break statement. It's been discussed before: http://groups.google.nl/groups?q=%2Bfor+else+group:comp.lang.python&hl=nl&lr=&ie=UTF-8&oe=UTF-8&selm=slrn9teq1k.1vd.huaiyu%40gauss.almadan.ibm.com&rnum=3 http://groups.google.nl/groups?q=%2Bfor+else+group:comp.lang.python+break&hl=nl&lr=&ie=UTF-8&oe=UTF-8&selm=uofzrqjex.fsf%40ctwd0143.fitlinxx.com&rnum=7 http://groups.google.nl/groups?hl=nl&lr=&ie=UTF-8&oe=UTF-8&threadm=uofzrqjex.fsf%40ctwd0143.fitlinxx.com&rnum=7&prev=/groups%3Fq%3D%252Bfor%2Belse%2Bgroup:comp.lang.python%2Bbreak%26hl%3Dnl%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26selm%3Duofzrqjex.fsf%2540ctwd0143.fitlinxx.com%26rnum%3D7 -- Ren? Pijlman From mlerner at NO.SPAM.umich.PLEASE.edu Wed Nov 5 17:43:35 2003 From: mlerner at NO.SPAM.umich.PLEASE.edu (Michael George Lerner) Date: Wed, 05 Nov 2003 22:43:35 GMT Subject: Is this horrible python code? References: Message-ID: Matthew wrote: > Hi, > class call_me(object): > def __init__(self, func, *args, **kw): > self.func = func > self.args = args > self.kw = kw > def __call__(self, *args, **kw): > print "Execing..." > return self.func(*self.args, **self.kw) I'm not sure what you're trying to do with the rest of this, but I think that your call_me class isn't doing what you want. asteroids% python Python 2.2 (#1, Feb 18 2002, 14:48:51) [C] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> class A(object): ... def __init__(self,a): ... self.a = a ... def __call__(self,a): ... print "self.a is '%s' and a is '%s'" % (self.a,a) ... >>> a = A('the first thing') >>> a('the second thing') self.a is 'the first thing' and a is 'the second thing' >>> so, i don't think your __call__ method will do what you want. then again, i'm not exactly sure what you're trying to do, so i can't figure out why you want to initialize things your objects with func, args and kw *and* want to be able to specify args and kw at call time. -michael From vmilitaru at sympatico.ca Fri Nov 7 08:34:52 2003 From: vmilitaru at sympatico.ca (Vio) Date: Fri, 07 Nov 2003 08:34:52 -0500 Subject: simple float numbers problem Message-ID: <3FAB9F7C.3060901@sympatico.ca> I need to test for equality between simple 2 decimal numbers. For example: if (10 + 15.99) == 25.99: do some stuff... The preceding sentence should be TRUE, but to Python it appears FALSE. Which is wrong. Perhaps because Python translates "25.99" to "25.98999999999999998" and not "25.99", which may be the reason for this error (me guessing...). If that's the case, how do I force Python to only use 2 decimal points, and not "make up" superfluous decimals? Or if that's not the cause for the problem, how do I make Python see my math expression as TRUE (as it "should" be)? Cheers, Vio PS. If it's of any help, I'm using Python2.3 (GCC 2.95.4 20011002 (Debian prerelease)) From roy at panix.com Wed Nov 26 16:53:36 2003 From: roy at panix.com (Roy Smith) Date: Wed, 26 Nov 2003 16:53:36 -0500 Subject: polymorphism in python References: <6bWwb.40604$Fv8.39489@twister01.bloor.is.net.cable.rogers.com> Message-ID: Jay O'Connor wrote: > Languages like Python [and] Smalltalk [...] are not as good at > overloading based on argument types (how do you have two methods > that have the same name but one takes a single integer argument > and one takes a single string argument? But how often is it actually useful to do such a thing? I can't remember the last time I wanted to do something like that in Python. Did lots of it in C++, but that's more working around the language than anything else. Can you think of a good example of why you would want to do something like that in Python? If your intent is that you could call foo(4) or foo('4'), you could just write: def foo (x): theRealX = int (x) or you could maybe even do: def foo (x): if type(x) == StringType: do string stuff else: do integer stuff but if you're trying to do either of the above, I suspect you're trying to write C++ in Python (which is as bad, if not worse, as trying to write Fortran in Python). From grisha at apache.org Fri Nov 28 12:22:13 2003 From: grisha at apache.org (Gregory (Grisha) Trubetskoy) Date: Fri, 28 Nov 2003 12:22:13 -0500 Subject: [ANNOUNCE] Mod_python 3.0.4 and 2.7.9 Message-ID: <20031128120645.Q92149@onyx.ispol.com> The Apache Software Foundation and The Apache HTTP Server Project are pleased to announce the release of versions 3.0.4 and 2.7.9 of mod_python. These two releases (for HTTP Server 2.0 and 1.3 respectively) address an issue whereby a specific query string processed by mod_python would cause the httpd process to crash. These two releases have also been patched to compile against Python 2.3 cleanly. There are no other changes or improvements from the previous version in these releases. Both of these releases are considered stable. If you are currently using mod_python 3.0.3 or 2.7.8, it is highly recommended that you upgrade to 3.0.4 or 2.7.9. Mod_python is available for download from: http://httpd.apache.org/modules/python-download.cgi For more information about mod_python visit http://www.modpython.org/ Regards, Grisha Trubetskoy From tuanglen at hotmail.com Tue Nov 18 18:03:23 2003 From: tuanglen at hotmail.com (Tuang) Date: 18 Nov 2003 15:03:23 -0800 Subject: syntax philosophy References: <873ccm78f3.fsf@strauser.com> Message-ID: Kirk Strauser wrote in message news:<873ccm78f3.fsf at strauser.com>... > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > At 2003-11-17T21:29:16Z, tuanglen at hotmail.com (Tuang) writes: > > > In Python, apparently you have to first remember to declare your > > dictionary outside the loop: > > > > histogram {} > > Note that you have to declare: > > my %histogram; > > outside the loop in Perl if use want it to be "use strict"-safe. And you > *do* want that, don't you? Actually, I don't, so your point is a good one. I occasionally build something big enough in Perl that "use strict" matters (me:"What? Perl CGI is the only platform available?", them:"Yep. Take it or leave it"), but that's not my preferred use for Perl. My preferred use is when I encounter some data in one form and I want to quickly process it into another form with about two minutes of work and less than ten lines of code. Sort of like using a particularly powerful sed+awk+grep+sort+... all rolled into one utility. I don't want to have to set things up. I just want to tell it what I want and have it take care of the overhead (declaring variables, initializing them to zero, taking care of memory, etc.) I was hoping that Python would be just as easy to use in that role AND scale better to larger programs. I'm convinced that it will scale better, but there is apparently a rather small but still real cost in inconvenience at the "one-liner" level. From aleax at aleax.it Fri Nov 14 09:47:02 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Nov 2003 14:47:02 GMT Subject: conceiling function calls.. References: <20j9rvsi2a1gi6emn1totgqipff6v5vr4a@4ax.com> Message-ID: Emile van Sebille wrote: > Gon?alo Rodrigues: >> Can you explain why you would want to do that? What possible gain > can >> you have by counfounding name lookup with calling? >> > > Well, I can't explain for the OP, but I found it (some years ago... > I'm not sure I'd do the same thing now) convenient in a prototype > minimalist database application. Data fields could always be inferred > if not actually present in the instance. Thus when programming you > could write: > duedate = order.shipdate + order.terms.duedays > without shipdate or terms being attributes of order. > > Similarly, > lineextenion = lineitem.qty * lineitem.price > without price or print the destination address without having > designated a shipto. > > This allowed order entry to get along with only the minimum "how many > of what go where" being entered. Everything else could be swizzled up > when needed if not present. I specifically wanted the data structure > to be an implementation detail. I see your use case as perfectly fine and totally unconnected to the OP's requirement. The concept of a property or dynamically fetched attribute of an object, such as your 'order' or 'lineitem', is perfectly fine (it is, however, valse that shipdate or terms would not be attributes of order -- hasattr would show this as being false -- if they can be accessed with this syntax, they ARE attributes, by Python's definition, even if they're computed via the property or __getattr__ routes). Having x.y "mean" x().y for some _function_ x is quite a different thing. _Functions_ don't have __getattr__ nor properties, they do have a simple dictionary where you can set arbitrary attributes and later fetch them back again, that's all. Properties and other dynamically computed/fetched attributes are typical of instamces of some user-coded classes that need such dynamism, not of functions. Alex From abriggs at westnet.com.au Mon Nov 3 06:54:30 2003 From: abriggs at westnet.com.au (Anthony Briggs) Date: Mon, 3 Nov 2003 19:54:30 +0800 Subject: nearest neighbor in 2D In-Reply-To: References: Message-ID: At 10:12 PM -0600 2/11/03, John Hunter wrote: >I have a list of two tuples containing x and y coord > > (x0, y0) > (x1, y1) > ... > (xn, yn) > >Given a new point x,y, I would like to find the point in the list >closest to x,y. I have to do this a lot, in an inner loop, and then I >add each new point x,y to the list. I know the range of x and y in >advance. One method that you can use is to narrow down the list of candidates by only considering those points within a box around your new point, eg xn-5 < x < xn+5, yn-5 < y < yn+5. You'll still need to test using trigonometric stuff after that, and also that there won't be a point outside the square that'll be closer, ie. that your closest point is < 5 away from the new point. You might also consider sorting the list by distance from some other point (eg. 0,0), and keeping it sorted as you add new points - it'll take some time to do, but might make things faster overall when searching. Hope that helps, Anthony -- ---------------------------------------------------- HyPEraCtiVE? HeY, WhO aRE YoU cALliNg HypERaCtIve?! aBRiGgS at wEStNeT.cOm.aU ---------------------------------------------------- From jussij at zeusedit.com Sun Nov 2 19:05:14 2003 From: jussij at zeusedit.com (Jussi Jumppanen) Date: Mon, 03 Nov 2003 11:05:14 +1100 Subject: ActivePython or Python2.2.3+win32? References: <9i0bqvs4ir5963iiiv5bpukejvirga6gm1@4ax.com> <87ekwq74y0.fsf@pobox.com> Message-ID: <3FA59BBA.7611@zeusedit.com> Andrei wrote: > Docs are better. CHM file including a Dive into Python, the FAQ, > PEPs, the complete python docs and then some more in a format > which is easy on the eyes. FWIW using this tool: http://www.confluent.fr/javadoc/htmltohlpe.html will make it very easy to convert html documents to the Windows help file format. IMHO definitely worth a look for Win32 developers. Jussi Jumppanen Author of: Zeus for Windows (All new version 3.90 out now) "The C/C++, Cobol, Java, HTML, Python, PHP, Perl programmer's editor" Home Page: http://www.zeusedit.com From bokr at oz.net Tue Nov 18 18:44:47 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Nov 2003 23:44:47 GMT Subject: good ways to convert string into time References: <731fc603.0311180958.32135957@posting.google.com> Message-ID: On 18 Nov 2003 09:58:08 -0800, soundwave56 at yahoo.ca (Hank) wrote: >hi, > >i have a string as follows > >18Nov2003:18:23:43:405 > >Is there an easy way to convert that to absolute time? What i really >want to do is to parse these times from a log file and do time >comparisons, averages, stop minus start (elapsed). > >Probably create my own conversion table i guess? > >thanks Quick and dirty using the time module (and re to split your string) Not tested beyond what your see here! ====< s2t.py >================== import time,re rxo = re.compile(r'(\d+)([a-zA-Z]+)(\d+):(\d+):(\d+):(\d+):(\d+)') monthnums = dict([(mo,i+1) for i,mo in enumerate( 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split())]) def s2t(s, dst=-1): # guess daylight svgs da,mo,yr,hr,min,sec,ms = rxo.search(s).groups() mo = monthnums[mo] tinfo = map(int, (yr,mo,da,hr,min,sec,ms)) ms = tinfo.pop() return time.mktime(tinfo+[0,0,dst])+ms/1000.0 ================================ >>> import s2t >>> s2t.s2t('18Nov2003:18:23:43:405') 1069208623.405 >>> import time >>> time.ctime(s2t.s2t('18Nov2003:18:23:43:405')) 'Tue Nov 18 18:23:43 2003' IOW, s2t converts your time info to a floating point number in seconds from the epoch, which e.g., time.ctime and other time functions can use. The milliseconds (I assumed) are ignored by ctime, but I tacked them on in the number returned. (Note that floating point won't represent all decimals accurately, but it should be good rounded to ms, e.g., >>> from ut.exactdec import ED >>> ED(s2t.s2t('18Nov2003:18:23:43:405'),'all') ED('1069208623.4049999713897705078125') That's all the bit info. Looks like a good four 9's below your ms unit. >>> ED(s2t.s2t('18Nov2003:18:23:43:405'),'all').round(3) ED('1069208623.405') PS. I think there is a bug in time.mktime -- I accidentally got it trying to find time zero: >>> s2t.s2t('01Jan1970:00:00:00:000', 1) 25200.0 >>> s2t.s2t('31Dec1969:23:00:00:000', 1) 21600.0 >>> s2t.s2t('31Dec1969:17:00:00:000', 1) 0.0 >>> s2t.s2t('31Dec1969:17:00:00:000', 0) 3600.0 >>> s2t.s2t('31Dec1969:17:00:00:000', 1) 0.0 >>> s2t.s2t('31Dec1969:16:00:00:000', 1) (boom) I got: The instruction at "0x7802a7ff" referenced memory at "0x00000000". The memory could not be "read". That shouldn't happen no matter what garbage I type as args, ISTM ;-/ Guess I'll post a plainer mktime example separately. Regards, Bengt Richter From mikit at zoran.co.il Wed Nov 5 10:55:59 2003 From: mikit at zoran.co.il (Miki Tebeka) Date: 5 Nov 2003 07:55:59 -0800 Subject: Testing & stdout References: <6250403b.0311040151.32fd4754@posting.google.com> <3FA7A9B1.D09ED381@engcorp.com> <3FA7C976.7AF9749D@engcorp.com> <6250403b.0311042334.7cf5a8ce@posting.google.com> Message-ID: <6250403b.0311050755.5c404581@posting.google.com> Hello John, > > > If it's at the module level, then the unit test suite has to do > something > > > different. I'd fix the offending module, but possibly he isn't using > > > XP, so he can't do that. > > > XP as in eXtreme Programming? What's the connection? > > Shared code ownership. The classical model says the tester writes > up a report and gets frustrated. The XP model says that if you find > it hard to test, you find a developer, sit down with him and fix it > so you can test it. OK. Since I wear both hats (coding & testing) it's not an issue. Miki From spam at thalassa.informatimago.com Sun Nov 2 07:09:37 2003 From: spam at thalassa.informatimago.com (Pascal Bourguignon) Date: 02 Nov 2003 13:09:37 +0100 Subject: Paging Mr. Rettig [ws Re: Explanation of macros; Haskell macros] References: <87brs2tjut.fsf@memetrics.com> Message-ID: <87n0bfhszi.fsf@thalassa.informatimago.com> Kenny Tilton writes: > Cue Duane of Franz. He mentioned over lunch at ILC2003 where John > McCarthy used my laptop for ten minutes that their Allegro Common Lisp Just put "John McCarthy used my laptop for ten minutes" in your signature and forget it! :-) -- __Pascal_Bourguignon__ http://www.informatimago.com/ From tweedgeezer at hotmail.com Tue Nov 18 05:59:47 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 18 Nov 2003 02:59:47 -0800 Subject: Can this be written more concisely in a functional style References: <92c59a2c.0311171648.6360213d@posting.google.com> <92c59a2c.0311172340.544faac6@posting.google.com> Message-ID: <698f09f8.0311180259.bdd4359@posting.google.com> jcb at iteris.com (MetalOne) wrote in message news:<92c59a2c.0311172340.544faac6 at posting.google.com>... > Maybe my post was not clear. > I want a means to test if there exists an element in the list that > satisfies a predicate. Sure there is. The code that you showed was an excellent way to do so. > Actually, when I word it that way, I guess what I want is PEP 289, > universal and existential qualifiers. > > I guess I'll have to wait. Why? Why not just stuff the code you wrote into an appropriately named function and use that? Anyway, here are more efficient implementations: def any(p, seq): """Returns true if any element in seq satisfies predicate p.""" for elt in itertools.ifilter(p, seq): return True else: return False def all(p, seq): """Returns true if all elements in seq satisfy predicate p.""" for elt in itertools.ifilterfalse(p, seq): return False else: return True Jeremy From jdhunter at ace.bsd.uchicago.edu Sun Nov 2 13:56:01 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 02 Nov 2003 12:56:01 -0600 Subject: gdmodule max colors Message-ID: GD module has a constant gdMaxColors >From the web page: Maximum number of colors in an image; GD will likely change this figure in a future version. Is there any way to increase this number? In the GD FAQ, there is an entry about missing colors in JPEG images that reads When creating truecolor images, you need to call gdImageCreateTrueColor, not gdImageCreate. but I see no analog of this in gdmodule. I tried increasing gdMaxColors to 2048 in gd.h of the GD src and recompiled it and gdmodule. When I do >>> import gd >>> print gd.gdMaxColors 2048 I get the right answer, but then I get a segfault when I try and create my image. I am creating pseudo-color plots in GD and would like to have a larger color pallet. Suggestions? Thanks, John Hunter gdmodule-0.42 gd-2.0.15 From peter at engcorp.com Mon Nov 10 18:06:33 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Nov 2003 18:06:33 -0500 Subject: "Autocoding Reloaded" (was Re: Matrix - Metaphors, Analogies and the REAL References: <3FB008DB.A4F3E01@engcorp.com> Message-ID: <3FB019F9.28B5CEBC@engcorp.com> 3seas wrote: > > Peter Hansen wrote: [Tim snipped everything I wrote and responded to none of it.] > Actually the most up to date code is not teh archive but what you get by > doing a wget on threeseas.net/vic/ excluding the .zip files. > But then that might be what you did. No, but thanks for the pointer. I don't feel there's any point in my investigating further at this time, however, as you've said nothing to address my points -- which increases my confidence in the accuracy of my analysis. > The full VIC will be able to set in motion dynamic automations, from simple > to complex of any number of automation types, from simple user defined > automations to more complex code generation AND compiling And Excution of > generated code. That would be much fun to see... what is there at this point is so far from being able to do anything resembling code generation or compilation that I doubt anyone but you can imagine what it is all about. > I have no doubt there have been and continue to be arguements against this > or that part of the VIC but no where will you find the integrated > configuration of all the parts in a manner that provides such versatility > as the VIC will. If we can't find it, maybe we just don't understand what we're looking for yet. I believe I've got a decent understand, to the extent possible, of what you imagine you are working on, and I believe I know of a variety of viable -- and usable! -- alternatives, such as Scons and A-A-P, or even just make in all its primitive glory, possibly combined with a little Python code. > Its not the objective to re-invent anything but rather to make the use and > reuse of many things possible, including the dynamic reuse of code > fragments to generate more complex code. Sounds a little vague, and to the extent that I can understand the least aspect of it, it sounds no different from what any decent build tool, combined with a general-purpose language like Python, could do. Anyway, my analysis stands. -Peter From bokr at oz.net Mon Nov 17 19:47:45 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Nov 2003 00:47:45 GMT Subject: PEP 321: Date/Time Parsing and Formatting References: <20031117161752.GA17615@nl.linux.org> Message-ID: On Mon, 17 Nov 2003 17:59:24 -0500, "John Roth" wrote: > >"Gerrit Holl" wrote in message >news:mailman.803.1069091744.702.python-list at python.org... >> Hi, >> >> PEP 321 reads: >> > Python 2.3 added a number of simple date and time types in the >> > ``datetime`` module. There's no support for parsing strings in various >> > formats and returning a corresponding instance of one of the types. >> > This PEP proposes adding a family of predefined parsing function for >> > several commonly used date and time formats, and a facility for generic >> > parsing. >> >> I was recently surprised by this fact. I don't know why there isn't >> such a function/method. In my opinion, it isn't a question of whether >> to add them or not, but how. >> >> > Input Formats >> > ======================= >> > >> > Useful formats to support include: >> > >> > * `ISO8601`_ >> > * ARPA/`RFC2822`_ >> > * `ctime`_ >> > * Formats commonly written by humans such as the American >> > "MM/DD/YYYY", the European "YYYY/MM/DD", and variants such as >> > "DD-Month-YYYY". > >I didn't notice this going past the first time: YYYY/MM/DD is the ^--UIAM, NOT! >ISO standard format, DD/MM/YYYY is the European variant to >the American MM/DD/YYYY. I thought '-' delimiters were standard, and the yyyy-mm-dd ordering standard, and anything else a variant. See http://www.w3.org/TR/NOTE-datetime or http://www.iso.ch/iso/en/prods-services/popstds/datesandtime.html [...] Regards, Bengt Richter From daniels at dsl-only.net Fri Nov 14 00:14:39 2003 From: daniels at dsl-only.net (sdd) Date: Thu, 13 Nov 2003 21:14:39 -0800 Subject: Access sql with python, please. I'm desperate In-Reply-To: <3fb46bdc$1@nntp0.pdx.net> References: <3fb31f7a$1@nntp0.pdx.net> <3fb46bdc$1@nntp0.pdx.net> Message-ID: <3fb472b5$1@nntp0.pdx.net> I wrote: > That said, on at least some systems you can say: > > SELECT * for (SELECT age, weight FROM personnel) > WHERE age in (SELECT age FROM retirees) When of course I meant to write: SELECT * FROM (SELECT age, weight FROM personnel) WHERE age IN (SELECT age FROM retirees) -Scott David Daniels Scott.Daniels at Acm.Org From nards_collective at yahoo.com.au Tue Nov 18 07:03:50 2003 From: nards_collective at yahoo.com.au (nards_collective) Date: Tue, 18 Nov 2003 12:03:50 -0000 Subject: new guy Message-ID: I'm new to Python, in fact I'm new to programming. I'm trying to write a simulation program, for a biology class I'm teaching next year. the following code is giving me trouble and i can't work out why. if e>= 1 : a=e else : a=0 I keep getting a syntax error. This piece of code is meant to keep the value of a equal to or grater than 0. Any odeas would be appreciated. THAnkS NArDS From tzot at sil-tec.gr Wed Nov 12 22:05:19 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 13 Nov 2003 05:05:19 +0200 Subject: Check of a Page About Python References: <3FAE6776.4040609@ithcorp.com> Message-ID: Xaire Anastasie. On Wed, 12 Nov 2003 17:12:37 +0100, rumours say that Eric Williams might have written: >Looks alright, but I'd be interested to know why you designate python a 4GL? >You might want to check your jargon lexicon on that one. Yep. If you want to improvise, change 4GL into NGL (for next generation language ;) 4GL was a term coined for higher level languages tied to a specific domain, AFAIK SQL servers. It's not trendy anymore :-) 'Scripting language' is OK, since this is what Python will be used for in FreeGee. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From stephen at dino.dnsalias.com Tue Nov 4 00:18:09 2003 From: stephen at dino.dnsalias.com (Stephen J. Bevan) Date: Tue, 04 Nov 2003 05:18:09 GMT Subject: Explanation of macros; Haskell macros References: <87brs2tjut.fsf@memetrics.com> Message-ID: Peter Seibel writes: [snip] > Now that's pretty trivial. But now we can use SHOW to build something > a bit more complex: > > (defmacro show-calls-to ((&rest names) &body body) > `(progn > ,@(loop for form in body > when (member (first form) names) collect `(show ,form) > else collect form))) > > This macro takes a lis of function names to SHOW and a body of forms. > All the top level forms in the body that contain calls to the named > functions are wrapped in a call to SHOW. A more sophisticated, and > useful, version of this macro would use code walker to find > interesting calls other than at the top level. > > CL-USER: (show-calls-to () (- 3 4) (+ 4 5) (* 6 7)) > 42 > CL-USER: (show-calls-to (+) (- 3 4) (+ 4 5) (* 6 7)) > TRACE>> Evaluating (+ 4 5); got 9 > 42 > CL-USER: (show-calls-to (+ *) (- 3 4) (+ 4 5) (* 6 7)) > TRACE>> Evaluating (+ 4 5); got 9 > TRACE>> Evaluating (* 6 7); got 42 > 42 Is the above something you find you use with any regularity or would expect others to use? I ask because unless other people look at it and go "Wow, that's something I really want and I can now see how to get it via macros", then macro examples like the above aren't going to win anyone over. For my part, show-calls-to is not something I would ever envisage using. I can envisage, and occasionally do use, the trace functionality found in some implementations that allows the inputs and output(s) of a specified function to be displayed but that is rather a different beast (though in some Lisp implementations it might well be partially implemented using a macro). From mlh at furu.idi.ntnu.no Mon Nov 17 01:32:23 2003 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Mon, 17 Nov 2003 06:32:23 +0000 (UTC) Subject: Python's simplicity philosophy References: <3FAC19F0.284DCB03@alcyone.com> <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <7xoevcf1u2.fsf@ruckus.brouhaha.com> <7x7k1zc0si.fsf@ruckus.brouhaha.com> <61Ztb.3481$sb4.1708@newsread2.news.pas.earthlink.net> Message-ID: In article <61Ztb.3481$sb4.1708 at newsread2.news.pas.earthlink.net>, Andrew Dalke wrote: [snip] > - sort is a method on lists. It only works on lists. Unlike STL, > which distinguishes between a container and an algorithm, there > is no way to apply sort directly to anything which isn't a list. Your > case (using sort on "a disk file or something") cannot occur. Surely he was talking about implementing "list-alikes"...? I.e. sequences polymorphically equivalent to lists, or at least wrt. sequence-ness and sorting...? The stability requirement does make this sort of thing a tad more difficult. (Not that I find it very problematic; I'm just trying to interpret the meaning of the post.) -- Magnus Lie Hetland "In this house we obey the laws of http://hetland.org thermodynamics!" Homer Simpson From aleaxit at yahoo.com Tue Nov 11 17:18:39 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 11 Nov 2003 22:18:39 GMT Subject: Regular expression code implementation review between Tcl vs Python References: <394af34.0311110758.3b1781ea@posting.google.com> Message-ID: <3fdsb.10497$hV.431113@news2.tin.it> K_Lee wrote: ... > One aspect I don't understanding about python is that the Python > language itself is object oriented and all the internal is implement > as C object. Why not C++ object? Using an OO language doesn't necessarily make implementing another OO language any easier, when the object models are mismatched (and they almost invariably are). Look at other opensource OO languages, such as Ruby, and you'll see they also use C, not C++. Actually, a small and carefully selected subset of C++ might surely help, _if_ there was consensus on what that subset should be and net of the work of hashing that consensus out. But C++ just isn't very much in the opensource culture -- C is just much more popular. Eric Raymond's book "The Art of Unix Programming" doesn't address the issue directly but much of what it says about "Unix culture" extends directly to opensource (as he notes, too). There are such values as an admiration for simplicity (cfr. C's principle, as per the Rationale of the C Standard, "provide only one way to perform an operation", and Python's corresponding "there ought to be one, and preferably only one, obvious way to do it") which militate in favour of C (which may not have reached simplicity everywhere but surely did and does always strive for it) and against C++ (which never gave language-simplicity a high priority level among its many design goals); even in subcultures that overtly reject such principles (e.g., Perl's) they may still have some subconscious-level effect. I used to bemoan this back when I was a C++ not-quite-but-close-guru. 3 years later, with little use of C++ in the meantime, I have forgotten more about C++ than most of it practitioners will ever learn... but C is just never forgotten, like how to swim or how to ride a bicycle. So, I am not any longer so sure if my "bemoaning" was warranted. Alex From bkelley at wi.mit.edu Mon Nov 10 09:18:37 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Mon, 10 Nov 2003 09:18:37 -0500 Subject: Talking through pipes interactively (on win32) In-Reply-To: References: Message-ID: <3FAF9E3D.4010205@wi.mit.edu> Jane Austine wrote: > I need to control a command line program via python. wxPython has a wxProcess class that makes this fairly easy. It is also portable between unix and windows (not macosX) the downside is that you need to run it in a wxWindows GUI environment. The other potential is to figure out how to use win32 Processes which are fairly hairy. The technical issue at hand is that under win32 you can't use python's select library on file objects or standard in or standard out pipes which makes controlling them fairly difficult. You can see a good demo of wxProcess in the wxPython demo. The upside is that wxProcess doesn't require a gui to be visible, just a wxPython application environment, the downside is that wxPython is fairly large. Hope this helps. From tim.one at comcast.net Thu Nov 6 10:43:52 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu, 6 Nov 2003 10:43:52 -0500 Subject: prePEP: Decimal data type In-Reply-To: Message-ID: [Alex Martelli] > European Union directives (adopted as laws by member states) mandate > the rounding procedure to be used in computations involving Euros > (round to closest Eurocent, always round up on half-Eurocent > results); they very explicitly mention that this may give a > 1-Eurocent discrepancy compared to "exact" arithmetic, and give > examples; they establish that such a 1-cent discrepancy that comes > from following exactly the prescribed rules is NOT legal cause for > any lawsuit whatsoever; they earnestly recommend that all computing > equipment and programs follow these same rules to avoid the huge > headaches that would result in trying to reconcile accounts > otherwise. > > Thus, for most accounting programs intended to run within the EU (not > just in Euros: these provisions also apply to the other non-Euro > currencies, as far as EU law is concerned), I do NOT think it would > be a good thing for the programmer to have to remember to round > explicitly -- the legal mandate is about rounding rules and it's > quite easy to avoid the "fail to meet the requirements", as they seem > designed to be easy to meet. I'd be astonished if the rules were consistent enough so that a type implementing a fixed number of decimal digits "after the decimal point" would be of real use for non-experts ... OK, here from: http://www.eubusiness.com/emu/retail8.htm The conversion of prices into euros will require the use of a six- significant-digit conversion rate (six digits disregarding initial zeros) which should not be rounded or truncated. This rate will be irrevocably fixed on 1 January 1999 and defined in the form of one euro expressed in national currencies. So that part mandates a *floating* point input (not meaning binary floating point, but "6 digits disregarding initial zeros" is the essence of floating point -- the total number of digits isn't fixed, nor is the # of digits after the decimal point fixed, just the # of *significant* digits). To convert from national currencies to the euro, one has to divide by the conversion rate. To convert from the euro to the national currency, one has to multiply by the conversion rate. The use of inverse rates is forbidden. Neutral. To convert from one national currency to another, amounts must be first converted into euros and then into the second national currency. The euro amount must be rounded to three decimal places. The national currency should then be rounded to two decimals. So no single fixed-point discipline can suffice: in one direction they want rounding to 3 digits after the decimal point, in the other to 2 digits, and one of the inputs is a floating-point value with no fixed number of digits after the decimal point. This is all very easily done with IBM's proposed arithmetic, but it requires the programmer to specify explicitly how many places after the decimal point they want after each * and / operation. Since that value changes in arbitrarily (from the POV of arithmetic semantics) mandated ways, no class can guess what's required from step to step. Again, this isn't an issue for + or -: if x and y have the same number of digits after the decimal point, then x+y and x-y are exact, and inherit that same number of fractional digits (provided only the user hasn't specified a suicidally low precision -- and they can easily know whether they have, because the "rounded result" flag would get set in the context). > Whether Decimal itself allows an optional rounding-policy (including > of course "no rounding" as a possibility) is one issue (I guess that > might violate some ANSI or IEEE standard...?) The IBM spec requires that the user be able to specify rounding mode, in the context. It sounds like the "round half up" mode is what the EU requires (not from the link above, but from what you said). Note that Cowlishaw's site has a "telco benchmark" wherein different steps require different rounding disciplines; I don't think that's uncommon either; I was able to get the exact result for that benchmark pretty easily using my FixedPoint class, but I enjoyed the luxury of having expert knowledge of the potential traps in advance. I expect most FixedPoint users would struggle with it. > but I most surely do want to be able to use such policies in whatever > arithmetic type underlies Money -- so I hope Decimal is at least > designed so that _subclasses_ can easily provide such customized > rounding (e.g., feature-testing for a __round__ specialmethod, not > defined in the baseclass Decimal if need be, but offering the needed > hook for subclasses to add the functionality). It has to support some half dozen specific rounding modes already (the spec requires them). The mandated modes have been reviewed by many people now over several years, so it's tempting to call YAGNI on adding more rounding complexity. My FixedPoint does support user-defined rounding modes; alas, all evidence to date suggests I'm the only person to date able to define one correctly . From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Nov 15 18:24:43 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sun, 16 Nov 2003 00:24:43 +0100 Subject: RuntimeError 'maximum recursion depth exceeded' In-Reply-To: References: <30ntb.5073$C14.183051@twister.southeast.rr.com> <3fb617c0$0$58715$e4fe514c@news.xs4all.nl> Message-ID: <3fb6b5bb$0$58714$e4fe514c@news.xs4all.nl> Georgy Pruss wrote: > Thank you. > Now it's "MemoryError: Stack overflow" but it's another story. :) Hmm, what are you doing exactly that requires this deep recursion? Can't you rewrite your algorithm in a non-recursive way? --Irmen From belred1 at yahoo.com Sat Nov 1 23:07:31 2003 From: belred1 at yahoo.com (Bryan) Date: Sun, 02 Nov 2003 04:07:31 GMT Subject: Why I love Python: More rambling... In-Reply-To: References: <20031028061245.12451.00000133@mb-m01.aol.com> Message-ID: <3FA482FE.6010507@yahoo.com> > > Data point (real world, from a few weeks ago): after spending ~2 weeks (spread > over a month) writing about 1400 lines of C++, debugging a nasty coredump, and > pounding the documentation, I had my 'fast' extension module finished for some > numerical work. Great, sweaty and exhausted but all proud of myself, I turn > my attention to the problem of writing a unittest. I decided to write it in > python, since I figured it would be easier, and an independent implementation > of the algorithm (simple one) should suffice, if tested with enough random > data. > > Python code: 15 lines (no, it's NOT a typo: fifteen). Time to write it: 10 > minutes. > > The sad part (to my ego, at least:)? The python runs faster! The C++ version > is now in the dustbin. At least I learned a bunch about the STL and > templates. The consolation... > > Cheers, > > f. > > ps for those thinking: you must be an idiot of a C++ programmer. That may well > be true. But still, there are reasons for the difference. The C++ version > uses a heavily templated library for handling multidimensional arrays with a > bearable syntax, and g++ isn't the best compiler out there for that kind of > code. The python version relies on Numeric.innerproduct(), which is very well > optimized, and tackles head-on the problem I was avoiding with the templates, > namely very annoying pointer manipulations for multidimensional tensors. The > Numeric guys got their hands dirty, did it once RIGHT, and it works extremely > well. i don't think this is an apples-to-apples comparison. in c++ you wrote everything yourself. in python, you used the numeric package which someone else wrote. i'm interested in knowing _why_ you chose to write it yourself in c++. and _why_ you didn't try to write it yourself in python, but instead chose to use an already written library. i just did a google search for "open source c++ numeric" and got several hits. i'm not putting you down in any way. i'm just interested in knowing why you made these different decisions for each language. bryan From rnd at onego.ru Tue Nov 18 01:30:51 2003 From: rnd at onego.ru (Roman Suzi) Date: Tue, 18 Nov 2003 09:30:51 +0300 (MSK) Subject: PEP263 and execfile() In-Reply-To: References: Message-ID: But is there solution possible without modification of all those files I do execfile() on? Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - On Tue, 17 Nov 2003, Martin v. [iso-8859-15] L?wis wrote: > Roman Suzi writes: > > > in one place (preferably at execfile() call)? > > You should call warnings.filterwarning. > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list > From nessus at mit.edu Fri Nov 14 04:19:12 2003 From: nessus at mit.edu (Douglas Alan) Date: Fri, 14 Nov 2003 04:19:12 -0500 Subject: How sum() should really be done References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <653b7547.0311121826.65b6b2d4@posting.google.com> <3FB40AD4.9428C78A@alcyone.com> Message-ID: Erik Max Francis writes: > Douglas Alan wrote: >> Ah, that reminds me -- both sum() and reduce() can be removed from >> Python by extending operator.add so that it will take any number of >> arguments. > reduce can't, since reduce doesn't require the function passed to be > operator.add. Well, as I said, for this to be true, *all* binary operators (that it makes sense to) would have to be upgraded to take an arbitrary number of arguments, like they do in Lisp. |>oug From aleax at aleax.it Mon Nov 17 10:58:57 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 17 Nov 2003 15:58:57 GMT Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <2259b0e2.0311140033.4e3ca8ea@posting.google.com> <2259b0e2.0311140906.87b7839@posting.google.com> Message-ID: <5f6ub.34346$9_.1371651@news1.tin.it> Michele Simionato wrote: ... > the world is. So, I do promote Python, but the pacific way ;) > > Michele > > P.S. in Italian "pacific" means "peaceful" but also, referred to a person, > somebody with a slow pace, and/or somebody who doesn't worry too much > (like me ;) not sure if the English word has the same connotation, but Yes, "pacific" has exactly the same two connotations in American English as "pacifico" has in Italian -- http://www.bartleby.com/61/37/P0003700.html It's just a rare-ish word, being overwhelmed by [a] "peaceful" and [b] the geographic-connoting "Pacific" (which refers not just to the Ocean, but to the huge variety of regions bordering said Ocean...). Alex From news at grauer-online.de Wed Nov 26 11:15:44 2003 From: news at grauer-online.de (Uwe Grauer) Date: Wed, 26 Nov 2003 17:15:44 +0100 Subject: kinterbas db column type In-Reply-To: References: Message-ID: Gandalf wrote: >> i need to know the database column types returned by kinterbasdb. >> Implicit type conversion is i nice thing to have, but it hides the >> real types in the database. >> So how could i get this information? > > > > If you use InterBase only, you can get that information from the > metadatabase. > Try this: > > RDB$RELATIONS - this stores table information > RDB$FIELDS - this is for the fields (here you have the RDB$FIELD_TYPE > field) > RDB$RELATION_FIELDS - connects relations to fields > > you can figure out the others. (Oh, it is for InterBase 6.0 but the > others are similar or the same) > > Cheers, > > L 1.0 > > > Does this mean, that the kinterbasdb isn't DB-API 2.0 compliant? From usenet at soraia.com Sat Nov 29 03:40:56 2003 From: usenet at soraia.com (Joe Francia) Date: Sat, 29 Nov 2003 08:40:56 GMT Subject: libmysqld.dll - any working example? In-Reply-To: References: Message-ID: JZ wrote: > On Sat, 29 Nov 2003 01:00:34 GMT, Dennis Lee Bieber > wrote: > > >>>Does anybody know any working example of using embedded MySQL library >>>for Win32 (libmysqld.dll)? That example from MySQL manual does not >>>work for me. I am looking for Python API to libmysqld.dll... >>> >> >> If I understand my book (hmmm, looks like New Riders has been >>swallowed by SAMS and renamed to "Developer's Library"), that DLL would >>have to be specified to the linker in place of the regular client >>protocol library. If so, to get Python to use it will likely require >>rebuilding the MySQLdb modules changing the linkage option. > > > Do you know how to rebuild this module using Visual Studio 7 instead > of v6? Is it possible? > > -- > JZ Unless you're totally married to MySQL, you may want to consider using one of the embeddable databases for Python, such as Sleepycat's Berkeley, Metakit, PySQLite, Kinterbase, etc. I've used Berkeley, Metakit and PySQLite, and they're all very good, each serving somewhat different needs. Shouldn't be too much effort to pull the data out of MySQL and into something else. Peace, Joe From bignose-hates-spam at and-benfinney-does-too.id.au Tue Nov 4 07:56:10 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 4 Nov 2003 23:46:10 +1050 Subject: Using debug print routine inside assert References: <8765i072jh.fsf@titan.staselog.com> Message-ID: On Tue, 04 Nov 2003 14:15:30 +0200, Edvard Majakari wrote: > Today I shortly discussed the problems in using print statements for > debugging problems in Python. Often in coding, in addition to asserts it > is nice to have a debug routine like > > import time > global DEBUG_LVL = 0 > ... > def debug(msg, threshold=1): > if threshold > DEBUG_LVL: > return > > print "%s %s\n" %(time.strftime("%d%m%y %H:%M:%S"), msg) > > # somewhere in the program > debug("subfrobnicate(%s, %s) returned %s" %(p1, p2, subfrobnicate(p1, p2))) The debug routine looks elegant and useful; thanks. The instance of its use is the problem. You're performing two discrete operations: get the result of the subfrobnicate() call, and then emit a debug message. The problem isn't with the debug message -- it's with the subfrobnicate() call. Or more precisely, the fact that you only seem to be using it for the debug() call. If the code only ever uses subfrobnicate() when you emit the debug message -- which isn't going to occur in the released program -- you don't really need to see it. # somewhere in the program debug( "p1 is %s, p2 is %s", % ( p1, p2 ) ) If the result of subfrobnicate() is important enough that you want to track it with a debug() call, it's probably because you're using the same result elsewhere. So why are you calling it each time it's needed? Calculate it, emit the message, then use it some more. # somewhere in the program sf_result = subfrobnicate( p1, p2 ) debug( "sf_result is %s (subfrobnicated from %s, %s)" % ( sf_result, p1, p2 ) ) do_other_stuff( sf_result ) Either the subfrobnicate() call is a waste of cycles -- remove it. Or, it's a necessary part of the program -- keep its result for use in the debug message *and* the main program. -- \ "If you make people think they're thinking, they'll love you; | `\ but if you really make them think, they'll hate you." -- | _o__) Anonymous | Ben Finney From mudd at vex.net Sun Nov 9 12:32:38 2003 From: mudd at vex.net (John Mudd) Date: 09 Nov 2003 12:32:38 -0500 Subject: dictionary lookup table? Message-ID: <1068399157.2099.26.camel@localhost.localdomain> I must be missing something here. It's clearly faster to lookup an item directly in a dictionary than to scan through a list. So when I have a large lookup table I always load it in the form of a dictionary. But it seems a waste. I end up having to assign an artificial value to the dictionary entry. Below I assign the value "None" to each dictionary entry. Is there a better way? I feel like I'm misusing the dictionary. #! /usr/bin/env python import random import time dict = {} list = [] n = 10000 n = 10000 for i in range(n): str = '%s' % random.random() list.append(str) dict[str] = None # <-- seems a waste sortedList = list[:] sortedList.sort() t1 = time.time() for i in range(n): if sortedList[i] not in list: print 'not found' print 'List lookups: %.3f sec' % (time.time() - t1) t1 = time.time() for i in range(n): if not dict.has_key(sortedList[i]): print 'not found' print 'List lookups: %.3f sec' % (time.time() - t1) ~ ~ ~ ~ ~ :!lookup.py List lookups: 28.848 sec List lookups: 0.041 sec Hit ENTER or type command to continue From jjl at pobox.com Wed Nov 19 09:03:12 2003 From: jjl at pobox.com (John J. Lee) Date: 19 Nov 2003 14:03:12 +0000 Subject: win32com from linux and jpq question References: <3FBA51F4.EC6049B9@ifi.uio.no> Message-ID: <873ccke9r3.fsf@pobox.com> Peder Ydalus writes: > 1) Anyone knows if it will be possible to e.g. read cells in an excel > sheet from linux? Yes: OpenOffice. > If python compiled bytecode is cross-platform (I don't > know), maybe it could add the necessary bits and bytes from win32com? No. > 2) I do not have PIL or other imaging libraries installed. Using plain > PhotoImage() and Label, is it possible to insert a jpg into an > application? What are PhotoImage and Label? John From mwh at python.net Fri Nov 21 08:37:08 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 21 Nov 2003 13:37:08 GMT Subject: Passing list with flexible length to C extension References: Message-ID: Bo?tjan Jerko writes: > Is there a way to pass list with flexible length to C extension? Yes, although I'm not quite sure what you mean. Do you want to be able to type my_ext_func([3.0, 1.0, 4.0, 1.0, 5.0]) or my_ext_func(3.0, 1.0, 4.0, 1.0, 5.0) ? If the latter you can't use PyArg_ParseTuple, but the `args' parameter is just a tuple, amenable to PyTuple_Length & so on. Cheers, mwh -- Our Constitution never promised us a good or efficient government, just a representative one. And that's what we got. -- http://www.advogato.org/person/mrorganic/diary.html?start=109 From johan at weknowthewayout.com Tue Nov 18 05:20:55 2003 From: johan at weknowthewayout.com (Johan Holst Nielsen) Date: Tue, 18 Nov 2003 11:20:55 +0100 Subject: Library to generate 3D Graphs Message-ID: <3fb9f2ae$0$9729$edfadb0f@dread14.news.tele.dk> Hi, Anyone have knowlegde of good (and easy-to-use) (free) libraries to generate 3D graphs? The only one I have found yet are http://www.fred.net/brv/chart/ - but it would be nice - of there was sometime more "eye-candy" creating library? Regards, Johan From trofer at nic.nac.wdyn.de Thu Nov 13 10:22:01 2003 From: trofer at nic.nac.wdyn.de (trofer at nic.nac.wdyn.de) Date: Thu, 13 Nov 2003 12:22:01 -0300 Subject: Printing dots in single-line Message-ID: <3fb39e32$1_1@nova.entelchile.net> Hey there, I want to print some dots in a single-line while my program loads or does something. I tried with he following but it didn't work :(. while 1: print '.', Prints line of dots separated by a whitespace (. . . . . . etc). Is there a way I can get it to display them without that white space (.......etc)? Thanks From pdaniell at ign.com Mon Nov 17 02:21:19 2003 From: pdaniell at ign.com (P. Daniell) Date: Sun, 16 Nov 2003 23:21:19 -0800 Subject: URL listers References: Message-ID: <022201c3acdb$65deee70$0300a8c0@HP> I have the following HTML document I don't give a hoot I want my HTMLParser subclass (code below) to output http://www.yahoo.com I don't give a hoot Instead it outputs http://www.yahoo.com I don http://www.yahoo.com ' http://www.yahoo.com t give a hoot Would anyone care to give me some guidance on how to fix this? Thanks, PD class URLLister(HTMLParser): def __init__(self): HTMLParser.__init__(self, formatter.NullFormatter()) self.in_a = 0 self.tempurl = '' def anchor_bgn(self, href, name, type): self.in_a = 1 self.tempurl = href def anchor_end(self): self.in_a = 0 def handle_data(self, data): if self.in_a == 1: print self.tempurl, data From kmneilso at REMOVEyahoo.com Sun Nov 9 17:07:18 2003 From: kmneilso at REMOVEyahoo.com (Kerry Neilson) Date: Sun, 09 Nov 2003 22:07:18 GMT Subject: sharing dictionaries amongst class instances References: Message-ID: Kerry, two observations: 1) That's not proper Python! ;-) and 2) I think the behaviours you want are only available in 'new style' classes, i.e. classes based upon 'object'. Did you mean: ---8<--- class A(object): my_dict = [] dict_entry = { 'key1':0, 'key2':0 } def __init__(self): for x in range(10): tmp = copy.deepcopy(self.dict_entry) tmp['key1'] = x self.my_dict.append(tmp) ---8<--- A.my_dict is a /class variable/, i.e. it is tied to the class, not the instance - there's only one of them, viz: ---8<--- >>> inst0,inst1=A(),A() >>> id(inst0),id(inst1) # get the id of the instances: (1083256236, 1083254732) >>> id(inst0.my_dict),id(inst1.my_dict) # and the id of their my_dict lists: (1083253228, 1083253228) >>> inst0.my_dict is inst1.my_dict True >>> ---8<--- If you move the initial assignment of my_dict into the __init__() procedure, and call it self.my_dict() instead, then you'll get a new instance of a list each time - maybe this is what you want. BTW, is there any particular reason for choosing the word 'my_dict' to describe a list? hope this helps you arrive at a solution ;-) Thanks for the reply, Andy. Your observation was correct, as I also learned from Peter, and moving the initial assignment into __init__ is whta I wanted. I guess I didn't realize that one could do that, being more familiar with c++. And no, calling a list my_dict was pure accident. Perhaps my explanation in response to Peter explains it a bit better. Thanks. From curty at freeze.invalid Thu Nov 20 10:25:08 2003 From: curty at freeze.invalid (Curt) Date: 20 Nov 2003 16:25:08 +0100 Subject: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com> <3FBC2025.B2A33B6F@alcyone.com> Message-ID: <87d6bncbaj.fsf@einstein.electron.net> Erik Max Francis writes: > Aahz wrote: > > Huh?!?! uniq has always to my knowledge only worked on sorted input. > > Reading the man page on two different systems confirms my knowledge. > uniq doesn't care whether the input is sorted or not. All it does is > collapse multiple consecutive duplicate lines into a single line. Using > uniq in conjunction with sort is certainly a common mode, but it's > hardly required. curty at einstein:~$ less uniq.txt flirty curty flirty curty curty at einstein:~$ uniq uniq.txt flirty curty flirty curty curty at einstein:~$ sort uniq.txt | uniq curty flirty Maybe my uniq is unique. curty at einstein:~$ man uniq NAME uniq - remove duplicate lines from a sorted file ****** From duncan at NOSPAMrcp.co.uk Fri Nov 21 09:42:29 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 21 Nov 2003 14:42:29 +0000 (UTC) Subject: Trouble with nested scopes when trying to rebind a variable References: <187srv08b4hbsckjje6s79dmipug8lcqlh@4ax.com> Message-ID: Fernando Rodriguez wrote in news:187srv08b4hbsckjje6s79dmipug8lcqlh at 4ax.com: > And here's where I get into trouble: if I write something like > PREVIEW = None inside the body of a function, it doesn't modify the > value of the existing PREVIEW variable, it creates a new variable in > the function scope. > > How can I modify the external PREVIEW variable? > > In Lisp there are different operators to rebind an existing variable > and to create a new variable. How do you do this in python? Use the global statement in the function to declare that you want to modify the global variable rather than creating a local variable, see section 6.13 of the reference manual. e.g. PREVIEW = 0 def aFunction(): global PREVIEW PREVIEW = 1 Better still, use classes and get rid of the global variable altogether. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From linux at ptd.net Sun Nov 9 21:03:02 2003 From: linux at ptd.net (Mark Smith) Date: Mon, 10 Nov 2003 02:03:02 GMT Subject: Newbie - 1st Program Message-ID: Hi, I'm trying to learn to program and Python seems to be the best "Starter" language (I've sat through various C tutorials, but have never used the language "in anger"). Actually, I think I have all the attributes of a hacker (not cracker) except for programming ability...I hope to learn... In trying to think of something to experiment with as my first thought-of-myself program, I thought back to an algorythm that I once worked out, which basically returns the number of possible routes in a cross connect (or switch) given the number of ingress or egress ports. It seems to work - great - but how would you make this more 'elegant' - I'm sure it's horrible to an experienced hacker... # Cross-Connect Calculator # (c)2003 Mark A Smith # Calculates the number of possible routes for a cross connect # given a certain number of ingress & egress ports. # Get number of ports from user inputPorts = input("Enter number of Input Ports: ") outputPorts = input("Enter number of Output Ports: ") # Main Routine totalPorts = float(inputPorts) + float(outputPorts) #Debug statements #print "Total Ports =", int(totalPorts) #print "Divisor =", float(totalPorts/2) #print "Subtraction =", int(totalPorts-1) crossConnects = (totalPorts / 2) * (totalPorts - 1) # Output print "You have", int(crossConnects), "possible connection routes." Any suggestions? Thanks Juglugs -- This sentence is in Spanish when you are not looking. From martin at v.loewis.de Fri Nov 28 16:30:29 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 28 Nov 2003 22:30:29 +0100 Subject: compile(unicode) & source encoding References: Message-ID: "Denis S. Otkidach" writes: [In the context of compile()] > 1. What is the reason to encode source code to utf-8? I think it is because Just found that the most straight-forward thing to do: UTF-8 supports all Unicode characters, and you have to choose *some* encoding, as the resulting byte strings need to be encoded somehow. In addition, anybody desiring a different encoding can explicitly invoke .encode() > 2. Why there is now option to define encoding of source passed to > compile function? No, although this should be implemented. It is not implemented at this point because it is very hard to do, and I have not found a good way to do it, yet. Regards, Martin From aleax at aleax.it Thu Nov 13 12:04:25 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Nov 2003 17:04:25 GMT Subject: a python book hint References: <_fydneqCioX5Ki-iRVn-iw@comcast.com> Message-ID: Cameron Laird wrote: > In article <_fydneqCioX5Ki-iRVn-iw at comcast.com>, > Aubrey Hutchison wrote: ... >>It appears that if you want to read about >> 1)--perl >> 2)--"C" >> 3)--jokes in a techinical book >> 4)-- British TV >> 5)-- Family history stuff >> 6)-- and so on..... ... > ? I don't think I understand. I believe you're saying that > such books as *Python in a Nutshell*, *Core Python Program- > ming*, *Text Processing in Python*, *Learn to Program Using > Python*, ... fail to "stick to the core subject". Do I have > that right? What do you see as examples of this fault? "Python in a Nutshell" _DOES_ show how to extend Python with C (chapter 24, 35 pages out of 636), thus presumably hitting Aubrey's trigger [2]; does mention and thanks some relatives in one line in the Acknowledgments, thus presumably hitting trigger [5]; does take half a page to (e.g.) explain about HTTP cookies rather than requiring the reader to be totally familiar with them, thus presumably hitting trigger [6]. I _think_ my editor managed to find and zap all of my few attempts at dry humor, and the book surely has nothing about perl nor British TV, but still, it's not _100%_ Python: I would guess _about_ 93.2% or so (if one considers "extending Python with C" to be "not Python" -- alas, the subject is FAR too useful to many readers for me to ever consider removing it, as, I believe, are the brief capsules or URLs about not-familiar-to-ALL technologies which I have before expanding on how Python interfaces to them...). Alex From aleax at aleax.it Fri Nov 14 08:05:16 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Nov 2003 13:05:16 GMT Subject: conceiling function calls.. References: Message-ID: Carlo v. Dango wrote: > Thanks for your reply... Unfortunately, I cannot truly see your > suggestions before my eyes.. Yeah, sigh, I was keeping them shrouded in a pitiful veil of shame. What you ask is so horrible, unPythonic, and deleterious, that it IS, in a way, a shame that Python lets you do it at all. However, it does. Here, as in most other places, it DOES "give you enough rope to shoot yourself in the foot" if you get "clever" enough (note that "clever" is NOT seen as a _positive_ quality in Python...). It comes down to that "trust the programmer" dictum. Sometimes I wonder how factually founded it is. Oh well, maybe it's an ethical rather than pragmatical idea: trusting the programmers ensures your place in heaven, or something. I sure hope so... thus, here it comes. >>> It is possible to conceil access to methods using the "property()" >>> function so method access looks like field access.. is the same possible >>> for functions (not taking any args... ) >> >> It's possible as long as the functions are accessed as attributes of >> some object -- it may be horrible, but you CAN, if you wish, write a >> __getattribute__ for the "some object" to force any access to the >> attribute to become a CALL to that attribute. > > but then I'm forced to use the self pointer.. I want to conceil it. That's a good part of what makes your request so horrible: you want to conceal what Python makes a point of revealing. >> You could, of course, wrap the function into an object (of the >> same name if you wish) that calls it whenever "an attribute of that >> name" is accessed (SHUDDER). > > hmm Im not sure what you are suggesting here. Are you still making use of > the self reference? or how would you construct this... > > please note that it's my purpose to hide the user from whats really going > on.. Yes, sigh -- the most horrible, evil purpose one might imagine, just about. I truly hope you reconsider your intended course of action. Still: To recap: you have a global function f which when called w/o arguments returns an object on which attributes may be accessed, a la print f().someattr You want to HIDE (shudder) the fact that a function is being called, ensuring, instead, that just coding: print f.someattr will call f secretly, behind the scenes. If one was truly intent on perpetrating this horror, then: class DontLetKidsSeeThisPlease(object): def __init__(self, f): self.__f = f def __getattr__(self, name): return getattr(self.__f(), name) f = DontLetKidsSeeThisPlease(f) there -- that's all there is to it. If you ALSO want to still be able to call f() explicitly, add one more line to the class: def __call__(self): return self.__f() and now an explicit f() will also behave as a normal call to f. [One can of course also add attribute setting, and all other operations, but I do hope I don't have to show them all explicitly too...!!!] Alex From jeff at cowz.com Tue Nov 11 01:10:59 2003 From: jeff at cowz.com (Jeff Sykes) Date: 10 Nov 2003 22:10:59 -0800 Subject: module import performance question Message-ID: <729b56c7.0311102210.4869d4f6@posting.google.com> I have a cgi script that imports modules based on a user config file. I am suffering some performance problems when I import these modules. Some logging revealed that it seems to be taking about 1.3 seconds to import these modules. This is running on a Windows 2000 box with a Pentium II 400 processor, Python 2.1, Apache 1.3.19 as the web server. I don't need screaming performance numbers, but this time is excessive. Is it me, or does that number seem kind of slow? Any code optimizations or recommendations? I would like to keep the architecture the same, just standard cgi scripts, so mod_python looks like it's a bit more involved than I would like. Here is a code snip: dyn_blocks = {} # set up a dict of the dynamic imports if confok: # was the configuration present? blocks = getBlocks(config) # get the application info from config for block in blocks: # each block indictates the ap & pg (module) ap = string.split(string.strip(block[1:len(block)]))[0] pg = string.split(string.strip(block[1:len(block)]))[1] sys.path.append(getAppPath(ap)) # add module dir to sys.path if (block[0] == '~'): try: dyn_blocks[ap + "_" + pg] = __import__(pg) except: Log.stacktrace(Log.ERROR) # log problem importing module Any help is appreciated. From phil_nospam_schmidt at yahoo.com Mon Nov 17 17:22:21 2003 From: phil_nospam_schmidt at yahoo.com (Phil Schmidt) Date: 17 Nov 2003 14:22:21 -0800 Subject: Making a maze.... References: <1PSsb.44675$jy.34613@clgrps13> <221e7b06.0311170946.3baaa2ca@posting.google.com> Message-ID: <221e7b06.0311171422.ceb82c5@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message news:... > On 17 Nov 2003 09:46:28 -0800, phil_nospam_schmidt at yahoo.com (Phil Schmidt) wrote: > > >I couldn't resist... > >-------------------------------------------------- > very pretty ;-) > > BTW, did you mean to prefix your code with something like > > from Tkinter import Canvas? > > [...] > > Regards, > Bengt Richter I actually used "from Tkinter import *", but yes, you are correct. A copy-paste error on my part. :) From http Sat Nov 1 18:18:54 2003 From: http (Paul Rubin) Date: 01 Nov 2003 15:18:54 -0800 Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0310312008.ce341ea@posting.google.com> <87r80sdyb1.fsf@pobox.com> <7xn0bg6njb.fsf@ruckus.brouhaha.com> Message-ID: <7x7k2jpti9.fsf@ruckus.brouhaha.com> Todd Stephens writes: > Regardless of the OP's intentions, I think the word "bankrupt" is not > qualified by "basically" so much as it is qualified by "is". I read the OP as saying TKC is basically bankrupt. I don't know what the actual facts surrounding TKC are. I didn't see any indication that it had legally filed bankruptcy and I don't really care since I'm not a creditor. What I want to know is whether it's paying its programmers and shipping product. There are conflicting claims about whether it's paying its programmers. Which claims are correct? From ngiff at yahoo.com Thu Nov 27 23:41:35 2003 From: ngiff at yahoo.com (nick) Date: 27 Nov 2003 20:41:35 -0800 Subject: Newbie question: importing module from C Message-ID: <7853e923.0311272041.1ab8ce45@posting.google.com> I'm trying to load the email.Message module from C and can't figure out what I'm doing wrong. What's wrong with the following code? PyObject *pMessage; pMessage = PyImport_ImportModule("email.Message"); if (pMessage == NULL) { printf("Null module\n"); exit(1); } I know my environment is set up correctly because if I change "email.Message" to "email", then I can successfully load the email package. From the email package, I can then get the dictionary and see the reference to the "Message", but don't know how to load it. Ultimately, what I want to do is instantiate an email.Message, fill it in, then send it off to the Python environment. I'm using Python 2.3.2 on Red Hat 9.0 thanks in advance, nick From Raaijmakers, Vincent (IndSys, Wed Nov 19 21:39:38 2003 From: Raaijmakers, Vincent (IndSys, (Raaijmakers, Vincent (IndSys,) Date: Wed, 19 Nov 2003 20:39:38 -0600 Subject: PIL and jpg -> png conversion, do I really need java for this??? Message-ID: <971323274247EB44B9A01D0A3B424C850372B240@FTWMLVEM02.e2k.ad.ge.com> Thanks for the advise. This seems a good solution but.. I just can't install it on Linux (RH7.2) from the sources. In a nutshell: - I downloaded boost.python and PythonMagick. - compiled bjam, copied this file into the same folder where the PythonMagick/readme.txt file is at. - changed the paths in buildLinux tried to run buildLinux but it complains that it can not find "boost-build.jam" Now, I really tried to do my best to follow every readme file, but this time it didn't help me. What step did I miss here? Vincent -----Original Message----- From: python-list-bounces+vincent.raaijmakers=ge.com at python.org [mailto:python-list-bounces+vincent.raaijmakers=ge.com at python.org]On Behalf Of Achim Domma Sent: Wednesday, November 19, 2003 5:00 PM To: python-list at python.org Subject: Re: PIL and jpg -> png conversion, do I really need java for this??? Hi Vincent, after a lot of problems with our server, I just got the PythonMagick website up and running again. If PNGs generated from ImageMagick work, it might be of help to you. Just have a look: http://www.procoders.net/pythonmagick regards, Achim -- http://mail.python.org/mailman/listinfo/python-list From anton at vredegoor.doge.nl Mon Nov 10 14:02:37 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Mon, 10 Nov 2003 20:02:37 +0100 Subject: recursion vs iteration (was Re: reduce()--what is it good for?) References: <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> Message-ID: On 9 Nov 2003 22:40:57 GMT, bokr at oz.net (Bengt Richter) wrote: [ackerman function generates very long integers] >Is there a fast formula for computing results, ignoring the representation problem? This seems to be an easy way to generate them faster: http://www.kosara.net/thoughts/ackermann.html ... back to the topic of this thread ... >From what I get of the main discussion (recursion vs iteration) it is reasonable to not make a distinction based on the type of algorithm but to only look at the order in which the nodes of the search space are visited. It seems possible to turn recursive functions into iterative ones by pushing and popping a stack of argument values. This opens up possibilities of continuing from arbitrary positions of the stack instead of just by pushing and popping ... Anton From peter at engcorp.com Tue Nov 25 11:59:05 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 25 Nov 2003 11:59:05 -0500 Subject: wxpython and telnet newbie References: <3fc36157$0$4361$79c14f64@nan-newsreader-01.noos.net> Message-ID: <3FC38A59.A890B262@engcorp.com> ataraxia2500 wrote: > > I found that little howto on the wxpython wiki: http://wiki.wxpython.org > index.cgi/WxHowtoSmallTelnetClient > I copied the whole thing and past it as is then I tried to run it but I got > an error. > this is the error message I got: > > /usr/share/themes/Geramik/gtk-2.0/gtkrc:25: error: unexpected identifier > `GtkButton', expected character `}' > Traceback (most recent call last): > File "wxtelnet.py", line 70, in ? > frame = TelnetFrame(None, -1, sys.argv[1]) > IndexError: list index out of range > > maybe I should modify some lines, I'm not sure. sys.argv is a list containing arguments passed on the command line. The above error is basically telling you that you have to specify at least one command line argument: probably a host name, though you should probably look at the definition of the TelnetFrame class to be sure. If you see a sys.argv[2] somewhere, that means you need a second argument, etc. -Peter From tdelaney at avaya.com Mon Nov 24 15:56:26 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 25 Nov 2003 07:56:26 +1100 Subject: Adding new methods at runtime to a class Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DEEEC2C9@au3010avexu1.global.avaya.com> > From: Fernando Rodriguez > > How can I add new methods at runtime to a class? Before we send you into what most would consider black magic in Python, you should explain why you want to. In most cases, this is *not* what you want to do - there are better, more elegant and much more Pythonic ways of doing it. Tim Delaney From davygrvy at pobox.com Wed Nov 12 00:42:45 2003 From: davygrvy at pobox.com (David Gravereaux) Date: Tue, 11 Nov 2003 21:42:45 -0800 Subject: Regular expression code implementation review between Tcl vs Python References: <394af34.0311110758.3b1781ea@posting.google.com> <3fb10cc1.7910169@News.CIS.DFN.DE> <394af34.0311112107.20b9a34f@posting.google.com> Message-ID: Google_Post at slink-software.com (K_Lee) wrote: >I guess the TCL original goal was also to support >Win16, DOS, etc. No it wasn't. Given whatever core an extension is loaded into, the extension grabs the function table from the core it is loaded into. Say for example I build all of Tcl statically into my application (kinda dumb, but let's just say). If I try to load an extension into it, where is it supposed to get the Tcl functions it needs? Do you see the issue Stubs solves? PS. try that setup with BLT and see why Stubs is a life saver for those in the know. -- David Gravereaux [species: human; planet: earth,milkyway(western spiral arm),alpha sector] From shuvit at 127.0.0.1 Wed Nov 5 08:06:56 2003 From: shuvit at 127.0.0.1 (Dave) Date: Wed, 5 Nov 2003 06:06:56 -0700 Subject: PyQt leaves C-code in python modules References: Message-ID: "Phil Thompson" wrote in message news:mailman.439.1067973360.702.python-list at python.org... > On Tuesday 04 November 2003 6:45 pm, Dave wrote: > > I'm having a strange problem with the pyqt-tools in the latest Debian > > packages. When I run > > $ pyuic colortool.ui > colortool.py > > Extracting init() > > Extracting loadSettings() > > Extracting saveSettings() > > ... > > it produces 'colortool.py' with python function headers, but the body of > > the functions are still in C. There are no error messages, just the normal > > log of "extracting" functions. > > [...] > That's because the form includes embedded C++ code. There is nothing to stop > you embedding Python code (just ignore the C++ style function definition) and > it will be properly extracted. > > What pyuic doesn't do is look at the embedded code and try to work out if it > is Python or something else. Oops. Please ignore my previous post. I misunderstood what Phil was saying. I see now what to do. Just write Python code in the body of the C++ stub functions ( leaving the outer { } in place ) , and pyuic will copy that code verbatim into the body of the translated Python functions. Excellent. Many thanks. -- Dave From mwh at python.net Wed Nov 5 08:37:52 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 5 Nov 2003 13:37:52 GMT Subject: dictionary keys, __hash__, __cmp__ References: <7h3fzh3hsb7.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h3wuafgcrx.fsf@pc150.maths.bris.ac.uk> Michael Hudson writes: > Jan-Erik Meyer-L?tgens writes: [snippety] > > -- I can ignore the 2nd statement, if I am aware of > > the fact that: if objects are equal it dosn't mean that > > they are the same key. > > Um, I don't understand you, but I think the answer is "no". > > If you ever have a situation where hash(a) != hash(b) but a == b then > you are very much breaking the rules. Having thought about it a bit more, I think the way you're doing things *is* actually safe given a platform where sizeof(int) == sizeof(PyObject*) and the current implementation, but sheesh, I wouldn't want to rely on it. Cheers, mwh -- In short, just business as usual in the wacky world of floating point . -- Tim Peters, comp.lang.python From james.kew at btinternet.com Mon Nov 3 18:16:42 2003 From: james.kew at btinternet.com (James Kew) Date: Mon, 3 Nov 2003 23:16:42 -0000 Subject: tar interface References: Message-ID: David Bear" wrote in message news:m3znfdgk7g.fsf at moroni.pp.asu.edu... > I just googled for a 'python tar interface module' and got over 33000 > hits. ug. > > I'm looking for a python module that either interfaces to gnutar in a > pythonic way or reads/writes tar files directly. I know there's > always os.popoen etc, but was hoping for something a little more .. Part of the standard library, if you use (or can move to) Python 2.3: http://www.python.org/doc/current/lib/module-tarfile.html -- James Kew james.kew at btinternet.com From Mike at DeleteThis.Geary.com Mon Nov 17 13:14:39 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 17 Nov 2003 10:14:39 -0800 Subject: True inconsistency in Python References: <3FB8847F.6CB1BECA@alcyone.com> <20031117072928.12288.00000313@mb-m25.aol.com> Message-ID: KefX: > Well, actually, some coding standards suggest you always compare against false. > This is so the code is slightly more clear, and "!= false" avoids the pitfall > that "== true" has. The problem of course is that some unwitting maintenance > programmer may decide that "== true" os more clear than "!= false", not > realizing it is wrong...which is why all maintenance programmers should read > programming standards. :) We can't program in baby C just for them, after all, > but we shouldn't make things unnecessarily difficult for them either, but I > think we have bigger things to worry about if a maintenance programmer fails to > understand such a simple concept after being told about it. > > Now of course any idiot C (or C++, or Java) programmer knows that these two are > equivalent: > > if(blah != false) > do_blah(); > > if(blah) > do_blah(); > > But if whatever goes in "blah" is really long (and often it is), you very > quickly see what is being compared: it's a straight boolean comparison, whereas > with the second you have to look at the whole thing, find no comparison > operator, and go, "oh, there's no explicit comparison so it's obviously an > implicit straight boolean comparison". This is especially valuable in really > long 'if' statements, such as one might want for an inverse parser (don't worry > if you don't know what one is). The idea is if you compare against 'false' all > the time, you won't forget it when it would actually give the code more > clarity. That strikes me as a really bad practice, in C, Python, or any language with a similar if statement. Code should read the way people think, and people don't tack on "!= false" when they make decisions based on conditions. Which would you say: "If you're hungry, eat!" or "If your hunger is not equal to false, eat!" So which is more clear: if( hungry ) eat(); or: if( hungry != false ) eat(); It's just as bad when you want to make the opposite test. Do you say, "If you're not hungry, don't eat!" or "If your hunger is equal to false, don't eat!" So do you code: if( ! hungry ) dontEat(); or: if( hungry == false ) dontEat(); (For those not familiar with C, "!" is the logical not operator and is pronounced "not".) I don't buy the argument that "you have to look at the whole thing, find no comparison operator, and go, 'oh, there's no explicit comparison so it's obviously an implicit straight boolean comparison.'" You *always* have to look at the whole thing, and an if statement always tests its entire argument for truth or falsity. Adding an explicit "!= false" or "== false" simply adds noise and reduces clarity. Comparing against a boolean isn't discouraged in Python because of some arbitrary cultural preference, it's discouraged because it makes code harder to read and understand. -Mike From tjreedy at udel.edu Wed Nov 12 17:38:00 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Nov 2003 17:38:00 -0500 Subject: trouble understanding None References: Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:bot32t$mf3$00$1 at news.t-online.com... > import sys > charset = { "S": > [ > " ________ ", > " /--------\ ", > "// \\\\", > "|| ^^", > "|| ", > r"\\________ ", > r" \--------\ ", > " \\\\", > " ||", > "_ ||", > r"\\________//", > r" \--------/ ", > ], Unless the OP actually needs a list of lines, I think I would make the value corresponding to each letter one string with embedded newlines: bigletter = { 'S': r''' ________ /--------\ // \\ || ^^ || \\________ \--------\ \\ || _ || \\________// \--------/''' # etc } print bigletter['S'] This is very easy to edit (with a fixed pitch editor), aud to use. >>> print bigletter['S'] ________ /--------\ // \\ || ^^ || \\________ \--------\ \\ || _ || \\________// \--------/ The only real problem is (maybe) the extra newline at the beginning of the file, which makes the first line line-up with the rest. The raw mode input makes it impossible (as far as I know) to escape it (with the usual '\', which gets printed instead). So one could either postprocess the dict to slice all values or delete the initial newline in the source code after getting the letter right. Terry J. Reedy From eelgueta at navix.cl Tue Nov 11 21:48:41 2003 From: eelgueta at navix.cl (Edo) Date: Tue, 11 Nov 2003 23:48:41 -0300 Subject: devel package install error Message-ID: Hi All, When I do "rpm -i python2.3-devel-2.3.2-1pydotorg.i386.rpm", I get error: Failed dependencies: python2.3 = 2.3.2 is needed by python2.3-devel-2.3.2-1pydotorg However, "rpm -qa | grep py" shows: python2.3-2.3-3pydotorg (among others 2.2 packages) If this is not the place to ask, any direction is very welcomed. TIA. Ed. PS. RedHat 9, with full python2.2 and base 2.3 installed. From jjl at pobox.com Sun Nov 9 14:53:04 2003 From: jjl at pobox.com (John J Lee) Date: Sun, 9 Nov 2003 19:53:04 +0000 (GMT) Subject: Status of JPE (Java-Python Extension)? In-Reply-To: <1068405973.1203.11.camel@emilio> References: <87fzgxfpv3.fsf@pobox.com> <1068405973.1203.11.camel@emilio> Message-ID: On Sun, 10 Nov 2003, Tim Churches wrote: > On Mon, 2003-11-10 at 03:50, John J. Lee wrote: > > Tim Churches writes: > > [...] > > > d) Are there any alternatives for making calls on Java objects from > > > CPython, or vice-versa? Or is Corba or similar the best approach? > > > > Pyro. Never used it, though. > > PyRO is great (have used it), but strictly Python to Python. Jython is Python. From the Pyro web page: What does Pyro offer you? Written in 100% pure Python. It is small, simple and extremely portable - it runs everywhere Python runs and TCP/IP networking is available. Partial support for Jython. Minimum Python version required is 2.1.x, though the latest Python version is recommended. dunno what 'partial support' means, though. John From see_signature__ at hotmail.com Sun Nov 30 01:18:36 2003 From: see_signature__ at hotmail.com (Georgy Pruss) Date: Sun, 30 Nov 2003 06:18:36 GMT Subject: Bug in glob.glob for files w/o extentions in Windows References: Message-ID: <0Zfyb.48050$dl.2119318@twister.southeast.rr.com> "Jules Dubois" wrote in message news:nj2k03e19clm$.uctj11fclu96$.dlg at 40tude.net... | On Sun, 30 Nov 2003 03:47:38 GMT, in article | , Georgy Pruss | wrote: | | > On Windows XP glob.glob doesn't work properly for files without extensions. | > E.g. C:\Temp contains 4 files: 2 with extensions, 2 without. | > [...] | > C:\Temp>dir /b *. | > ccccc | > ddddd | | This is standard Windows behavior. It's compatible with CP/M and therefore | MS-DOS, and Microsoft has preserved this behavior in all versions of | Windows. That's what I meant, wanted and liked. C'mon guys, I don't care if it's FAT, NTFS, Windows, Linux, VMS or whatever. All I wanted was to get files w/o dots in their names (on my computer :)). I did it and I can do it on any system if I need. | Did you ever poke around in the directory system in a FAT partition | (without VFAT)? You'll find that every file name is exactly 11 characters | long and "." is not found in any part of any file name in any directory | entry. | | It's bizarre but that's the way it works. If you try | | dir /b * | | does cmd.exe list only files without extensions? By definition it's the same as *.* if my memory serves me right. | >>>> glob.glob( '*.' ) | > [] | > | | glob provides "Unix style pathname pattern expansion" as documented in the | _Python Library Reference_: If there's a period (".") in the pattern, it | must match a period in the filename. | | > It looks like a bug. | | No, it's proper behavior. It's Windows that's (still) screwy. I see. Show the world a perfect OS and you'll be a billionaire. G-: From stevee at zuken.co.uk Thu Nov 6 13:15:34 2003 From: stevee at zuken.co.uk (Steve Evans) Date: Thu, 06 Nov 2003 18:15:34 +0000 Subject: Emacs mode: Display higher level References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 5 Nov 2003, guettli at thomas-guettler.de wrote: > Hi! > > I use xemacs. Is it possible to show the next higher > level in the status bar? > > Up to now it looks like this: > > Noconv-----XEmacs: foo.py (Python Font)----L1177-C0--79%--- > > It would be nice if it could look like this: > > Noconv-----XEmacs: foo.py/MyClass (Python Font)----L1177-C0--79%--- > > if the cursor is inside "class MyClass ....." > > Or better, like this, if the cursor is inside > myFunc of MyClass: > > Noconv-----XEmacs: foo.py/MyClass/myFunc (Python > Font)----L1177-C0--79%--- > > thomas You could try func-menu. Note the last sentence, which says it does what you wish. ;; Description: ;; ============ ;; Suppose you have a file with a lot of functions in it. Well, this package ;; makes it easy to jump to any of those functions. The names of the ;; functions in the current buffer are automatically put into a menubar menu, ;; you select one of the function-names and the point is moved to that very ;; function. The mark is pushed on the mark-ring, so you can easily go back ;; to where you were. Alternatively, you can use enter the name of the ;; desired function via the minibuffer which offers completing read input. In ;; addition, the name of the function before point is optionally displayed in ;; the modeline. I use it like this: (require 'func-menu) (add-hook 'find-file-hooks 'fume-add-menubar-entry) Steve - -- ____________________________________________________________________________ Steve Evans, Zuken Limited, TEL: +44 (0)1454 207800 ext 8607 1500 Aztec West, Fax: +44 (0)1454 207803 Almondsbury, mailto:stevee at zuken.co.uk Bristol, BS32 4RF, UK Web: http://www.zuken.com Registered Linux user #217906: http://counter.li.org Public Encryption Key: http://www.gorbag.com/public-key-work.html "a at b c"@d _____________________________________________________________________________ "Only an idiot fights a war on two fronts. Only the heir to the throne of the kingdom of idiots would fight a war on twelve fronts." "We can handle it. Our resources are greater than you think." -- Londo and Lord Refa in Babylon 5:"Ceremonies of Light and Dark" -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (SunOS) Comment: Processed by Mailcrypt 3.5.8 iD8DBQE/qo/E1a67iNP86GcRAn+eAKCUi/w+M9uoQHLqoR3Oy1Ek0cjs9wCeMPd2 pHhD0Dr1XdBr4Uo3ZF64AQk= =41zm -----END PGP SIGNATURE----- From msurette at laframboise.net Wed Nov 26 15:34:04 2003 From: msurette at laframboise.net (Michael Surette) Date: Wed, 26 Nov 2003 20:34:04 GMT Subject: superuser access to aliases database file Message-ID: I have written a python milter which needs to read the email aliases database (a dbhash file). Unfortunately this file is owned by root. I assume that this is for security reasons. I am told that I shouldn't run my milter as root, also for security reasons. Is there a simple, secure way to read this file? From newsgroups at jhrothjr.com Fri Nov 7 12:45:35 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 7 Nov 2003 12:45:35 -0500 Subject: Mailman gateway broken - again. Message-ID: The Mailman gateway seems to be picking posts up from the newsgroup and then reposting them to the newsgroup. As an example, see my post in the interminable PrePEP: Decimal Data Type thread dated 11/6/2003 at 3:49 PM. It showed up again from the mailing list to newsgroup gateway just after 12:30 on 11/7, but still dated 11/6, and formatted text/plain. There are a number of other posts in this, and I think other, threads that have also been double posted this way. John Roth From stain at stud.ntnu.no Sat Nov 22 15:11:23 2003 From: stain at stud.ntnu.no (Stian =?iso-8859-1?Q?S=F8iland?=) Date: Sat, 22 Nov 2003 20:11:23 +0000 (UTC) Subject: Dictionary problem References: Message-ID: * anton muhin spake thusly: > for i in range(10): > for setting in myList[i]: Btw, this kind of code I see too much of from fresh python programmers. Remember that for-loops iterates over sequences by default, so you really don't need those indexes. In most cases, your code could be simplified to for item in myList: for setting in item: If you really need both items and their indexes, try using zip from python 2.2: >>> items = ["a","b","c","d"] >>> zip(range(len(items)), items) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] >>> for (index, item) in zip(range(len(items)), items): ... print index, item ... 0 a 1 b 2 c 3 d -- Stian S?iland Being able to break security doesn't make Trondheim, Norway you a hacker more than being able to hotwire http://stain.portveien.to/ cars makes you an automotive engineer. [ESR] From nessus at mit.edu Mon Nov 10 17:35:32 2003 From: nessus at mit.edu (Douglas Alan) Date: Mon, 10 Nov 2003 17:35:32 -0500 Subject: What do you think of this Python logo? References: Message-ID: "Brandon J. Van Every" writes: > What do you think of this Python logo? > http://pythonology.org/logos > Good, bad, indifferent, love it, hate it? I like it! |>oug From radam2 at tampabay.rr.com Sat Nov 1 03:06:09 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Sat, 01 Nov 2003 08:06:09 GMT Subject: My first Python program.. Calculating pi geometrically. References: Message-ID: On Sat, 01 Nov 2003 06:49:55 GMT, Ron Adam wrote: > >Hi, I'm having fun learning Python and want to say thanks to everyone >here for a great programming language. > >Below is my first Python program (not my first program) and I'd >apreciate any feedback on how I might do things differently to make it >either more consice, readable, or faster. ie... are there better ways >to do it in Python? > >It won't break any records for calculating pi, that wasn't my goal, >learning Python was. But it might be good for testing floating point >and decimal performance. It also might make a good demo of the same. > > >Anyway, here it is, any feedback would be apreciated. > >_Ron > > BTW, I do know I can do this and get pi much much faster. >>>import gmpy >>>gmpy.pi(1000000) That gives me over 300,000 decimal places in 2 to 3 minutes. Which is very impressive. :-) Doing it geometrically was strictly a learning exercise. And I did learn quite a bit by doing it. _Ron From arnaud.fausse at wanadoo.fr Wed Nov 26 15:28:12 2003 From: arnaud.fausse at wanadoo.fr (Arnaud-F. FAUSSE) Date: Wed, 26 Nov 2003 21:28:12 +0100 Subject: Is there a .tolower() for a string?? References: <7b1fa3cb.0311261057.ecb7325@posting.google.com> Message-ID: look at .lower() I hope it helps AF "Amy" a ?crit dans le message de news:7b1fa3cb.0311261057.ecb7325 at posting.google.com... > I have a string say > > a = "Hello how are YOU" > > I want to end up with > > a = "hello how are you' > > Isn't there a built in method for changing a string to lowercase? > > Thanks. From try_vanevery_at_mycompanyname at yahoo.com Fri Nov 14 03:14:20 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Fri, 14 Nov 2003 00:14:20 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> Message-ID: "Asun Friere" wrote in message news:38ec68a6.0311132310.630e10e2 at posting.google.com... > python473 at yahoo.com (John Howard) wrote in message news:<9eabe547.0311131610.4dd7819c at posting.google.com>... > > I've sent several messages over the last year asking about python - > > Who teaches python? Is python losing steam? etc. I have noticed, eg, > > the declinng number of books at my local borders. The last time I > > visited a borders (last week), there was 1 (sic) book about python on > > the shelve compared to dozens on perl & java! > > > If you were developing in Java or Perl maybe you would need dozens of > books. But Python is so elegant and intuitive a single one will do. > ;) It is still not a good sign. If Python is so easy, and it were also popular, then presumably people would write problem specific books "in Python." Do your website in Python, your database in Python, your game in Python, your AI in Python, your laundry in Python... -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA Brandon's Law (after Godwin's Law): "As a Usenet discussion grows longer, the probability of a person being called a troll approaches one RAPIDLY." From jjl at pobox.com Fri Nov 14 10:07:48 2003 From: jjl at pobox.com (John J. Lee) Date: 14 Nov 2003 15:07:48 +0000 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> <84fc4588.0311140319.3778de15@posting.google.com> Message-ID: <874qx79eez.fsf@pobox.com> pythonguy at Hotpop.com (Anand Pillai) writes: [...] > There might have been thousands of books published in C/C++ > language and they have all helped to popularize it in one > or the other way. Contrast, in the python world we have one > Alex Martelli, one Wesley Chun, one David Mertz, really > countable by hand. And thank heavens for that. Most books on C++ (and the same goes for all kinds of other technical subjects) actually do nothing other to make it harder to find the decent books. Ironically, the good books often seem to get published first, followed afterwards by a glut of awful ones jumping on the bandwagon. So much for competition... > There is a limit to how much a single person can evangelize > a language. Questions similar to what the O.P posted arise > from the listeners. > > I would prefer to see more books on Python though they all might > be useless from a pure techie point of view. Let us have > a book on Software Projects in python for example. It might not > have the technical superiority of a Martelli book, but more > attempts like that will save the language and help the > eyeball factor, which is so important in practical marketing. [...] ... but I can see where you're coming from. John From ville.spammehardvainio at spamtut.fi Sun Nov 23 04:32:04 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 23 Nov 2003 11:32:04 +0200 Subject: Help with script with performance problems References: Message-ID: googlegroups at spacerodent.org (Dennis Roberts) writes: > is enough of a difference that unless I can figure out what I did > wrong or a better way of doing it I might not be able to use python > (since most of what I do is parsing various logs). The main reason to Isn't parsing logs a batch-oriented thing, where 20 minutes more wouldn't matter all that much? Log parsing is the home field of Perl, so python probably can't match its performance there, but other advantages of Python might make you still want to avoid going back to Perl. As long as it's 'efficient enough', who cares? > f = sys.stdin Have you tried using a normal file instead of stdin? BTW, you can iterate over a file easily by "for line in open("mylog.log"):". ISTR it's also more efficient than readline()'s, because it caches the lines instead of reading them one by one. You can also get the line numbers by doing "for linenum, line in enumerate(open("mylog.log")):" > splitline = string.split(line) Do not use 'string' module (it's deprecated), use string methods instead: line.split() > clients[source] = clients[source] + 1 clients[source] += 1 or another way to handle the common 'add 1, might not exist' idiom: clients[source] = 1 + clients.get(source,0) See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66516 -- Ville Vainio http://www.students.tut.fi/~vainio24 From mbabcock at fibrespeed.net Mon Nov 3 14:37:38 2003 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Mon, 03 Nov 2003 14:37:38 -0500 Subject: Does python always need to compile ENTIRE program before it can start to run it??? In-Reply-To: References: Message-ID: <3FA6AE82.9010109@fibrespeed.net> > make ; myprogram > > >I am trying to think of an advantage Python has over this hack.... > >Is it true that unlike C/C++ that Python programs can start executing >before compilation is COMPLETELY done??? I think so but I'm not sure. > Yes. You can have Python code that wouldn't "compile" but still runs. As long as the paths the interpreter takes have no errors, you're fine (minor exception of syntax errors). class a: def __init__(self): help # syntax error if we initialize an instance of a() print "hello world" ... that'll still run 'fine' because you don't use "a" That said, the "compilation" time of a Python program is almost nonexistant in most cases. Most of the work is runtime; load a class, wait for the class to compile, and so on.. -- Michael T. Babcock C.T.O., FibreSpeed Ltd. http://www.fibrespeed.net/~mbabcock From http Thu Nov 20 16:12:51 2003 From: http (Paul Rubin) Date: 20 Nov 2003 13:12:51 -0800 Subject: rotor alternative? References: <7x8ymd4hwf.fsf@ruckus.brouhaha.com> Message-ID: <7xptfmyca4.fsf@ruckus.brouhaha.com> bokr at oz.net (Bengt Richter) writes: > Just noticed your using time.time. > > I believe clock has more bits than time, at least on windows: Interesting, I might try that. Thanks. From js at cis.uni-muenchen.de Tue Nov 11 11:01:44 2003 From: js at cis.uni-muenchen.de (Joerg Schuster) Date: 11 Nov 2003 17:01:44 +0100 Subject: make order of function definitions irrelevant References: <87he1beug3.fsf@pobox.com> <2259b0e2.0311110650.2cea16b0@posting.google.com> Message-ID: Hello Michele, thanks for your hint. Yet, I have decided to give my program a new design which makes some old problems disappear. (Now I am having trouble with some new problems, of course.) J?rg From jmcalvar at telecable.es Mon Nov 10 12:02:09 2003 From: jmcalvar at telecable.es (=?ISO-8859-1?Q?Jos=E9?=) Date: Mon, 10 Nov 2003 18:02:09 +0100 Subject: response time Message-ID: I'm programming a simple script to calculate response time from one server to another server. I put the time in secons in a variable. I take the web, and I take the time again, the difference is the time one servers takes to take the page. I can only calculate it in seconds, is there a way to do it in miliseconds? Thanks From keflimarcusx at aol.comNOSPAM Sat Nov 1 10:50:27 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 01 Nov 2003 15:50:27 GMT Subject: Everybody likes python References: Message-ID: <20031101105027.12380.00000091@mb-m11.aol.com> >I thought Guido wanted Python associated with Monty Python? Yup, though the snake remain popular nonetheless. I think it may come down to a match between the remaining Pythons and a python. We could throw in a computer running a Python app while we're at it. Python vs. Python vs. python! - Kef From 2002 at weholt.org Fri Nov 21 13:19:44 2003 From: 2002 at weholt.org (Thomas Weholt) Date: Fri, 21 Nov 2003 19:19:44 +0100 Subject: Programming cellular phones using Python/Jython ? Message-ID: Hi, Is it at all possible to use python to make apps on cellular/mobile phones, using something like Jython etc. ? Hm ... ?? Thomas From martin at v.loewis.de Mon Nov 10 16:32:48 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 10 Nov 2003 22:32:48 +0100 Subject: pickle complexity limit? References: Message-ID: Simon Burton writes: > yow, eek... Well, i had this same problem a few days ago. > Could the docs be at least modified to take a note of this limitation? > I'll stick a post on bugzilla. Better yet, contribute a documentation change: submit the precise wording that you want to appear. Regards, Martin From james.anderson at setf.de Sun Nov 2 11:10:40 2003 From: james.anderson at setf.de (james anderson) Date: Sun, 02 Nov 2003 17:10:40 +0100 Subject: Paging Mr. Rettig [ws Re: Explanation of macros; Haskell macros] References: <87brs2tjut.fsf@memetrics.com> <4wuaj84x5.fsf@franz.com> <3FA5027D.5FDFB4AB@setf.de> <4r80q3hvs.fsf@franz.com> Message-ID: <3FA52C13.CF9DE444@setf.de> Duane Rettig wrote: > > james anderson writes: > > > Marcin 'Qrczak' Kowalczyk wrote: > > > > > > On Sun, 02 Nov 2003 02:01:58 -0800, Duane Rettig wrote: > > > > > > > With this much openness, it doesn't seem unreasonable > > > > to expect a debugger to be able to use such information to make macros > > > > and the forms they expand into completely debuggable and steppable at > > > > any desired level. > > > > > > Does any debugger do this? > > > > ? you mean like this? wrt evaluating > > > > (defun testf (x) > > (dotimes (i x) > > (print i))) > > > > (step (testf 2)) > > I've reproduced the whole code below so that readers can see it > when they contemplate this comment and a question (I have no time > now, but I'll explain tonight if nobody gets it, although it should > be easy): James did not say what lisp he was using, but presumably > it is a Common Lisp. The following example was obviously not > compiled. Can you explain why? > > > ==> > >... > > > > v/s > > > > ... > > > > depending on whether one stepped into or over the macro form? yes. whereby the first transcript is the result of successive "steps into". ... From aleax at aleax.it Tue Nov 4 11:01:33 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 04 Nov 2003 16:01:33 GMT Subject: new file.write method References: Message-ID: David Bear wrote: > I'd like something like the versioning behavior in emacs for the > file.write method. I spent some time looking around parnassus and > couldnt find anything there. Google for "python file version method" > was useless. Looking at the lib reference, there don't seem to be any > addition methods/attributes available for the file.write method. > > what I would like is a write method that each time is was called it > would look for an existing file by that name, if it existed rename it The write method of a file object takes a string of bytes and writes it to the file object (which must already be opened for writing). So, it seems that it's definitely not the unbound method file.write that you might interested in changing, but rather the constructor 'file' (aka 'open') which is what does the open-for-writing. If that's indeed your goal, take a look at the Python Cookbook, recipes 4.25 and 4.26 (p. 154-159 of the printed version) -- there will be something in the online cookbook at activestate, too, of course, but the printed-cookbook versions tend to be cleaned up, better discussed, etc. If you don't own the Python Cookbook and don't want to pay for it, I suggest you subscribe to O'Reilly's Safari service -- safari.oreilly.com, I believe: the first two weeks are free, so as long as you cancel before 14 days you will not pay -- and two weeks is plenty to look over these, and other neat things, in the Cookbook, the Nutshell, and other online books (on Python and other subjects). Alex From fredrik at pythonware.com Fri Nov 21 07:36:50 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 21 Nov 2003 13:36:50 +0100 Subject: Empty list as default parameter References: Message-ID: Alex Panayotopoulos wrote: > Maybe I'm being foolish, but I just don't understand why the following > code behaves as it does: > > - = - = - = - > > class listHolder: > def __init__( self, myList=[] ): > self.myList = myList > > def __repr__( self ): return str( self.myList ) > > # debug: 'a' should contain 42, 'b' should be empty. But no. > a = listHolder() > a.myList.append( 42 ) > b = listHolder() > print a > print b > > - = - = - = - > > I was expecting to see [42] then [], but instead I see [42] then [42]. It > seems that a and b share a reference to the same list object. Why? the default value expression is evaluated once, when the function object is created, and the resulting object is bound to the argument. if you want to create a new object on every call, you have to do that yourself: def __init__( self, myList=None): if myList is None: myList = [] # create a new list self.myList = myList or perhaps: def __init__( self, myList=None): self.myList = myList or [] see the description of the "def" statement for more info: http://www.python.org/doc/current/ref/function.html From aleax at aleax.it Thu Nov 6 06:40:39 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 06 Nov 2003 11:40:39 GMT Subject: Some python questions (building cgi website) References: <8bbd23e1.0311060319.5b813014@posting.google.com> Message-ID: paul h wrote: > hi there, > i'm learning to use python for cgi, and i've hit a few road blocks. > basically, i need to know how to achieve the following things using > python, on linux. > create a new directory, and sub-directory. > so if the user inputs "HELLO", i can create a dir called HELLO, and > then some other dirs in there. Assuming that: 1. your process's current directory is the one you want to have as the parent of 'HELLO'; 2. your process is running as a user that has permission to write in its current directory; 3. there is no subdirectory named 'HELLO' in the current directory; 4. some variable, say X, refers to the string which in this case happens to be 'HELLO'; then: import os os.mkdir(X) will make that 'HELLO' subdirectory, and then, e.g.: os.mkdir(X + '/foop') will create a subdirectory foop of that HELLO subdirectory. All these points, especially 1-2, cannot be taken for granted since your process is running as a CGI script; you must ensure by administrative means that your process is running as the user you desire (Python or any other language is powerless to help you there!) and either administratively or programmatically ensure the current directory is the one you want (or that you know the full path to prepend to X) -- the latter may not be trivial if chroot is in play, as it should be in most well-run network servers, for security reasons. > i also need to know how i can write various things into a file. > the following doesnt seem to work for me: > file.write("TEXT HERE") > how can i write plain text into a file? You need to OPEN a file for writing first: x = file('thefile.txt', 'w') and THEN you can call x.write("TEST HERE") to write some string (in this case, one without a terminating newline). file.write is an unbound method of built-in type file and, called as you mean to, would have no possible idea on WHAT file to write on!!! Alex From s-rube at uselessbastard.net Wed Nov 12 11:12:37 2003 From: s-rube at uselessbastard.net (Eric Williams) Date: Wed, 12 Nov 2003 17:12:37 +0100 Subject: Check of a Page About Python References: <3FAE6776.4040609@ithcorp.com> Message-ID: Hallo, Looks alright, but I'd be interested to know why you designate python a 4GL? You might want to check your jargon lexicon on that one. cya, Eric Anastasios Hatzis wrote: > Hi > > I have set up a page for a project on SourceForge. This project is about > a bundled tech platform, which contains Python (among other OSS tools), > so I also included a page with regard to Python. Indeed my English isn't > that good, thus the information given on this page really needs a > check-up. > > I would be very happy, if someone has the time and willingness to read > this page (English, orthographical, and textual). The URL is: > > http://freegee.sourceforge.net/FG_EN/products/freegee/modules/python_html.html > > There are also Python related information on some other web > pages/documents of the project, but they are just abstracts/copies of > this page. > > Many thanks! > > Anastasios -- --- s- should be removed to contact me... From jkrepsBEAR at FISHneb.rr.com Tue Nov 11 16:30:40 2003 From: jkrepsBEAR at FISHneb.rr.com (GrayGeek) Date: Tue, 11 Nov 2003 21:30:40 GMT Subject: Rekall and associated software go 100% GPL References: <3fae9c76$0$12714$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <4ycsb.22783$Vu6.6549@twister.rdc-kc.rr.com> Jim wrote: > On Tue, 11 Nov 2003 14:25:57 GMT, GrayGeek > wrotf: > >>John Dean wrote: >> >>> Hi >>> >>> It gives me great pleasure to inform you that Rekall, the cross-platform >>> alternative to MS Access, is now totally GPL. So please visit >>> http://www.totalrekall.co.uk and download download a copy for yourself. >>> In order for you to be able to download you must register with the Total >>> Rekall Portal. The reason we have have made this a requirement is >>> because we would like to be able to notify everybody when a new version >>> becomes available. We are presently working on V2.2.0 and I am sure you >>> would not like to miss out. >>> >>> You should also be aware that in order for for us to continue the future >>> development of Rekall we will have to charge for technical support, >>> customisation, training and consulting, therefore, now that we have gone >>> wholly GPL, you will have to take out a technical support subscription. >>> I will post information relating to support levels and pricing once we >>> worked out the detail. In the meantime may I suggest that you sign up to >>> our mailing list. Instructions can be found at the bottom of the home >>> page. >>> >> >>mmm, either the registration process is overloaded, or it is not >>functioning. After registering I failed to receive the confirmatory >>email. (Yes, my data was correct). >>Anyone else notice this? >>I see that all the previous msgs are on the 9th, but none after that. > > All I got was a demo version after registering. Also, there are some dead > links on their page I reported that haven't been fixed. Something isn't > right here. It apparently is getting worse. The original site containing the links to download the 'GPL' software disconnected from me in the middle of trying to download Rekall for Mandrake 9.1 after I had registered. When I attempted to reconnect to http://www.totalrekall.co.uk I was redirected to http://www.rekall.a-i-s.co.uk/ which is totally devoid of download links. If I were to hazard a guess it would be that theKompany has shut Dean down. ??? Before the new redirect was established I was getting a "can't connect to ".....theKompany.comrelease". The theKompany URL to rygannon.com gave: "An error occured while loading http://www.rygannon.com: Unknown host www.rekall.a-i-s.co.ukindex.php" So the battle must be raging on... ??? -- - GrayGeek From adalke at mindspring.com Tue Nov 18 02:28:14 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 18 Nov 2003 07:28:14 GMT Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: Georgy Pruss: > I NEVER wondered which of constructions should I > use in any particular case. I just solved the problem and wrote its solution > in that language and the language HELPED me to express myself clearly. While I, when writing Perl code, also NEVER had a problem. I ignored just about all of its variations if ($cond) {$a++} $a++ if $cond; $a++ unless !($cond); unless (!($cond)) {$a++}; I almost only used the first of these, and when other variations in structure came up I again had a strong preference for the one closest to C in feel. I did this not because it was the most expressive but because I wanted to write code that others could follow, and indeed one of the praises I got was "wow! It's Perl code I can actually understand!" > Half of all the conditions in real Python programs are 1 or True. :-) Cute as a joke, but in real-life it omits while loops, wherein the conditionals usually end up being true. ;) x = 1 while x < 1000: print x x = x + random.random(10) Andrew dalke at dalkescientific.com From noemail at noemail4u.com Mon Nov 3 11:12:38 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Mon, 03 Nov 2003 16:12:38 GMT Subject: programming languages (etc) "web popularity" fun References: <3d06fae9.0310310915.4447d4ca@posting.google.com> <9Zzob.75517$e5.2773519@news1.tin.it> Message-ID: <2531b4fb3a153253e29f8a74f733aef1@news.teranews.com> On Sat, 01 Nov 2003 00:53:17 -0000, claird at lairds.com (Cameron Laird) wrote: >Note, too, that the Python one hasn't been on the street >as long as some of the others. It's reasonable to specu- >late that the ratios haven't equilibrated yet. Not sure I understand your comment. Python predates Java. --dang From eppstein at ics.uci.edu Mon Nov 3 20:11:45 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 03 Nov 2003 17:11:45 -0800 Subject: nearest neighbor in 2D References: Message-ID: > >I have a list of two tuples containing x and y coord > > > > (x0, y0) > > (x1, y1) > > ... > > (xn, yn) > > > >Given a new point x,y, I would like to find the point in the list > >closest to x,y. I have to do this a lot, in an inner loop, and then I > >add each new point x,y to the list. I know the range of x and y in > >advance. Here's some not-very-heavily-tested code for doing this using a kD-tree. Worst case efficiency is still linear per point or quadratic total (unlike some other more sophisticated data structures) but in practice if your points are reasonably well behaved this should be pretty good; e.g. I tried it with 10000 random points (each queried then added) and it made only 302144 recursive calls to nearestNeighbor. Also note that only the test code at the end restricts to two dimensions, everything else works in arbitrary numbers of dimensions. def dist2(p,q): """Squared distance between p and q.""" d = 0 for i in range(len(p)): d += (p[i]-q[i])**2 return d class kdtree: def __init__(self,dim=2,index=0): self.dim = dim self.index = index self.split = None def addPoint(self,p): """Include another point in the kD-tree.""" if self.split is None: self.split = p self.left = kdtree(self.dim, (self.index + 1) % self.dim) self.right = kdtree(self.dim, (self.index + 1) % self.dim) elif self.split[self.index] < p[self.index]: self.left.addPoint(p) else: self.right.addPoint(p) def nearestNeighbor(self,q,maxdist2): """Find pair (d,p) where p is nearest neighbor and d is squared distance to p. Returned distance must be within maxdist2; if not, no point itself is returned. """ solution = (maxdist2+1,None) if self.split is not None: solution = min(solution, (dist2(self.split,q),self.split)) d2split = (self.split[self.index] - q[self.index])**2 if self.split[self.index] < p[self.index]: solution = min(solution, self.left.nearestNeighbor(q,solution[0])) if d2split < solution[0]: solution = min(solution, self.right.nearestNeighbor(q,solution[0])) else: solution = min(solution, self.right.nearestNeighbor(q,solution[0])) if d2split < solution[0]: solution = min(solution, self.left.nearestNeighbor(q,solution[0])) return solution if __name__ == "__main__": import math import random n_points = 50 max_x = 1000 max_y = 1000 max_dist2 = max_x**2 + max_y**2 k = kdtree() for i in range(n_points): x = round(max_x*random.random()) y = round(max_y*random.random()) p = (x,y) if i == 0: print 'new point',p else: d,q = k.nearestNeighbor(p,max_dist2) print 'new point', p, 'has neighbor', print q, 'at distance', math.sqrt(d) k.addPoint(p) -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From vincent at visualtrans.de Tue Nov 25 16:59:41 2003 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 25 Nov 2003 22:59:41 +0100 Subject: Problem with PyRun_SimpleFile and MFC Application References: <188007e5.0311251232.6c4b6254@posting.google.com> Message-ID: "Susanne" schrieb im Newsbeitrag news:188007e5.0311251232.6c4b6254 at posting.google.com... | Hello! | | In have embedded python into my MFC application. | It works fine using the PyRun_SimpleString method, giving it a string with | some simple commands. | | When i am using PyRun_SimpleFile instead, my application crashes. | | I have also created a console application. There i also call PyRun_SimpleFile. | The console application executes the given script. | >//works fine, only says, that there is no modul called CORBA | | So, does anyone of you have an idea, what i am doing wrong in my mfc app? PyRun_SimpleFile() reportedly (and I can second that) when certain compiler flags are different from the pythonxx(_d).dll. Try setting your Project Settings -> C/C++, Code Generation -> "Use runtime library" - to "(Debug) Multithreaded DLL" (Don't know if or how this affects any of your MFC stuff though) Hope this helps, Vincent Wehren | | Susanne From kylotan at hotmail.com Wed Nov 26 09:20:26 2003 From: kylotan at hotmail.com (Kylotan) Date: 26 Nov 2003 06:20:26 -0800 Subject: Pychecker under Windows References: <153fa67.0311252016.2e02b575@posting.google.com> Message-ID: <153fa67.0311260620.9f22938@posting.google.com> "Steve Holden" wrote in message news:... > You can redirect python output to a file from the Windows command line. The > only caveat is for *some* command processors (NT in particular, IIRC) output > redirection only works if you explicitly call the python interpreter (i.e. > use the command "python prog.py > file.out") rather than implicitly call it > (i.e. use the command "prog.py > file.out"). Sadly, the way to use Pychecker on Windows involves indirect usage; you call it via a batch file on the command line. Redirecting that - at least on Win98 SE - doesn't work, instead creating an empty file and sending all output to stdout as normal. -- Ben Sizer From aleax at aleax.it Mon Nov 10 14:53:05 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 10 Nov 2003 19:53:05 GMT Subject: Strange infinite recursion in metaclass's __new__ References: Message-ID: Jp Calderone wrote: > Due to some bizarre constraints placed on me, I've written the following > metaclass: > > import types > > def remove(t, o): > return tuple([e for e in t if t not in o]) > > class BizarreMetaclass(type): > def __new__(klass, name, bases, attrs): > if name == 'BaseClass': > return type.__new__(klass, name, bases, attrs) > return types.ClassType(name, remove(bases, [object]), attrs) > > class BaseClass(object): > __metaclass__ = BizarreMetaclass > > class Foo(BaseClass): > pass > > The solution is extremely hacky (but I've already tried and discarded > about a dozen more straightforward attempted solutions). > > It is also broken, but it is broken in a way that I do not understand. > > Can anyone explain the unbounded recursion that occurs? type.ClassType bends over backwards to accomodate classes that do in fact have a metaclass of 'type'; this is basically to let you code: class WeirdMix(classicone, object): ... to obtain a _new-style_ class otherwise equivalent to classicone (save for whatever additions and overrides you may choose to do in the body of WeirdMix). Since you don't remove Baseclass from among the bases before calling types.ClassType, then it identifies that one base class has a metaclass of BizarreMetaclass and defers to it -- whence the recursion. I did try to cover this in my Europython tutorial on metaclasses, btw -- it IS an important point, and an often-overlooked one. Since it does not appear to me that you NEED 'BaseClass' to remain among the bases of Foo, why don't you remove it, just as you remove object...? There's also a bug in your remove function, and the name of the first arg to __new__ in a metaclass should be mcl (just like it should be cls for __new__ in a normal class and self for other methods) -- I proposed that at Europython and Guido liked it;-) -- so, overall: import types def remove(t, o): return tuple([e for e in t if e not in o]) class BizarreMetaclass(type): omit = [object] def __new__(mcl, name, bases, attrs): if name == 'BaseClass': result = type.__new__(mcl, name, bases, attrs) mcl.omit.append(result) return result return types.ClassType(name, remove(bases, mcl.omit), attrs) class BaseClass(object): __metaclass__ = BizarreMetaclass class Foo(BaseClass): pass f = Foo() print f, type(f), f.__class__ print isinstance(f, BaseClass) print issubclass(Foo, BaseClass) this print, as required and expected: <__main__.Foo instance at 0x402decac> __main__.Foo False False Alex From aleax at aleax.it Tue Nov 11 10:13:41 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 11 Nov 2003 15:13:41 GMT Subject: response time References: <1jSrb.2419$9_.105379@news1.tin.it> <87d6bzetsz.fsf@pobox.com> <3FB01787.529425BC@engcorp.com> <87u15bf6qs.fsf@pobox.com> Message-ID: John J. Lee wrote: > Peter Hansen writes: > [...] >> Strange, but based on a relatively mundane thing: the frequency >> (14.31818MHz) of the NTSC color sub-carrier which was used when >> displaying computer output >> on a TV. This clock was divided by 3 to produce the 4.77MHz clock for >> the > [...] >> in time-keeping, which then counted on every edge using a 16-bit counter >> which wrapped around every 65536 counts, producing one interrupt every >> 65536/(14.31818*1000000/12) or about 0.5492 ms, which is about 18.2 ticks > [...] > > That doesn't explain it AFAICS -- why not use a different (smaller) > divisor? An eight bit counter would give about 0.2 ms resolution. The original IBM PC (8088, 64KB of memory if you were lucky, and two 160 KB floppies), which is where all of these numbers come from, didn't exactly have all that much power to spare. Dealing with 18.2 clock interrupts a second was plenty -- dealing with way more was probably considered out of the question by the original designers. We _are_ talking about more than 20 years ago, after all (and I'm sure none of those designers could possibly dream that their numbers had to be chosen, not for ONE computer model, but for models that would span 15 or more turns of Moore Law's wheel...!_). Alex From r at msolutionsinc.com Tue Nov 4 19:24:08 2003 From: r at msolutionsinc.com (Rob McMonigal) Date: Tue, 4 Nov 2003 19:24:08 -0500 Subject: setup.py for c++ References: <3FA6C613.5010302@wildmail.com> Message-ID: python setup.py build --help-compilers will give you a list of available compilers. In your case it would probably be --compiler=unix If you starting out, you may want to go through the options by starting at python setup.py --help and explore from there. HTH Rob "Zora Honey" wrote in message news:3FA6C613.5010302 at wildmail.com... > I'm taking baby steps toward extending python with c++. I got the demo > from "Extending and Embedding the Python Interpreter" running. My next > step was to modify the demo to output stuff using . This > fails, and this seems to be because my setup.py file is using a c > compiler (gcc) instead of a c++ compiler. I've searched the web and > found several solutions, none of which I've been able to implement > correctly. I seem to be only inches away but always missing a critical > piece of information, and I was wondering if the gurus here could help. > My attempts: > > 1.) From Pythonmac-SIG: "The problem is that the link step is done with > "gcc", not "g++", so you have to add the C++ library by hand. The > easiest is to add an extra_link_libraries (iirc) flag to the setup.py > file." Where in the setup.py file? Is this simply a flag or does it need > arguments? > > 2.) From "Extending and Embedding the Python Interpreter": "For example, > if you need to link against libraries known to be in the standard > library search path on target systems > > Extension(..., > libraries=["gdbm", "readline"])" > This does seem to work, but I don't know if it's the same as 1) or which > libraries I need to include. > > 3.) From "Installing Python Modules": "Arbitrary switches intended for > the compiler or the linker can be supplied with the -Xcompiler arg and > -Xlinker arg options: > foo foomodule.c -Xcompiler" > > I'm using the syntax: > odule1 = Extension(modulename , > sources = sourcecode, > ) > in my setup.py file, and don't know where to put this compiler option. > > 4.) From ?: Use compiler option: python setup.py build --compiler=g++ > I get an error message that ends in: > distutils.errors.DistutilsPlatformError: don't know how to compile C/C++ > code on platform 'posix' with 'g++' compiler > Which sounds like distutils doesn't like my compiler (or somehow I need > to set the platform--I'm on RedHat 7.1). > > Thanks for any ideas, > Zora > From adeleinandjeremy at yahoo.com Sun Nov 30 23:16:38 2003 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Sun, 30 Nov 2003 20:16:38 -0800 (PST) Subject: Using and Implementing iterators with classes such as linked lists Message-ID: <20031201041638.79452.qmail@web40808.mail.yahoo.com> I am taking a second programming course in Java and am currently attempting to apply what I have learned using Python instead. One thing that is puzzling me is how to use an iterator. I am writing a module containing everything I'd need for canonical linked lists. One particularly useful feature would be to use a for loop over the whole structure. For this I have learned the benefits of iterators. I have read a few book entries on Python iterators, as well as an online article by David Mertz, I believe, and PEP 234, and I may be lacking some insight but I am still confused about one thing. How does the iteration know where to begin? AFAIU, in my LinkedList class, I can either have the LinkedList be its own iterator by making its __iter__() method return self and defining a next() method, or I can have a separate iterator called from LinkedList's __iter__(). My view is that it would be best to have the LinkedList be its own iterator - is that the case? Or is an external iterator preferable in this case? My problem with implementing the former comes with this: in LinkedList I would have: ... def __init__(self): return self ... def next(self): if self.__current.next == None: raise StopIteration self.__current = self.__current.next return self.__current.next ... Now, is this good in the eyes of more experienced programmers? Also, do I really want to dedicate an instance variable to keep track of where to begin iteration (if __current is used for other purposes, iteration could conceivably begin anywhere right?)? Does this suggest that I should have a separate LinkedListIterator class? And if I do have that separate class, do I make the LinkedList.__iter__() pass on to LinkedListIterator's constructor the head node of LinkedList, or the whole linked list? Thanks in advance, Jeremy __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From list-python at ccraig.org Fri Nov 7 12:34:44 2003 From: list-python at ccraig.org (Christopher A. Craig) Date: 07 Nov 2003 12:34:44 -0500 Subject: simple float numbers problem References: <3FAB9F7C.3060901@sympatico.ca> Message-ID: Vio writes: > Perhaps because Python translates "25.99" to "25.98999999999999998" > and not "25.99", which may be the reason for this error (me > guessing...). If that's the case, how do I force Python to only use > 2 decimal points, and not "make up" superfluous decimals? Or if > that's not the cause for the problem, how do I make Python see my > math expression as TRUE (as it "should" be)? Python does not translate 25.99 as 25.98999999999999998. IEEE (assuming your chip has the same fp as mine, which may not be valid) floating point stores 25.99 sort of as the binary number 7315534644709949*(2**-48), which is the closest it can come to 25.99. Of course, that doesn't tell you how to compare them. You have two choices there: The normal way to do floating point compares is to say if abs(a-b) < 1e-10 then that's good enough. If you really, really need equality, then you need something other than a float. You could try rationals[0] or fixed points[1] but they both have other problems... see http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate [0] http://sourceforge.net/project/showfiles.php?group_id=27765&release_id=90046 [1] http://fixedpoint.sourceforge.net/ -- Christopher A. Craig "No one has ever called us untrustworthy" -- Steve Balmer From andreas at mtg.co.at Mon Nov 24 15:41:29 2003 From: andreas at mtg.co.at (Andreas Kostyrka) Date: 24 Nov 2003 12:41:29 -0800 Subject: Use of GPLed Python extension modules References: <653b7547.0311230957.69e5cdbc@posting.google.com> Message-ID: pmaupin at speakeasy.net (Patrick Maupin) wrote in message news:<653b7547.0311230957.69e5cdbc at posting.google.com>... > As for the moral issue, IMO the distinction the FSF makes between > loosely-coupled and tightly-coupled programs is false. (Legally, > also, this distinction is false except when the programs are coupled > so tightly they MUST be provided in the same distribution. In other > words, it is the distribution of GPLed code which offends, not any > technical aspects of how non-GPLed code interacts with GPLed code.) Well, the big "difference" between C libraries, and Python modules is that C libraries usually consist of .h files, which get included in your "dynamically" linked program. That wouldn't be that bad, but .h files often contain macros and/or inlined function, which makes every client of the library include some part of the sourcecode of the library. Python modules OTOH include only my name, so there is no "code" leaked into my program. If you read the interviews of the FSF Lawyers with this in your head, it just makes much more sense (yeah, by using readline you are including it, well at least parts, in your program). Andreas From mwilson at the-wire.com Mon Nov 10 15:51:32 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Mon, 10 Nov 2003 15:51:32 -0500 Subject: True, False, None References: <20031110065915.07735.00000461@mb-m07.aol.com> Message-ID: In article , Thomas Bellman wrote: >Alex Martelli wrote: > >> True, False and None may well become keywords in the future, because that >> might make things "even finer" in some respects. E.g., right now, >> while True: >> ... >> has to look-up 'True' at EACH step just in case the ... code rebinds >> that name. This _is_ a bit silly, when there is no real use-case for >> "letting True be re-bound". Nothing major, but...: > >That's a silly reason to make them keywords. A much better way >to achieve the same goal would be to make the optimizer recognize >that True isn't re-bound within the loop. Often you can't tell. Any loop that includes a function call could do anything, determined by events that occur long after the optimizer terminates. And many things can invoke function calls.. __add__, anyone? Regards. Mel. From peter at engcorp.com Mon Nov 3 13:23:50 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Nov 2003 13:23:50 -0500 Subject: programming languages (etc) "web popularity" fun References: Message-ID: <3FA69D36.FD0A72C8@engcorp.com> SBrunning at trisystems.co.uk wrote: > > > From: Alex Martelli [SMTP:aleax at aleax.it] > > Sure (e.g. Windows Server 2003 in a Nutshell in September; C# in > > a Nutshell 2nd edition in August; C++ in a Nutshell in May; and > > others, too, I'm sure). O'Reilly is relentless...:-). > > C++ in a Nutshell? How many volumes was that? ;-) That would be a *coconut*, I suppose... ;-) -Peter From espen at *do-not-spam-me*.vestre.net Mon Nov 3 03:32:27 2003 From: espen at *do-not-spam-me*.vestre.net (Espen Vestre) Date: 03 Nov 2003 09:32:27 +0100 Subject: Paging Mr. Rettig [ws Re: Explanation of macros; Haskell macros] References: <87brs2tjut.fsf@memetrics.com> <87n0bfhszi.fsf@thalassa.informatimago.com> Message-ID: Kenny Tilton writes: > I prefer the subliminal approach, it affects brain Cells more indelibly. > > How about JMUML? Hmm. Does this call for something like the Erd?s numbers? http://www.oakland.edu/~grossman/erdoshp.html ;-) -- (espen) From nessus at mit.edu Wed Nov 12 03:37:34 2003 From: nessus at mit.edu (Douglas Alan) Date: Wed, 12 Nov 2003 03:37:34 -0500 Subject: Python's simplicity philosophy References: <3FAC19F0.284DCB03@alcyone.com> <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> Message-ID: pmaupin at speakeasy.net (Patrick Maupin) writes: > Douglas Alan wrote: >> Your claim is silly. sum() is not *way* simpler than reduce(), and >> anyone can be explained reduce() in 10 seconds: "reduce() is just like >> sum(), only with reduce() you can specify whatever addition function >> you would like." > Maybe reduce() can be explained in 10 seconds to someone who has used > sum() a few times, but that has no bearing whatsoever on trying to > explain reduce() to someone if sum() is not available and hasn't > been used by them. Describing reduce() in 10 seconds is utterly trivial to anyone with an IQ above 100, whether or not they have ever used sum(): "To add a sequence of numbers together: reduce(add, seq) To multiply a sequence of numbers together: reduce(mul, seq) To subtract all of the numbers of a sequence (except the first number) from the first number of the sequence: reduce(sub, seq) To divide the first number in a sequence by all the remaining numbers in the sequence: reduce(div, seq) Any two-argument function can be used in place of add, mul, sub, or div and you'll get the appropriate result. Other interesting examples are left as an exercise for the reader." If someone can't understand this quickly, then they shouldn't be programming! > I'm sorry, but from a pure CS viewpoint, reduce() is way off the > radar screen. Especially for a 101 course. I'm sorry, but you are incorrect. When I took CS-101, we learned assembly language, then were assigned to write a text editor in assembly language, then we learned LISP and were assigned to write some programs in LISP, and then we learned C, and then we were assigned to implement LISP in C. If you can write a !$#@!!%# LISP interpreter in C, you no doubt can figure out something as mind-achingly simple as reduce()! >> You should be assuming that your audience are the smart people >> that they are, rather than the idiots you are assuming them to be. > Ignorance is not stupidity. Assuming that your audience cannot learn the simplest of concepts is assuming that they are stupid, not that they are ignorant. >> I sure hope that Python doesn't try to emulate C. It's a terrible, >> horrible programming language that held back the world of software >> development by at least a decade. > I used to hate C. But then, when it borrowed enough good concepts > from Pascal and other languages, and the compilers got smart enough > to warn you (if you cared to see the warnings) about things like > "if (x = y)" I stopped using Modula-2. C held software back 10 > years in the same manner as Microsoft did, e.g. by helping to > standardize things to where I can buy a $199 system from WalMart > which would cost over $20,000 if everybody kept writing code like > the pointy-headed ivory tower academics thought it ought to be written. You score no points for C by saying that it is like Microsoft. That's a strong damnation in my book. And you really don't know how the world would have turned out if a different programming language had been adopted rather than C for all those years. Perhaps computers would be more expensive today, perhaps not. On the other hand, we might not have quite so many buffer overflow security exploits. Perhaps we'd have hardware support for realtime GC, which might be very nice. On the other hand, perhaps people would have stuck with assembly language for developing OS's. That wouldn't have been so pretty, but I'm not sure that that would have made computers more expensive. Perhaps a variant of Pascal or PL/1 would have taken the niche that C obtained. Either of those would have been better, though no great shakes either. Many of the pointy-headed ivory tower academics, by the way, thought that code should look something like Python. The reason these languages are not widely used is because typically they either did not come with batteries, or there was no lightweight implmentation provided, or they only ran on special hardware, or all of the above. >> The reason for Python's wide acceptance isn't because it is >> particularly well-designed compared to other programming languages >> that had similar goals of simplicity and minimality (it also isn't >> poorly designed compared to any of them -- it is on par with the >> better ones) -- the reason for its success is that it was in the right >> place at the right time, it had a lightweight implementation, was >> well-suited to scripting, and it came with batteries included. > I'd vote this as the statement in this group most likely to start > a religious flamewar since the lisp threads died down. The only way it could start a religious flamewar is if there are people who wish to present themselves as fanboys. I have said nothing extreme -- just what is obvious: There are many nice computer programming languages -- Python is but one of them. If someone wishes to disagree with this, then they would have to argue that there are no other nice programming languages. Now that would be a flame! > I'm not particularly religious, but I _will_ bite on this one: > 1) In what way was it at the "right place at the right time?" Perl was in the right place at the right time because system administrators had gotten frustrated with doing all their scripts in a mishmash of shell, awk, sed, and grep, etc. And then web-scripting kicked Perl into even more wide acceptance. Python was in the right place in the right time because many such script-writers (like yours truly) just could not stomach Perl, since it is an ugly monstrocity, and Python offered such people relief from Perl. If Perl had been a sane OO language, Python would never have had a chance. > You didn't name names of other languages, but I'll bet that if you > can name 5 which are similar by your criteria, at least two of them > were available when Python first came out. I'm not sure what you are getting at. There were many nice programming languages before Python, but not many of them, other than Perl, were portable and well-suited to scripting. Oh, yeah, I forgot to mention portability in my list of reasons why Python caught on. That's an essential one. Sure you could elegantly script a Lisp Machine with Lisp, and some Xerox computers with Smalltalk, but they didn't provide versions of these languages well-suited for scripting other platforms. > 2) What part of "lightweight implementation, well suited to > scripting" contradicts, or is even merely orthorgonal to > "particularly well-designed"? Again, I'm not sure what you are getting at. "Lightweight implementation" and "well-suited to scripting" do not contradict "well-designed", as Python proves. Lightweightedness and capability at scripting are certainly orthogonal to the property of being well-designed, however, since there are a plethora of well-designed languages that are not suited to scripting. They just weren't designed to address this niche. > 3) Do you _really_ think that all the batteries were included when > Python first came out? It certainly was not a particularly popular language until it came with pretty hefty batteries. There are many other languages that would have been equally popular before Python started coming with batteries. > Do you even think that Python has more batteries _right_ _now_ than > Perl (via CPAN), or that some competing language couldn't or hasn't > already been designed which can coopt other languages' batteries? Um, the last time I checked Perl was still a lot more popular than Python, so once again I'm not sure what you are getting at. Regarding whether or not some future language might also come with batteries and therefore steal away Python's niche merely due to having more batteries: Anything is possible, but this will be an uphill battle for another language because once a language takes a niche, it is very difficult for the language to be displaced. On the other hand, a new language can take over a sub-niche by providing more batteries in a particular area. PHP would be an example of this. > I can accept the premise that, for Python to enjoy the acceptance it > does today, Guido had to be lucky in addition to being an excellent > language designer. But if I were to accept the premise that > Python's popularity is due to sheer luck alone my only logical > course of action would to be to buy Guido a plane ticket to Vegas > and front him $10,000 worth of chips, because he has been extremely > lucky for many years now. I never claimed *anything* like the assertion that Python's popularity is due to luck alone! |>oug From martin at v.loewis.de Sat Nov 8 18:23:28 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 09 Nov 2003 00:23:28 +0100 Subject: Help for unicode References: <3fad6fb5$0$58715$e4fe514c@news.xs4all.nl> <2perb.101236$vO5.3965040@twister1.libero.it> Message-ID: "Noixe" writes: > print u'\u2205' > > I have this error: UnicodeError: ASCII encoding error: ordinal not in > range(128) > > > Why? I must include some module? No. Just don't print it: >>> x=u'\u2205' >>> x u'\u2205' The character U+2205 is EMPTY SET; your terminal is not capable of displaying that symbol. Regards, Martin From tim.ronning at start.no Fri Nov 7 11:39:08 2003 From: tim.ronning at start.no (Tim Ronning) Date: Fri, 07 Nov 2003 17:39:08 +0100 Subject: Rekall not longer available from theKompany.com - a fabrication In-Reply-To: References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <3fa6a75e$0$12666$fa0fcedb@lovejoy.zen.co.uk> <23891c90.0311070355.1de4184c@posting.google.com> Message-ID: P? Fri, 07 Nov 2003 14:11:37 GMT, skrev Alex Martelli : > Paul Boddie wrote: > ... >>> licensing scheme. There would be a free for non-commercial use GPL >>> version and the normal commercial version. >> >> Well, given the history of Rekall, combined with TheKompany's problems >> with selling GPL software because people apparently demanded the >> source code for free without buying anything, it's hard to know > > *blink* surely the source has to be given only if the binaries are? > Can't stop others from redistributing that, but "demand the source > code w/o buying anything" doesn't seem something the GPL mandates. > > >>> The GPL would not include any kind of support whatsoever, therefore >>> you would need to take out a support subscription. >>> The GPL version would be free for non-commercial use. >> >> You have to ask yourself the question: if your knowledge of the GPL >> was sketchy or non-existent, how would you interpret that last >> sentence? > > Presumably in the "obvious way", yes:-). > > >> Isn't this known as being "economical with the truth", or is it just >> downright contradictory? It's like saying that "nude bathing is >> allowed but you aren't allowed to get wet", only to explain such a >> ridiculous statement away by then saying that "they just forgot to >> mention that you are allowed to get wet as well". > > No, your analogy is misplaced: the "aren't allowed" would be > overtly false in your "it's like". > > A correct analogy would be: "I never strangle somebody with the > initials PB on a Friday". This statement _is_ perfectly true: I > never strangle anybody at all, and therefore, in particular, not > people with the initials PB, and even more specifically, not > on a Friday, > > However, it's _misleading_ because, although Aristotelian logic > has nothing to say in the matter, people "naturally expect" that > a qualification restricting a statement is there for SOME reason: > typically because, without the restriction, the statement would > not hold. But that's just a heuristical inference based on "if > the restriction wasn't necessary he wouldn't bother stating it" -- > there's nothing either dishonest or contradictory in putting on > a statement _more_ qualifications than strictly necessary (it's > the difference between "precondition" and "WEAKEST precondition"). > > E.g., a similarly misleading statement would be "In Euclidean > geometry, there is one and only one perpendicular to a given > line through a given external point". The qualification "In > Euclidean geometry" is way stronger than necessary, since > existence and uniqueness of the perpendicular follow from the > first _four_ axioms of Euclid only, _not_ needing the fifth > one which is not valid in non-Euclidean geometries such as > Riemann's and Lobachevsky's. > > And yet, unless I have specifically undertaken to tutor > somebody in a field including non-Euclidean geometries, I > might well make such a statement and consider it defensible. > Indeed, I have seen _proofs_ of this very statement, based > on other results which _do_ hold in Euclidean geometry only... > Presumably, depending on context, the responsibility for > learning about NON-Euclidean geometries may be held to belong > to the reader of my statements, without any duty on my part > to instruct said reader in this subject. > > Similarly, the asserters of the above statement (falsely > claimed to be contradictory, though truly claimable as being > misleading) might contend that the responsibility for learning > about the GPL belong to their customers, without any duty on > their part to instruct said customers. I'm gonna stay neutral > on the specifics, but I've always been fascinated by the issues > of NON-weakest preconditions and qualification in many fields > (natural language, programming, and logic) so I couldn't resist...:-) > > > Alex > Puuuhhh! And I just ordered your Nutshell book. God thing it was COD! Joke aside, I'm sure it's fine, I just coldn't resist either......:-) Rgds Tim R. -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From sammyelal at hotmail.com Fri Nov 28 08:06:14 2003 From: sammyelal at hotmail.com (Sammy) Date: 28 Nov 2003 05:06:14 -0800 Subject: Py_RunFile() Message-ID: <6fe6e3b4.0311280506.51e57495@posting.google.com> Hi Does anybody has any luck using the funtion Py_RunFile() in VC .Net 2003 It seams like the only function I can't get to work. It works fine with VC studio 6.0 Any thoughts and does anybody know if python has been tested with .Net yet. From amk at amk.ca Fri Nov 14 07:28:24 2003 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 14 Nov 2003 06:28:24 -0600 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> <84fc4588.0311140319.3778de15@posting.google.com> Message-ID: On 14 Nov 2003 03:19:49 -0800, Anand Pillai wrote: > I would prefer to see more books on Python though they all might > be useless from a pure techie point of view. Let us have Consider two situations: 1) There are four introductory Python books. All sell X copies; the publishers make money and are happy. 2) There are twelve introductory Python books. All sell X/3 copies; the publishers lose money and let them go out of print. (Example: the O'Reilly Python Standard Library book.) There's a finite number of dollars being spent on general Python books; no point in having 15 titles chasing after the same market. The recent run of topic-specific books is very heartening, however. --amk From mis6 at pitt.edu Thu Nov 6 10:04:07 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 6 Nov 2003 07:04:07 -0800 Subject: screensaver Message-ID: <2259b0e2.0311060704.754a4b6e@posting.google.com> I would like to disable/enable the screensaver on a Win98 box with a Python script. Any suggestion? Thanks, Michele From jjl at pobox.com Thu Nov 27 18:31:17 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Nov 2003 23:31:17 +0000 Subject: math.pow vs pow References: Message-ID: <87k75lmlru.fsf@pobox.com> Clueless Moron writes: > Why do they act differently with respect to complex numbers? [...] > Apart from handling complex numbers, the built-in pow also has a > modulo efficiency hack. > > When would I want to use math.pow? For some applications, getting a complex result means you've made a mistake. And some people don't know what a complex number is, and would rather have their teeth drilled than find out. John You wouldn't know a subtle plan if it painted itself purple and danced naked on top of a harpsichord singing 'Subtle Plans Are Here Again' Blackadder From skip at pobox.com Mon Nov 3 16:20:30 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 3 Nov 2003 15:20:30 -0600 Subject: Qn: Nested dictionary cleanup In-Reply-To: <3fa6c327$1@news.iconz.co.nz> References: <3fa6c327$1@news.iconz.co.nz> Message-ID: <16294.50846.267758.386669@montanaro.dyndns.org> Colin> for key1 in dict1.keys(): Colin> for key2 in dict1[key1]: Colin> if dict1[key1][key2] == None: Colin> del dict1[key1][key2] Should be for key1 in dict1.keys(): for key2 in dict1[key1].keys(): if dict1[key1][key2] == None: del dict1[key1][key2] Note that the inner for loop explicitly calls .keys(). That creates an explicit list. You loop over that instead of an iterator. Why did you choose to call dict1.keys() but not dict1[key1].keys()? Skip From fperez528 at yahoo.com Fri Nov 7 19:19:14 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 07 Nov 2003 17:19:14 -0700 Subject: Why I love Python: More rambling... References: <20031028061245.12451.00000133@mb-m01.aol.com> <92c59a2c.0311011455.45b2f5e4@posting.google.com> Message-ID: Juha Autero wrote: > Fernando Perez writes: > >> Tests made by a blitz developer with the SGI C++ compiler show far >> better scaling (with the rank of the tensors), but I needed to run >> this on linux boxes using g++. > > What kind of Linux boxes? Intel has a C++ compiler for Linux that is > clamed to be better than GCC. It is not free and naturally only > available for x86, but if you can live with those terms, you could try > the free evaluation version to see if it helps. > I tested ifc on blitz++ code, and it's not significantly better than g++. The issue is the expression templates used by blitz++, which ifc doesn't seem to handle any better than g++. Granted, my testing was not exhaustive, but that was the quick feeling I got. Note that these issues creep up in blitz++ only when using their tensor index objects at high rank, a somewhat dark corner case which obviously puts compilers in a world of pain. Best, f From M.Waack at gmx.de Sat Nov 8 05:01:39 2003 From: M.Waack at gmx.de (Mathias Waack) Date: Sat, 08 Nov 2003 11:01:39 +0100 Subject: Can I hook a "file" to a python script? References: Message-ID: <3hru71-7p3.ln1@valpo.de> Scott Chapman wrote: > I'd like a "file" on the Linux box to actually be the input and > output > of a Python script. Anything written to the file would be sent to > a database and anything read from the file would come from the > database. I know how to do the database end of this but I'm not > sure if a script > can be hooked to a "file" transparently. The script would probably > have to be run as a daemon. I doubt there's enough magic in the > Linux world to make it so that a read/write would actually launch > the script. That'd be Ok. The solution is very easy. There are at least two ways. First the easier one: create a named pipe using mkfifo(1) and start your python script which should attach itself to one end of the pipe. The second solution is bit more complex: you need a new device. The device driver will only forward all input to your user space daemon or read all output from it. This way your python script can be started automagically each time someone accesses the device special file. And I'm sure there is a whole bunch of other solutions... Mathias From alvmart at terra.es Wed Nov 12 16:50:54 2003 From: alvmart at terra.es (Alv Mart) Date: Wed, 12 Nov 2003 21:50:54 GMT Subject: ADO and Makepy Message-ID: <2Xxsb.1046331$uj6.2632860@telenews.teleline.es> Hi, I ran makepy for ADO. After I installed a new version of python I have this error: Do you know why could I have this error? >>> from ADODB import Connection,Recordset >>> conn = Connection() Traceback (most recent call last): File "", line 1, in ? File "C:\Python2\lib\site-packages\win32com\client\__init__.py", line 479, in __init__ if oobj is None: oobj = pythoncom.new(self.CLSID) TypeError: Only strings and iids can be converted to a CLSID. I have run makepy again but it does not work egards From jbublitzno at spamnwinternet.com Tue Nov 18 11:17:32 2003 From: jbublitzno at spamnwinternet.com (Jim Bublitz) Date: Tue, 18 Nov 2003 16:17:32 GMT Subject: PyQt, Qt, Windows and Linux References: <87d6bpvnu3.fsf@pobox.com> Message-ID: John J. Lee wrote: > Jim Bublitz writes: >> Jim Bublitz wrote: > [...] >> Following up on my own message, David Boddie has just released >> PyKDE addons for doing KParts, KDE Control Center Modules and > [...] >> This will still require installing sip/PyQt/PyKDE but looks >> like it will be maintained separate from the normal PyKDE >> distribution. > Not *another* package! Qt, sip, PyQt, PyKDE, and now this... > (not to mention Qwt and PyQwt, if you use those). Couldn't you > combine the packages, at least after Paul's package settles > down a bit? You left out eric :) The logic of separating the packages (beyond making them easier to build) goes like this: sip is a general purpose C++ -> Python bindings generator and run-time and while it has enhancements for PyQt, doesn't require PyQt. A lot of people who use PyQt have no desire to use PyKDE or PyQwt (or PyQt + PyQwt but not PyKDE). There are a lot of PyQt users running Windows and OSX support is in place for sip/PyQt 4, which is in pre-release. Probably most people using PyKDE won't want to write KParts or other plugin type stuff. PyQt and PyKDE also have fairly long compile times, or when packaged as binaries, are usually split into pieces themselves (eg PyQt, PyQt-devel, etc). The other consideration is that each of the packages is developed mostly independently and while there is a lot of communication between us, we all have conflicting goals, schedules and development styles. Right now the binaries are also produced independent of the developers as well. There are probably more packages coming over the next year, too. Jim From guettli at thomas-guettler.de Tue Nov 18 10:26:38 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 18 Nov 2003 16:26:38 +0100 Subject: Unit Testing Examples References: Message-ID: Am Mon, 17 Nov 2003 09:10:32 -0800 schrieb Tom Verbeure: > Hello All, > > so I'm now convinced that unit testing is really the way to go and I > want to add it to an existing project. The first thing that I find > out, is that, well, it's hard work. Harder than writing the real > functional code. If you are using objects which are containers for other objects, you could do it like this: Every object gets a method called "unittest". This performs a unittest on its own data, and then calls unittest() for all child objects. This way you can check all objects by calling unittest for the root object, or call the method for only a part. Be sure to do no recursion if you have circular data. thomas From john at rygannon.com Fri Nov 7 11:33:49 2003 From: john at rygannon.com (John Dean) Date: Fri, 7 Nov 2003 16:33:49 GMT Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <3fabc945$0$12680$fa0fcedb@lovejoy.zen.co.uk> > [Richie] > > Your website (http://www.totalrekall.co.uk) says "The GPL version would > > be > > free for non-commercial use", which is a contradiction. The above statement has been removed. But I should point out that only Rekall for Linux will be released under the GPL. If all goes well those variant will follow > > [Phil] > > There's nothing innacurate or contradictory in that statement. After > > all, the GPL *is* "free for non-commercial use"; it just happens to > > be free for commerical use as well -- and the website doesn't say > > that it isn't, it just omits to mention that it is. > > You are right of course. Let me be more precise (addressing John again): > > The words used on your website seem to me to imply that the GPL version > could not be used commercially. If that is the intention of those words, > you are mistaken about either the meaning of the GPL, or your power as a > copyright owner to control the application of the GPL to your code. If > you release your code under the GPL, it can be used commercially, and you > cannot change that. > > (I vote Phil for pedant of the week. 8-) -- Best Regards John From des.small at bristol.ac.uk Thu Nov 27 09:30:40 2003 From: des.small at bristol.ac.uk (Des Small) Date: Thu, 27 Nov 2003 14:30:40 GMT Subject: invert dictionary with list &c References: Message-ID: Des Small writes: > anton muhin writes: [...] > This, however, has given me ideas. It was never concision I wanted > but rather redundancy elimination, and the pattern I wanted _can_ be > written: > > def dict_cons(iter, func, default): > def process_element(d, (k, v)): > val = d.get(k, default) > d.update(dict([[k, func(v, val)]])) > return d > return reduce(process_element, iter, {}) Or rather: def dict_cons(iter, func, default): def process_element(d, (k, v)): d[k] = func(v, d.get(k, default)) return d return reduce(process_element, iter, {}) def count(l): def pair_pad(l): return [(e, ()) for e in l] return dict_cons(pair_pad(l), lambda k,d: d+1, 0) def invert(d): def invertitems(l): for k,v in l: yield v,k def addtolist(k, l): return l+[k] return dict_cons(invertitems(d.iteritems()), addtolist, []) > Which is not to say that it should be, of course. > Whereupon, we can say: > > def count(l): > def pair_pad(l): return [(e, ()) for e in l] > return dict_cons(pair_pad(l), lambda k,d: d+1, 0) > > def invert(d): > def invertitems(l): for k,v in l: yield v,k > def addtolist(k, l): return l+[k] > return dict_cons(invertitems(d.iteritems()), > addtolist, []) > > Perhaps I'm terminally unpythonic, but I quite like these. [...] -- "[T]he structural trend in linguistics which took root with the International Congresses of the twenties and early thirties [...] had close and effective connections with phenomenology in its Husserlian and Hegelian versions." -- Roman Jakobson From ramen at lackingtalent.com Mon Nov 3 00:21:21 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 03 Nov 2003 05:21:21 -0000 Subject: delete duplicates in list References: Message-ID: In article , Martin Chilvers wrote: > Maybe I'm just old-school, and it won't win any prizes for speed but... > >>>> a = [1, 3, 2, 3, 4, 2, 1, 4, 3, 2, 1, 2, 4] >>>> reduce(lambda l, x: x not in l and l.append(x) or l, a, []) > [1, 3, 2, 4] > > ;^) Hey, I wanna play this game too: [d.setdefault(x, x) for d in [{}] for x in a if x not in d] Now, try replacing that with "old-school" functionals. I'm stumped. =) -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From mjancar at suse.cz Tue Nov 18 13:03:53 2003 From: mjancar at suse.cz (Marian Jancar) Date: Tue, 18 Nov 2003 19:03:53 +0100 Subject: spec file parsing Message-ID: <20031118190353.1a1fba93.mjancar@suse.cz> Hi, Is there a module for parsing spec files available? Marian -- -- Best Regards, Marian Jancar software developer --------------------------------------------------------------------- SuSE CR, s.r.o. e-mail: mjancar at suse.cz Drahobejlova 27 tel:+420 283 095 382 190 00 Praha 9 fax:+420 283 095 374 Czech Republic http://www.suse.cz From tjreedy at udel.edu Fri Nov 7 21:38:57 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 7 Nov 2003 21:38:57 -0500 Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: "Alex Martelli" wrote in message news:aKVqb.109736$e5.3978380 at news1.tin.it... > above. Try: > x = reduce(operator.add, listoflists, x) > vs: > for L in listoflists: x.extend(L) > for a sufficiently big listoflists, and you'll see... (the latter if need be > can get another nice little multiplicative speedup by hoisting the x.extend > lookup, but the key issue is O(N**2) reduce vs O(N) loop...). Right: however that issue and the possibility of hoisting x.extend have *nothing* to do with reduce vs. for. For a fair comparison of the latter pair, try the following, which is algorithmicly equivalent to your sped-up for loop. >>> xs=[[i] for i in range(10)] >>> x=[] >>> xtend=x.extend >>> reduce(lambda dum,L: xtend(L), xs, x) >>> x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [timeits snipped]... > See what I mean? That you hate reduce? I am sure that the O(N) reduce would be similarly faster than an O(N**2) operator.add for loop: what would *that* mean? > Already for a mere 999 1-item lists, the plain Python > code is 10 times faster than reduce, No, you have only shown that for N=999, O(N) can be O(N**2)/10, and that smart programmers who understand that can write better (faster) code than those who do not. Terry J. Reedy PS: for practical rather than didactic programming, I am pretty sure I would have written a for loop 'reduced' with xtend. From frank at chagford.com Thu Nov 6 05:51:42 2003 From: frank at chagford.com (Frank Millman) Date: 6 Nov 2003 02:51:42 -0800 Subject: Question re threading and serial i/o References: <246a4e07.0311040705.5f8d9a9@posting.google.com> <3FA7CB03.6B650215@engcorp.com> Message-ID: <246a4e07.0311060251.3a24d5b@posting.google.com> > Frank Millman wrote: > > > > def scan(): > > p = file('/dev/ttyS0') > > txt = [] > > while x: > > ch = p.read(1) > Peter Hansen wrote: > The last line above is the heart of the problem... > > You need to use the select.select() function with a timeout, so that > you can wake up periodically to check a flag that is set by the other > thread, asking the i/o thread to terminate. select() will return > immediately if the file has data waiting to be read, so you don't > significantly decrease the latency of the response in this way. > Thanks a lot for the reply, Peter. I tried select(), but I cannot get it to work properly. If I show you what I am doing, hopefully you can point out the error of my ways. This is my Mk 2 version, that is a bit ugly, but seems to work - def scan(): p = os.open('/dev/ttyS0',os.O_RDONLY|os.O_NONBLOCK) while x: try: print ord(os.read(p,1)) except OSError: time.sleep(0.1) os.close(p) This is my Mk 3 version, using select() - def scan(): p = file('/dev/ttyS0') while x: ans = select.select([p],[],[],0.1) if ans[0]: print ord(p.read(1)) p.close() The scanner sends a string consisting of 'code' 'qty' . If I scan a code of '1' and a quantity of '1', I would expect the program to display 49 9 49 13. The Mk 2 version does this correctly. The Mk 3 version behaves differently. After the first scan, it displays 49. After each subsequent scan, it displays 9 49 13 49. If anyone can explain what I am doing wrong, I will be most grateful. In the meantime I am sticking with Mk 2, as it is doing the job. Platform is Python 2.2.2 on Redhat 9. Thanks in advance Frank From FBatista at uniFON.com.ar Thu Nov 6 13:35:37 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 6 Nov 2003 15:35:37 -0300 Subject: prePEP: Decimal data type Message-ID: Tim Peters wrote: #- They have another choice, because Guido had a brilliant idea: the #- arithmetic operations in Eric's implementation are methods #- *of* a context #- object (because Guido suggested that). So a maximally robust library Now I can explain to myself those lines of code, :) . Facundo From timr at probo.com Wed Nov 19 17:51:35 2003 From: timr at probo.com (Tim Roberts) Date: Wed, 19 Nov 2003 14:51:35 -0800 Subject: question about precision of arithmetic involving empirical, measured quantities Re: Unum 4.0 beta References: <3fb7dbfd$0$241$4d4efb8e@news.be.uu.net> Message-ID: "John Benson" wrote: > >Will this package handle approximate quantities, too? > >Here's some background for the question: > >Let's say you have measured the side of a square area to be 10 meters, +/- 1 >meter. We want to compute the area of the square. > >We are squaring a range of 9 to 11 meters, and get a resulting area range of >81 to 121 square meters. If we take the midpoint of this range as the most >representative value, we end up with (81 + 121)/2 or 101 square meters, >plus-or-minus 20 square meters! Right. Algebra would have told you this: (a-1)**2 + (a+1)**2 = a**2 - 2a + 1 + a**2 + 2a + 1 = 2a**2 + 2 Divide that by two, and you get a**2 + 1. >But what about the discrepancy between 100 and 101? The discrepancy is that you chose to take the center of the range as the "most representative value". There is no mathematical basis for that decision. What you're talking about here is interval arithmetic. Although it is useful for working with approximate measurements, it actually increases the precision of your knowledge. For example, we KNOW that the actual area is in the interval [81,121]. We do NOT know what the exact area is, or even what the best estimate is, and there is no analytical method for extracting that information from the interval. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From aleaxit at yahoo.com Sun Nov 16 10:15:45 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 16 Nov 2003 15:15:45 GMT Subject: Python's simplicity philosophy References: <3FAC19F0.284DCB03@alcyone.com> <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> Message-ID: Andrew Dalke wrote: ... > The other three are in csv.py and look something like > quotechar = reduce(lambda a, b, quotes = quotes: > (quotes[a] > quotes[b]) and a or b, > quotes.keys()) > and are identical in intent to your use case -- select the > object from a list which maximizes some f(obj). I have already suggested, in a post on this thread's direct ancestor 9 days ago, the 100%-equivalent substitution in pure, simple, faster Python: quotechar = None for k in quotes: if not quotechar or quotes[k]>quotes[quotechar]: quotechar = k or, for those who consider fast, simple, obviously correct code too boring, quotechar = max([ (v,k) for k,v in quotes.iteritems() ])[-1] which is more concise and at least as clever as the original. > This suggests the usefulness of a new function or two, > perhaps in itertools, which applies a function to a list Nope -- itertools is not about CONSUMERS of iterators, which this one would be. All itertools entries RETURN iterators. > of values and returns the first object which has the > maximum value, as in Given that the sort method of lists now has an optional key= argument, I think the obvious approach would be to add the same optional argument to min and max with exactly the same semantics. I.e., just as today: x = max(somelist) somelist.sort() assert x == somelist[-1] we'd also have x = max(somelist, key=whatever) somelist.sort(key=whatever) assert x == somelist[-1] a perfectly natural extension, it seems to me. I've found such total and extreme opposition to this perfectly natural extension in private correspondence about it with another Python committer that I've so far delayed proposing it on python-dev -- for reasons that escape me it would appear to be highly controversial rather than perfectly obvious. > def longest(seq): > return imax(seq, len) That would be max(seq, key=len) in my proposal. > lines. There were very few, and the paucity suggests > that 'sum' isn't needed all that often. Then again, I'm > not one who suggested that that be a builtin function ;) Right, that was my own responsibility. I did identify about 10 spots in the standard library then (including substitutions for reduce); that's more than the typical built-in has, even though the tasks handled by the standard library are heavily slanted to string and text processing, networking &c, and (of course) "pure infrastructure", rather than typical application tasks. Alex From SBrunning at trisystems.co.uk Mon Nov 3 11:35:41 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Mon, 3 Nov 2003 16:35:41 -0000 Subject: programming languages (etc) "web popularity" fun Message-ID: <31575A892FF6D1118F5800600846864D01200C62@intrepid> > From: Dang Griffith [SMTP:noemail at noemail4u.com] > On Sat, 01 Nov 2003 00:53:17 -0000, claird at lairds.com (Cameron Laird) > wrote: > > >Note, too, that the Python one hasn't been on the street > >as long as some of the others. It's reasonable to specu- > >late that the ratios haven't equilibrated yet. > > Not sure I understand your comment. > Python predates Java. He's talking about the 'Nutshell' book, rather than the language. 'Python in a Nutshell' was published early this year, 'Java in a nutshell' in 1996. Cheers, Simon Brunning, http://www.brunningonline.net/simon/blog/ --LongSig ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From joconnor at cybermesa.com Fri Nov 21 12:20:57 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Fri, 21 Nov 2003 10:20:57 -0700 Subject: Garbage collection working improperly? In-Reply-To: References: Message-ID: Aahz wrote: >In article , >Jay O'Connor wrote: > > >>I kinda like VisualWorks Smalltalk's approach. It uses a system whereby >>new objects are scavenged aggresivly and objects that survive the >>scavenger are moved to a different memory space that is not GC'ed nearly >>as much. (New objects tend to have short lives..objects that survive >>several generations of scavenging tend to live longer) When it's memory >>reaches a threshold, it makes a decision as to whether to either request >>more from the OS or to GC the old object memory space in an attempt to >>free more memory. The nice part is that you can configure a. how much >>memory it starts with b. at what point the threshold is set for and >>c.the weighting of the algorithim to determine whether to GC or allocate >> >> > >Python does the same thing -- you just can't configure it as much. > > I remember this in particular because I was working on an application where the performance characteristics were such that for the most part we wanted to allocate new memory rather than GC, but then as the memory we were using reached a certain point, we wanted to free some of our own cached objects so tha the GC could reclaim them. Being able to fine tune the memory usage characteristics, and also hooking into VisualWork's notification mechanism to be informed when GC was happening, proved very important. From rainerd at eldwood.com Tue Nov 11 17:42:14 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Tue, 11 Nov 2003 22:42:14 GMT Subject: Regular expression code implementation review between Tcl vs Python References: <394af34.0311110758.3b1781ea@posting.google.com> <3fdsb.10497$hV.431113@news2.tin.it> Message-ID: Alex Martelli wrote: > Using an OO language doesn't necessarily make implementing another > OO language any easier, when the object models are mismatched (and > they almost invariably are). Using RAII to automate reference count management would certainly help in implementing Python, even if it is a feature that Python itself doesn't have. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From keflimarcusx at aol.comNOSPAM Thu Nov 13 06:35:13 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 13 Nov 2003 11:35:13 GMT Subject: Books I'd like to see References: Message-ID: <20031113063513.20279.00000124@mb-m04.aol.com> Book I'd hate to see: Herbert Schildt Python: The Complete Reference - Kef From mlh at furu.idi.ntnu.no Sat Nov 15 15:03:01 2003 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 15 Nov 2003 20:03:01 +0000 (UTC) Subject: +/-infinity in Python? References: Message-ID: In article , Peter Otten wrote: >Andreas Neudecker wrote: > >> Is there anything like +infinity and -infinity available in Python, and >> can it be used in comparisons together with int or float numbers? > >To lazy to look it up, so let's try: [snip] Looking it up might be good, though... See, for example, PEP 754, "IEEE 754 Floating Point Special Values": http://www.python.org/peps/pep-0754.html The problem is that the expression float('infinity') works on some platforms, along with float('Inf'), but, as the PEP points out, on many systems you'll just get an error. You could also try stuff like float(1e3000). So, my response to the original question would be "sort of" -- since it's there, but it's not particularly reliable. Let's just hope that PEP 754 (or something similar) is accepted; infinity _is_ certainly useful... -- Magnus Lie Hetland "In this house we obey the laws of http://hetland.org thermodynamics!" Homer Simpson From nessus at mit.edu Sat Nov 8 02:21:29 2003 From: nessus at mit.edu (Douglas Alan) Date: Sat, 08 Nov 2003 02:21:29 -0500 Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: Alex Martelli writes: > Existing, builtin functions _will_ be removed in 3.0: Guido is on record > as stating that (at both Europython and OSCON -- I don't recall if he > had already matured that determination at PythonUK time). They > exist for a reason, but when that reason is: "once upon a time, we > thought (perhaps correctly, given the way the rest of the language and > library was at the time) that they were worth having", that's not > sufficient reason to weigh down the language forever with their > not-useful-enough weight. The alternatives to removing those parts that > aren't useful enough any more are, either to stop Python's development > forever, or to make Python _bloated_ with several ways to perform the > same tasks. I agree: Down with bloat! Get rid of sum() -- it's redundant with reduce(), which I use all the time, like so: def longer(x, y): if len(y) > len(x): return y else: return x def longest(seq): return reduce(longer, seq) print longest(("abc", "yumyum!", "hello", "goodbye", "?")) => yumyum! |>oug From jegenye2001 at fw.hu Sat Nov 8 16:47:28 2003 From: jegenye2001 at fw.hu (Jegenye 2001 Bt) Date: Sat, 8 Nov 2003 22:47:28 +0100 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: Message-ID: Edward K. Ream wrote in message news:vqq9rgp1gcl9cb at corp.supernews.com... > > Sounds good. However, I won't try it until there's a shell-based mode; > > I do too much of my work remotely. > > Could you be more-specific about what you mean by "shell-based" mode? What > would have to be different in Leo? > > Are you talking about a version of Leo that doesn't put up a gui? If so, a > null-gui plugin might suffice. If Leo can't do what you want already, I > suspect that adding this feature would be easy. > > Edward > No, I think he means using Leo with a text terminal a la browsing the web with lynx. Btw, a web based interface would be absolutely cool.. Do you see chance to integrate Leo with, say, Zope? Mikl?s -- PRISZNY?K Mikl?s --- Jegenye 2001 Bt. ( jegenye2000 at parkhosting.moc ... to send mail increment the number and reverse the domainname.. ) Egyedi szoftverk?sz?t?s, tan?csad?s Custom software development, consulting http://jegenye2001.parkhosting.com From timr at probo.com Sun Nov 9 02:56:30 2003 From: timr at probo.com (Tim Roberts) Date: Sat, 08 Nov 2003 23:56:30 -0800 Subject: Decoding email attachments. References: Message-ID: Thomas Williams wrote: > >When I use this line jpg attachment, come out darker >that it's suppose to be. > >filelne = filelne + base64.decodestring(line) Compared to what? I can think of two possibilities. Image applications do color management differently. So, for example, a JPEG viewed in Microsoft's default image viewer wil look different from the same JPEG viewed in Photoshop. Alternately, if you're running Windows, you might be writing the file out in text-mode instead of using open('xxx.jpg','wb') to write it in binary. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mwh at python.net Thu Nov 6 07:39:59 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 6 Nov 2003 12:39:59 GMT Subject: Python on Powerpc References: <221d8dbe.0311060007.54db50d1@posting.google.com> Message-ID: <7h3brrphdxf.fsf@pc150.maths.bris.ac.uk> srijit at yahoo.com writes: > Hello, > Has anyone ported Python on powerpc(ppc8xx) with Linux? Is this some kind of embedded situation? If you have a C compiler and a vaguely POSIX-ish environment and a reasonable amount of memory, it should more-or-less just work (but I have little experience in this situation). Python runs just fine on the PowerPC when the PowerPC is in a Mac :-) Cheers, mwh -- > It might get my attention if you'd spin around in your chair, > spoke in tongues, and puked jets of green goblin goo. I can arrange for this. ;-) -- Barry Warsaw & Fred Drake From exarkun at intarweb.us Sun Nov 16 01:12:38 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sun, 16 Nov 2003 01:12:38 -0500 Subject: Gadfly DB in python standard library? In-Reply-To: References: <3fe406f0.0311141353.3aec780f@posting.google.com> Message-ID: <20031116061238.GA4063@intarweb.us> On Sat, Nov 15, 2003 at 04:30:04PM -0600, A.M. Kuchling wrote: > On Sun, 16 Nov 2003 03:38:08 +1100, > Anthony Baxter wrote: > > I believe there is still merit to including an SQL database being in > > the standard distribution of python - personally I could live with > > sqlite being included. > > +1 from me. In retrospect, it probably would have been more useful to add > sqlite than BerkeleyDB support to Python 2.3. > FWIW, I'm glad bsddb is there :) Jp From hungjunglu at yahoo.com Sat Nov 8 01:37:27 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 7 Nov 2003 22:37:27 -0800 Subject: Pure Aspect-Oriented Program: an example References: <8ef9bea6.0311052119.4f5ab5d6@posting.google.com> Message-ID: <8ef9bea6.0311072237.3f991318@posting.google.com> Richie Hindle wrote in message news:... > > Fantastic! That's the best introduction to the concepts of AOP I've seen. > Many thanks for a very clear and thought-provoking article. > > Now please implement it for Python, including your proposed IDE. 8-) Yeah, right. :) I do realize that people are converging in their ideas. AOP is becoming more and more clear with each passing day. That's really exciting. But I believe things have not yet finalized, and I am not a "marketoid" to go out and sell half-baked ideas. :) Java folks have economical resources, but their language puts so much handcuff on them that AOP there is kind of hard to use. Ruby is perhaps the language that's easiest to accomodate, and Python comes a close second. As for IDEs, you can bet Java folks will have something before anyone else. Although I am not sure why people'd keep investing effort into such a rigid language. See for instance: http://www.hpcc.gov/iwg/sdp/vanderbilt/position_papers/gregor_kiczales_aspect_oriented_programming.pdf where people are focusing a bit on IDE already, though theirs is not nearly as good as my proposed one. :) Hung Jung From mike at nospam.com Tue Nov 11 20:28:55 2003 From: mike at nospam.com (Mike Rovner) Date: Tue, 11 Nov 2003 17:28:55 -0800 Subject: Structured Text or ReStructured Text Viewer References: Message-ID: Hoang wrote: > yes, I ran across that in my search and was very unhappy that it was > only for the Mac. I wonder if the tool was written in Python. Yes, it is. But it tightly coupled with Apple design tools, framework etc. You might want to take a look at docutils subproject DocFactory at http://docutils.sourceforge.net/sandbox/gschwant/docfactory/doc/ which is wxPython based and cross-platform. Mike From peter at engcorp.com Mon Nov 3 15:24:49 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Nov 2003 15:24:49 -0500 Subject: programming languages (etc) "web popularity" fun References: <3d06fae9.0310310915.4447d4ca@posting.google.com> <9Zzob.75517$e5.2773519@news1.tin.it> <2531b4fb3a153253e29f8a74f733aef1@news.teranews.com> <3FA68205.636ED781@engcorp.com> <7433c90b9d6a866ceaabce31235cfb59@news.teranews.com> Message-ID: <3FA6B991.80C8BD0B@engcorp.com> Dang Griffith wrote: > > On Mon, 03 Nov 2003 11:27:49 -0500, Peter Hansen > wrote: > > >Dang Griffith wrote: > >> > >> On Sat, 01 Nov 2003 00:53:17 -0000, claird at lairds.com (Cameron Laird) > >> wrote: > >> > >> >Note, too, that the Python one hasn't been on the street > >> >as long as some of the others. It's reasonable to specu- > >> >late that the ratios haven't equilibrated yet. > >> > >> Not sure I understand your comment. > >> Python predates Java. > >> --dang > > > >I'm sure Cameron is quite aware of that, and yet your comment > >does nothing to invalidate his statement. Surely you can accept > >that "Python hasn't been on the street as long as *some* of > >the others" (emphasis added), can't you? > > > >-Peter > I definitely accept that--I had glossed over the 'in a nutshell' > portion of Alex' post, and thought the comment was about the > language's popularity, not the nutshell books. We both made the same mistake, actually, as I had missed the nutshell parts as well until Peter Otten's reply. > Apologies for my confusion infusion, hopefully, now defused. Yes, let's get back to useful topics. :-) -Peter From joconnor at cybermesa.com Sat Nov 29 18:03:56 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Sat, 29 Nov 2003 16:03:56 -0700 Subject: sorting dictionary keys? In-Reply-To: <3fc91af5$0$28610$636a55ce@news.free.fr> References: <3fc91af5$0$28610$636a55ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Jay O'Connor wrote: > >> John Smith wrote: >> >> > Hi, what's the fastest way (least amount of typing) >> >> Never good criteria >> >>> but I would like to do: >>> #error here >>> for k in d.keys().sort(): >>> print k, d[k] >>> >>> why doesn't the nested function call work? Thanks in advance. >>> >> >> sort() sorts in place and returns None >> > > > Which is one of the main PITA in Python IMHO :( > (not the fact that it sort in place, the fact that it does not return > self). > Arguably, if that's a main PITA, that's not too bad. I like Python, but there are other things about it that bug me more. It's a minor annoyance and given the name, I think it makes sense. If it returned itself or a copy, the name should probably be sorted() From aaron at reportlab.com Wed Nov 19 12:24:51 2003 From: aaron at reportlab.com (Aaron Watters) Date: 19 Nov 2003 09:24:51 -0800 Subject: rotor alternative? References: <9a6d7d9d.0311181113.3bf45ec8@posting.google.com> <7xwu9x32j2.fsf@ruckus.brouhaha.com> Message-ID: <9a6d7d9d.0311190924.bdf3ac6@posting.google.com> Paul Rubin wrote in message news:<7xwu9x32j2.fsf at ruckus.brouhaha.com>... > aaron at reportlab.com (Aaron Watters) writes: > > > Is an alternative to rotor planned? > > > http://athos.rutgers.edu/~aaron/python/pulver.py> > At first glance that function looks awful (no offense intended), and > the implementation looks very slow. I'd strongly advise against doing > anything serious with it. If you want a pure-Python cipher, please try > > http://www.nightsong.com/phr/crypto/p3.py Offense taken :(. Please explain (offline if you like). It's okay to call my stuff awful, but I require a bit of constructive criticism to go with it. FWIW it was loosely inspired by RC4 and it seems to scramble things up nicely. Regarding speed: for small blocks it should be reasonably fast for a pure python module which doesn't use any extension modules, and it is also suitable for conversion into a very small self contained C function, which was the intent. But yours is much faster of course, since it uses an extension module for the critical loop. For larger blocks more than an order of magnitude faster. This is the timing I get when I modify your test function % python p3.py (yours) plain p3: 1000 5 0.22000002861 sec = 22727.2697717 bytes/sec plain p3: 1000 20 0.261000037193 sec = 76628.3415706 bytes/sec plain p3: 1000 200 0.520999908447 sec = 383877.226766 bytes/sec plain p3: 100 2000 0.300000071526 sec = 666666.507721 bytes/sec (mine) plain pulver: 1000 5 0.210000038147 sec = 23809.5194845 bytes/sec plain pulver: 1000 20 0.680999994278 sec = 29368.5758708 bytes/sec plain pulver: 1000 200 5.94900000095 sec = 33619.0956409 bytes/sec plain pulver: 100 2000 5.76800000668 sec = 34674.0637601 bytes/sec In a C implementation I think mine would be more than competitive, however. The two are not precisely comparable, I think, because as far as I can tell you just encrypt a single string, whereas mine encrypts a sequence of strings progressively, unless I'm missing something. Obviously, I have something really important to do, otherwise I wouldn't be procrastinating like this :(... Enough goofing off... -- Aaron Watters === never eat anything bigger than your head. -kliban From mal at egenix.com Wed Nov 26 04:51:04 2003 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 26 Nov 2003 10:51:04 +0100 Subject: Database connect / PDO In-Reply-To: <04ca01c3b3bc$00f7a8c0$7401a8c0@voidmk9> References: <3FC248D1.3090603@ghaering.de> <030d01c3b2d9$4220a970$7401a8c0@voidmk9> <3FC3323A.3050209@egenix.com> <046d01c3b37e$f74fd000$7401a8c0@voidmk9> <3FC3BACB.9090705@egenix.com> <04ca01c3b3bc$00f7a8c0$7401a8c0@voidmk9> Message-ID: <3FC47788.2070700@egenix.com> Jon Franz wrote: >>Can you present a use case ? display_size is predefined statically in >>ODBC: >> > > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odappdpr_28.asp > >>I can't think of any use case for internal size... > > Variable length character (or binary) fields... > I've written many a piece of code over the years that has had to > create dynamic edit forms for a database. Variable length > character fields are common place, and I've always found that > enforcing the limit at edit time, rather than letting an error be > raised or data be silently truncated, is a good practice. Ah, now I understand: for VARCHAR columns, that information is available in the precision field of .descpription. It may sound like the wrong entry, but that's where ODBC put's this information. OTOH, what the optional description entries really mean is not defined anywhere in the DB API. Perhaps we should fix that (on the db-sig mailing list where these discussions usually happen) ?! -- Marc-Andre Lemburg eGenix.com Professional Python Software directly from the Source (#1, Nov 26 2003) >>> Python/Zope Products & Consulting ... http://www.egenix.com/ >>> mxODBC.Zope Database Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From no-spam at no-spam.org Mon Nov 3 17:18:08 2003 From: no-spam at no-spam.org (Krister L.) Date: Mon, 3 Nov 2003 22:18:08 +0000 (UTC) Subject: Max 64 connections/thread under Windows? Message-ID: Hi all, Newbie warning on. I'm having a problem under Windows where I'm getting an error 10055 when I'm using select() and having 64 sockets open in a single thread. The description for 10055 is "An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full". I found some more info about this here: http://www.sockets.com/winsock.htm#Deviation_MaxSockets When reading /Python-2.3.2/Modules/selectmodule.c I found the following snippet /* Windows #defines FD_SETSIZE to 64 if FD_SETSIZE isn't already defined. 64 is too small (too many people have bumped into that limit). Here we boost it. Users who want even more than the boosted limit should #define FD_SETSIZE higher before this; e.g., via compiler /D switch. */ #if defined(MS_WINDOWS) && !defined(FD_SETSIZE) #define FD_SETSIZE 512 #endif which to me looks like Python is trying to increase the value of this constant, but fails to do so (My only evidence for this is that I'm getting this error). To pick up the errno I also need to write something like except error, (errno, strerror): when I would expect except error errno, strerror = error to work if I have interpreted the documentation correctly: ...The exception raised when an error occurs. The accompanying value is a pair containing the numeric error code from errno and the corresponding string, as would be printed by the C function perror(). Should this trigger a WindowsError exception by the way? (selectmodule.c calls PyErr_SetExcFromWindowsErr to create the exception.) /Krister From tim.one at comcast.net Sun Nov 23 14:45:36 2003 From: tim.one at comcast.net (Tim Peters) Date: Sun, 23 Nov 2003 14:45:36 -0500 Subject: strange exponentiation performance In-Reply-To: Message-ID: [Jeff Davis] > I was doing some thinking about exponentiation algorithms along with a > friend, and I happened upon some interesting results. Particularly, I > was able to outperform the ** operator in at least one case, with a > recursive algorithm. This leads me to believe that perhaps the ** > operator should tune it's algorithm based on inputs or some such > thing. Here is my data: I'm taking the liberty of rewriting your functions to stop trying to squash as much as they can on each line. It's important to do that if you want to modify the code quickly when experimenting. First you rediscovered the "left to right" binary exponentiation algorithm: def h(b, e): if e == 0: return 1 if e == 1: return b t = h(b, e >> 1) return t*t * h(b, e & 1) When you tried to remove recursion from it, you rediscovered the "right to left" binary exponentiation algorithm: def f(b, e): n = 1 while e > 0: if e & 1: n *= b e >>= 1 b *= b return n That's close to what Python's builtin ** does, but is missing an important speed trick (explained later). Note that h and f aren't really the *same* algorithm! f squares the current value of b on every trip through the loop. h does not. If you print out all the inputs to all the multiplications, you'll see that they're not at all the same. Finally (I'll skip g(), as it isn't interesting): def o(b, e): return b**e > ... > now, g() was blown out of the water, as expected, but the others were > close enough for another test at a higher "e" value. > > >>> test(f,19,500000) > 8.02366995811 > >>> test(h,19,500000) > 3.66968798637 > >>> test(o,19,500000) > 5.29517292976 > >>> Your box is faster than mine. Here under 2.3.2 on Windows: f 14.6648669941 h 6.53576912117 o 9.59630399437 > Now, that is the interesting part. How did ** not measure up to h()? The left-to-right exponentiation algorithm can be faster than the right-to-left one. The former is clumsier to code in C, though, and nobody ever bothered to endure that pain in Python's implementation. If you search the archives hard enough, you'll eventually find a thread about this from Christian Tismer. Neither algorithm is optimal for all inputs, BTW. Turns out optimal exponentiation is a very hard problem; Knuth Volume 2 has an extensive discussion of this ("Evaluation of Powers"); another algorithm based on first factoring the exponent (expressing it as a product of primes) is better "on average" than either binary method, but sometimes loses to them. > It's also interesting that f(), which is supposed to be a more > efficient version of h(), is lagging behind. The biggest trick it's missing is that it *always* does b *= b even on the last trip through the loop. The value of b it computes on the last trip is never used, and b has grown very large by that time so computing b*b is *very* expensive then. Change f like so: def f(b, e): n = 1 while e > 0: if e & 1: n *= b e >>= 1 if e: # new guard: only square b if the result will be used b *= b return n and then it's essentially identical to the builtin **: f 9.5959586986 h 6.54231046447 o 9.59677081413 > I would like help explaining the following: > (1) How did my less-than-perfectly-optimized recursive algorithm win > against the ** operator? It used left-to-right instead of right-to-left, which on this pair of inputs is a better approach. > (2) How can I unwrap and optimize h()? Make it work left-to-right instead of right-to-left. That's tedious to do. You can't get the same sequence of multiplication inputs by going right-to-left, so the code will have to be more complicated. Start by finding the highest bit set in e. For example, def q(b, e): if e == 0: return 1 if e == 1: return b e2, numbits = e, 0 while e2: e2 >>= 1 numbits += 1 assert numbits >= 2 result = b mask = 1L << (numbits - 2) for dummy in range(numbits - 1): result *= result if e & mask: result *= b mask >>= 1 return result That's bound to be a little faster than h on most inputs, because it also optimizes away multiplications by 1 (well, unless b happens to be 1). Let's see: f 9.53526793946 o 9.53408287098 h 6.54592768903 q 6.11897031462 Yup, those matter, but not a whale of a lot. The savings in skipping multiplications by 1 is proportional to the number of 0 bits in the exponent. What *didn't* matter is whether it's recursive or iterative. > From what I understand,recursion is never supposed to be the most > efficient. I suspect there are some hidden inefficiencies in using > while(), but I'd like to know the specifics. Na, none of that matters. All these algorithms do a number of multiplications proportional to log(e, 2), which is insignificantly tiny compared to the magnitude of the result. Long-int multiplication is the only thing that consumes significant time here, so the only thing that matters to the time is the exact sequence of inputs fed to *. Even whether you write the *driver* in Python or C or assembly language is insignificant compared to that. > If my algorithm h() is better, why can't ** use a quick test to change > algorithms based on inputs? Or is mine better in all cases? See Knuth . > ... > Also note that I'm not exactly an algorithms expert, I just happened > upon these results while chatting with a friend. You did good! The first couple things you tried only nick the surface of what's known about this problem. You *could* spend a year learning everything that's known about it. In the end, if you implemented all that, you could easily end up with 1000x more code, which sometimes ran faster. To become an algorithm expert, you should do that . In real life, a crucial complementary skill is learning when to say "good enough", and move on. That's indeed why Python's implementation settled for the easy-to-code-in-C right-to-left binary exponentiation method. If that part of Python had been written in Python instead, I would have used the easy-to-code-in-Python recursive left-to-right method instead. Sticking to easy-to-code methods also has good influence on minimizing the # of bugs, of course. From aleax at aleax.it Mon Nov 10 07:25:14 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 10 Nov 2003 12:25:14 GMT Subject: Am I the only one who would love these extentions? - Python 3.0 proposals (long) References: Message-ID: Georgy Pruss wrote: > "Alex Martelli" wrote in message > news:K3Krb.446059$R32.14871630 at news2.tin.it... > | Georgy Pruss wrote: > | ... > | > I would like to propose some extentions to the language, probably > | > for the version 3.0. They are mainly lexical or syntactical and the > | > language will stay compatible with 2.X (even although it was > | > | Not at all -- these changes would break the vast majority of > | significant, well-coded existing Python programs, for example by > | removing the 'else' clause on 'try' for no other reason that it "sounds > | very unnatural" to you. (I'm not sure how extensive your Python > | experience is, but this remark suggests "not very"). > > That particular item, 'else' for 'try' and 'for' has the lowest priority > for me, if I dare to say so. Of course I understand that it would break > many many existing programs. It's not just that: it would break *well-coded* programs, programs that are coded using the _BEST, MOST APPROPRIATE_ constructs, and not give any really good alternative way to recode them. It's not so much the 'else' on _for_ -- removing _that_ would break a zillion good programs, but the alternatives are almost decent, at least in most cases. But the 'else' on _try_?!?! How would you code around _THAT_ lack? One sign that somebody has moved from "Python newbie" to "good Python programmer" is exactly the moment they realize why it's wrong to code: try: x = could_raise_an_exception(23) process(x) except Exception, err: deal_with_exception(err) proceed_here() and why the one obvious way is, instead: try: x = could_raise_an_exception(23) except Exception, err: deal_with_exception(err) else: process(x) proceed_here() What WOULD sound natural to you in order to express the crucial pattern: 1. first, try doing "this and that" 2. if "this and that" raises such an exception, do something 3. else (i.e. if it doesn't raise exceptions) do s/thing else instead 4. and then in either case proceed from here ...??? Trying to kludge it around with "status-flag" variables isn't very satisfactory, of course -- it can only complicate things and add error-prone needs for setting and resetting "status flags". To me, removing 'else' from 'try' and proposing to use status-flags instead is about as sensible as making the same proposal regarding 'if' -- i.e., not very. > My main suggestions were the first ones, > dealing mainly with the lexer and the parser of Python. Ah, I see -- you probably weakened the effectiveness of your post by mixing in it things you cared little about and at the same time were such as to ensure alarm among experienced Pythonistas. Each of your proposals requires very detailed analysis to become a PEP. For example, consider one I do like a bit: the ability to insert underscores in literal numbers. If we enrich the lexer to allow that, I would _also_ want at the very least a warning to be raised if the underscores are not inserted at "regular" intervals -- this would, I think, enhance the usefulness, by making the lexer able to help diagnose at least _some_ typos in number literals. However, there seem to be arguments for at least two approaches: one, just force the number of digits allowed between underscores to exactly three -- probably the most common usage; or, two, allow any number of digits between underscores as long as the usage is "consistent" (within a single number? or in a larger lexical unit, and, if so, which one -- a module?). In either case, the issue of number of digits allowed before the first underscore and after the last one should be tackled -- perhaps differently for sequences of digits that come before a decimal point (or without any at all) or after a decimal point. Further, if we're able to _input_, say, 1_000_000 to indicate "a million" to the lexer -- surely we'll want that same ability when the same string is otherwise recovered (e.g. read from a file) and then transformed into an integer by calling int(s). Should int(s) just accept underscores in string s, or be more selective? Should underscores perhaps only be accepted in int(...) [and other type constructors such as long(...), float(...), ...) if explicitly enabled by an optional argument? And what about the _output_ side of things? Surely if 1_000_000 becomes an acceptable syntax for "one million" there should be a simple way to make the number 1000000 _print out_ that way. Should that be through some optional argument to str() and/or repr()? Or a new function (and/or method), and where located? How would we get that effect with the %-formatting operator? A PEP on this single change to the language would stand no chance of acceptance -- it would probably, and quite correctly, just get rejected outright by the PEP-editor, as clearly under-researched -- unless each and every one of these points (and probably more yet that I haven't thought of -- all of the above is the result of just a couple minutes' worth of thought, after all!) was identified and clearly addressed, indicating what design choices were considered and why they were accepted or rejected. Considerations about how such things are dealt with in other languages and why adopting their solutions would be appropriate or inappropriate in Python would be very helpful here, too. And this one is probably the simplest out of all of your wishes, right? Plus, as I said, is one I might well like, so I'm definitely not "looking for excuses" against it -- on the contrary, I'm trying to pin down enough details so it stands a _chance_ (and it might, even in Python 2.4, since changes that are useful and backwards-compatible ARE under consideration for that, the next release). > I have rather little experience with Python, but very big programming > experience. I remember PL/I and IBM/360 assembler :) And I like Python a > lot. Yep, I also recall PL/I (not very fondly...) and BAL (very fondly indeed, though I admit it was on a /370 that I was using it -- I don't think there were any /360's left by that time, at least not in IBM Research). > No, no. I don't think that it's a good idea to fork Python. Again, I'm Probably not -- forking rarely _is_ a good idea, except perhaps under extreme provocation. However, Python's conservatism might feel like such (extreme provocation) to somebody who's truly gung-ho for change. > quite happy with what it is now. I don't insist on introducing the switch > statement and conditional expression in 3.0. But I forget a colon for > each 'else' and I feel that I'm not the only one. Yep -- as for me, I kept doing that continuously for the first (roughly) three months of intense Python use, still a lot (just a bit less) over the _next_ three months, and even though the frequency's been going down it's mainly thanks to smart-editors which immediately show, typically by not auto-formatting things as I expect, that I have _again_ forgotten. However, I do like the colons there when I _read_ Python code, which, all in all, I do far more often than writing it; so, the slight inconvenience in writing is (for me, and by now) balanced out by the convenience in reading. You may want to investigate "smart editors" to see if the balance can be made similarly acceptable to you. Alex From noahd at juno.nospam.com Fri Nov 7 22:02:32 2003 From: noahd at juno.nospam.com (Noah) Date: Sat, 08 Nov 2003 03:02:32 GMT Subject: IPv6 Python on Windows Message-ID: <12bbfc1ac0eb74a6bd9369884ad9afc8@news.bubbanews.com> Are there any precompiled Windows binaries with IPv6 support available? -Noah From jkrepsBEAR at FISHneb.rr.com Wed Nov 12 17:57:16 2003 From: jkrepsBEAR at FISHneb.rr.com (GrayGeek) Date: Wed, 12 Nov 2003 22:57:16 GMT Subject: ANN: ruleCore - The event pattern detector engine References: <438a319a.0311091143.256db982@posting.google.com> <1Q5sb.23278$M02.14529@twister.rdc-kc.rr.com> <438a319a.0311112313.22df2a95@posting.google.com> Message-ID: Marco wrote: > Yes, I can imagine that there are lots of events in an industrial > process control setup. I suppose all these events could be fed into > ruleCore and there it could detect all kinds of interesting patterns of > events that should be reacted to. > > I didn't understand much of the ladder, but it seems to be some kind of > tool for event correlation just as ruleCore is. Most industrial process controllers come with a software/hardware modeling tool that uses the IEC 1131-3 language. Once you get the model working (using Ladder, for instance) you can then burn the software that the Ladder generates into the control EPROM. -- - GrayGeek From gerrit at nl.linux.org Thu Nov 13 14:52:48 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 13 Nov 2003 20:52:48 +0100 Subject: HELLO everybody! In-Reply-To: <20031113134210.GA20327@doctor.nl2k.ab.ca> References: <003001c3a9c1$92eeed60$35c8c8c8@mcgsdev1.com> <20031113134210.GA20327@doctor.nl2k.ab.ca> Message-ID: <20031113195248.GA5646@nl.linux.org> The Doctor wrote: > On Thu, Nov 13, 2003 at 04:38:46PM +0800, ?????? wrote: > > I am newbie for python. > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > Please note that this message is not viewed by anti-spam software > as friendly It is here: X-Spambayes-Classification: ham; 0.14 ...although 0.14 points is indeed a lot yours, Gerrit. -- 49. If any one take money from a merchant, and give the merchant a field tillable for corn or sesame and order him to plant corn or sesame in the field, and to harvest the crop; if the cultivator plant corn or sesame in the field, at the harvest the corn or sesame that is in the field shall belong to the owner of the field and he shall pay corn as rent, for the money he received from the merchant, and the livelihood of the cultivator shall he give to the merchant. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From mis6 at pitt.edu Thu Nov 13 08:41:19 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 13 Nov 2003 05:41:19 -0800 Subject: Metaclass' __init__ Does not Initialize References: Message-ID: <2259b0e2.0311130541.2d7a52a3@posting.google.com> "achan" wrote in message news:... > And for those who are puzzled why I insist on using __slots__, I'm using it > to reduce errors and not for saving space, wink! To reduce errors ?? It is possible that you want to forbid overriding attributes by using __slots__: this is exactly the WRONG way to use __slots__. See this thread (Classes in Python) for a discussion and a solution without using __slots__: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=2259b0e2.0304181308.316737a4%40posting.google.com&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DISO-8859-1%26q%3Dsimionato%2Bfrozen%26btnG%3DGoogle%2BSearch If I misunderstood you, pardon me; still. that thread make a good reading for everybody, so I posted the reference for the sake of other posters too ;) Michele Simionato From aleax at aleax.it Tue Nov 4 10:35:47 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 04 Nov 2003 15:35:47 GMT Subject: Sorting out which exceptions to handle References: <3fa70fe4$0$1740$5a62ac22@freenews.iinet.net.au> Message-ID: Derek Fountain wrote: > I recently asked a question about the exceptions raised by the MySQLdb > module. The answer produced a new question. :o) The documentation I was > pointed at tells me the module has the following exception tree: > > StandardError > |__Warning > |__Error > |__InterfaceError > |__DatabaseError > |__DataError > |__OperationalError > |__IntegrityError > |__InternalError > |__ProgrammingError > |__NotSupportedError ... > The O'Reilly Python in a Nutshell book says "Generally your code uses a > statement of the form: > > try: > ... > except module.Error, err: > ... > " Well, yes, generally. Not _invariably_, else I would have written that;-). > with the word "module" in italics. I tried the line: > > except MySQLdb.Error, err: > > and various variations, but always got errors. What errors? this seems exactly correct (save that you won't catch *warnings*) according to the above hierarchy. If you also need to catch warnings together with errors, except MySQLdb.StandardError, err: should be satisfactory. Alex From seqxob at deflifa.org Thu Nov 6 19:08:05 2003 From: seqxob at deflifa.org (Ali Al Queda) Date: Fri, 7 Nov 2003 00:08:05 GMT Subject: rethink the cool References: <9b07f16a.21588a24@news.yculvazo.com> Message-ID: <2bee3948.e1e96c78@news.zagvune.org> On 7 Nov 2003 00:08:05 GMT, Wayne at kedxije.org wrote: > >Rethink the Cool + the Shoe > >phil knight had a dream. he'd sell shoes. he'd sell dreams. >he'd get rich. he'd use sweatshops if he had to. > >then along came a new shoe. plain. simple. cheap. fair. >designed for only one thing: kicking phil's ass. > >the unswoosher > >$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ > >For years, Nike was the undisputed champion of logo culture, >its swoosh an instant symbol of global cool. > >Today, Phil Knight's Nike is a fading empire, badly hurt by >years of "brand damage" as activists and culture jammers >fought back against mindfuck marketing and dirty sweatshop labor. > >Now a final challenge. We take on Phil at his own game - and win. >We turn the shoes we wear into a counterbranding game. The swoosh >versus the anti-swoosh. Which side are you on? > >Adbusters has been doing R&D for more than a year, and guess what? >Making a shoe - a good shoe - isn't exactly rocket science. >With a network of supporters, we're getting ready to launch the >blackSpot sneaker, the world's first grassroots anti-brand. >You can help launch the blackSpot revolution. > >THE BIG QUESTION: > > Is it possible to take Phil Knight's billion-dollar > marketing momentum and, in a quick judo-like move, slap > him onto the mat with the power of his own PR thrust? > >OUR KICK-ASS MARKETING STRATEGY >> http://blackspotsneaker.org > >$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ > >buy it............................preorders at blackspotsneaker.org > >sell it...........................wholesale at blackspotsneaker.org > >invest in it......................investors at blackspotsneaker.org > >support it........................donations at blackspotsneaker.org > >join the jam........................jammers at blackspotsneaker.org > > Make a straight donation... it's a worthy cause > with the potential to set an historic precedent > that could be repeated in other industries and > usher in more grass roots version of capitalism > in which megacorps do not control every area of > our children's lives. > >https://www.groundspring.org/donate/index.cfm?ID=2217-0%7C742-0 > >$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ > The ball above the proud drawer is the puddle that hates seemingly. If the rural cars can climb stupidly, the short film may taste more markets. If you'll smell Laura's stadium with yogis, it'll familiarly hate the unit. Until Ibrahim irritates the butchers fully, Pervis won't tease any shallow shores. Well, bandages shout over cold sunshines, unless they're strange. -- Ali Al Queda of boundaries and ethics try to control minds and events on the street. Such people have lived with people on the street for years, so each time things go wrong, ordinary people who only relate to environment based on assumptions will hear and believe what everyone else around them does. So if Iraq war goes ahead, and a few innocent people die, those who share values with people of Iraq will definitely see it as murder thus creating one more gap in our relationship, where as bad guys will use this situation to create more people. I remember that Abu Omar during Afghan war used to tell us in the mosque that Jews and Christians are out there to kill us, and seeing the events these statements had confused me a lot, and if I after all my intelligence and education can be confused I am sure ordinary people can be too. If bad guys have plan to attack anywhere in the world tomorrow, you might be able to stop it but it would only be a short term fix there is in fact no short term solution, the long term and properly solution to this problem is firstly realising what and where we all have gone wrong, believing in being honest, just, unbiased, unconditionally caring and truthful before anything else. Accepting what we did not do right in past and getting better, thus showing the peo From peter at engcorp.com Fri Nov 21 12:17:33 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Nov 2003 12:17:33 -0500 Subject: what do you use python for? References: Message-ID: <3FBE48AD.1CC48865@engcorp.com> Jason Tesser wrote: > > I work for a Bible College of about 1000 people and we are going to be developing a complete software > package for the college. We are looking at using Python with PostgreSQL in the backend. We want to > have applications that are cross-platform and in the future could easily be ported to other OSs like Linux as > our desktops are all M$. > > Ok my question is are any of you doing this kind of stuff in Python and what do > you think about our project? Our project will include everything from registration stuff to busness office to > POS system. > > Thank you in advance for any feedback :-) It sounds like an *excellent* use for Python, and I'd wholeheartedly support it for your application. I would caution you about the scope of what you are attempting, however, as I've seen people (and organizations the size of yours) take on such projects time and again and, eventually, fail to produce much of anything that was really usable. My constructive advice about that area would be to investigate some of the Extreme Programming ideas, as they are very effective at helping you see scope-creep and understand how to deliver the really useful parts to your users very quickly, and gather feedback on what the real priorities are. (Too many developers spend too little time helping their customers understand why they don't really want what they think they want, and too many customers spend too little time insisting that they really do what certain things, but that other things are just icing on the cake and they could do without.) As for Python itself: you might want to take a little trip east to Church Street in T.O. this coming Tuesday, for the regular monthly meeting of PyGTA. This is the Greater Toronto Area Python user group, and it usually gets pretty good attendance from between ten and twenty people with a variety of Python and programming backgrounds, and there would definitely be people there to offer advice, stories, and perhaps even assistance on your project. See the URL http://www.engcorp.com/pygta for the main page and be sure to click on the NextMeeting link that you'll find there. There's also a mailing list for general discussion (you could ask questions there about local help if you can't make it to the meeting) and for meeting announcements. -Peter From newsgroups at jhrothjr.com Thu Nov 20 21:20:14 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 20 Nov 2003 21:20:14 -0500 Subject: Details on exceptions References: <3fbd7509$0$1749$5a62ac22@freenews.iinet.net.au> Message-ID: "Derek Fountain" wrote in message news:3fbd7509$0$1749$5a62ac22 at freenews.iinet.net.au... > Are the details of the builtin exceptions laid out anywhere? I was looking > though the O'Reilly Nutshell book, which informs me that errors with file > objects raise the builtin exception IOError. However, it doesn't describe > this exception in the same way it describes, for example, the OSError > exception. How do I get the actual error code from IOError of what went > wrong? > > I did a search on the Python docs, and couldn't find the information either. > So either the information is well hidden for some reason, or I've missed > some very important information on the standardisation of exception > handling techniques. Library Reference, Built-in Exceptions will tell you everything you want to know. John Roth From Pierre-et-Liliane.DENIS at village.uunet.be Tue Nov 18 15:53:55 2003 From: Pierre-et-Liliane.DENIS at village.uunet.be (Pierre Denis) Date: Tue, 18 Nov 2003 21:53:55 +0100 Subject: question about precision of arithmetic involving empirical, measured quantities Re: Unum 4.0 beta References: <3fb7dbfd$0$241$4d4efb8e@news.be.uu.net> Message-ID: <3fba8738$0$239$4d4efb8e@news.be.uu.net> This issue of approximate quantities, as you describe it, is not addressed by Unum. I fully agree that this is an important, under-estimated -or even ignored- problem. I think it is not, in essence, a problem specific to quantities or units; it happens for any operation on any numbers (or other mathematical entities) with uncertainties, for instance if you square PI, approximated in a floating-point variable. Unum focus on unit consistency, not on uncertainty calculation or error propagation, which deserves deeper mathematical analysis. Of course, your example is disturbing. Actually, I am not sure about what should be the most sensible answer. I have the feeling that it is neither 100 [m2] nor 101 [m2]. It firstly depends on how you model the error probability distribution. Is it a uniform distribution from 9 [m] to 11 [m] or, most likely, a Gaussian function centered on 10 [m] ? Even, if you take the simpler uniform distribution, the problem is not obvious : if you represent your possible input values on two-axis system, the 'input space' is a square (9[m],9[m])-> (11[m],11[m]), with each point representing equiprobable input value couple (x,y). Then each possible solution S, from 81 [m2] to 121 [m2], corresponds to a hyporbola curve having the equation x.y = S. From here, I think the most sensible result S? should be the one such that there is 50% of the input points x.y > S? and 50 % such that x.y < S? (strict equality is negligible for continouous variables). This requires some integral calculation and I don't dare to go further here... I presume that mathematicians have already calculate the answer to this. In any case, in this specific case, the uncertainty of the results decreases as the uncertainties of the input decrease. Such 'numerical stablity' is assumed (maybe wrongly) in most calculations so people usually do not care. Pierre John Benson a ?crit dans le message : mailman.806.1069094367.702.python-list at python.org... > Will this package handle approximate quantities, too? > > Here's some background for the question: > > Let's say you have measured the side of a square area to be 10 meters, +/- 1 > meter. We want to compute the area of the square. > > We are squaring a range of 9 to 11 meters, and get a resulting area range of > 81 to 121 square meters. If we take the midpoint of this range as the most > representative value, we end up with (81 + 121)/2 or 101 square meters, > plus-or-minus 20 square meters! I seem to recall some rule that in a > multiplication, the total uncertainty is the sum of the quotients > (multiplicand/uncertainty of multiplicand) over all multiplicands. By this > rule, the total uncertainty then would compute as (10/1) * (10/1) or twenty > square meters, as we reckoned by explicit range calculation. But what about > the discrepancy between 100 and 101? > > Whenever arithmetic is done involving things like volts and m/sec (as > opposed to apples, bananas and people), you necessarily end up with problems > like this. However, I got through a few years of college physics and > chemistry without anyone ever worrying about the real uncertainties, beyond > the simple "significant figures" approach for multiplication and the > comparative precision approach for addition. > > ----- Original Message ----- > From: "Pierre Denis" > To: > Sent: Sunday, November 16, 2003 12:18 PM > Subject: ANN: Unum 4.0 beta > > > > Unum 4.0 beta is now available on > http://home.tiscali.be/be052320/Unum.html. > > > > This Python module allows you to work with units like volts, hours, > meter-per-second or dollars-per-spam. So you can play with true > > quantities (called 'unums') instead of simple numbers. Consistency between > units is checked at each expression evaluation and an > > exception is raised when something is wrong, for instance, when trying to > add apples to bananas. Unit conversion and unit output > > formatting are performed automatically when needed. The main goals are to > avoid unit errors in your calculations and to make unit > > output formatting easy and uniform. > > > > This new version encompasses all the SI units and allows you to define > your own libraries of units, with specific names and symbols. > > Other improvements makes this version more solid : compatibility with > NumPy, packages, misc optimizations, true exceptions, > > new-style class, static methods, etc. The installation also should be > easier and more standard through installation files. The site > > and tutorial page have been updated to give more accurate information. > > > > This 4.0-beta version is stable, fairly. The term 'beta' essentially means > that problems may potentially occur at installation on > > specific OS. I made successful installation tests on Windows 98, XP and > Red Hat Linux 7.2. Besides this, the choices I made for unit > > names and symbols are subject to change if I receive more sensible > suggestions. Of course, any other ideas, comments or criticisms > > are welcome before releasing the official Unum 4.0 (no planning yet). > > > > This version requires Python 2.2 (at least). > > > > The license is GPL. > > > > Thanks for your interest, > > > > Pierre Denis > > > > > > > > > > > > > > > From frobozz_electric at hotmail.com Mon Nov 10 23:43:01 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 11 Nov 2003 04:43:01 GMT Subject: What do you think of this Python logo? References: <3FB00D3B.2BCE081A@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3FB00D3B.2BCE081A at engcorp.com... > "Brandon J. Van Every" wrote: > > > > What do you think of this Python logo? > > http://pythonology.org/logos > > Good, bad, indifferent, love it, hate it? > > Pretty slick, although at least the larger version look a lot like > an egg being impregnated by a sperm... > > Has potential though. What about minus the planet? > > -Peter I don't mind the snake, but I would lose the planet ("Python is taking over the world!" ... ahem ... right ... ok, then ...), and perhaps add eyes, so it looks less like sperm. I would also probably move the snake logo into the text to replace the 'O' in Python. (I think I saw an early version of this where that was done). It's odd - sure, it's a coiled snake beside the word "Python" but, for some reason, they don't really seem to have anything to do with one another. At least, not to me. Anyway. If I could draw, I would probably try to make the snake in the shape of the letter "P" - something like this http://chat.carleton.ca/~sross/py.JPG (only not drawn with a mouse in MSPAINT, like this was :). Kind of a cross between "GAP" and the Portishead logo - um, but with a snake. Slick it up a bit and it might make a good T-Shirt ... or, not ... OK, so, good luck with whatever it is you're doing, Sean p.s. The logo at python.com (yeah, _that_ python.com) with the green, bared-fang snake, and the electrified "Powered by Python" is pretty cool (though not really corporate, which is what it looks like you're after). Too bad it's on a porn site ... From mcrider at bigfoot.com Sat Nov 1 15:30:10 2003 From: mcrider at bigfoot.com (2mc) Date: 1 Nov 2003 12:30:10 -0800 Subject: Array and COM object interfacing Message-ID: <500a4565.0311011230.6ff010a7@posting.google.com> All, I'm getting a better handle on Python and NumPy. I've found solutions to many of my questions. Thanks to all. I would like to interface Python (in WinXP) with another program through the COM object. This other program downloads data for me on a daily basis. I have a choice of many methods to export the data from this program - the fastest of which is through the COM object. One of the methods of this other program is a function called "CopyRetrievedDataToArray." It will let me talk to the program and pull info out into an array. Is this something Python can do? Can someone point to documentation for interfacing through API? Thanks. Matt From max at alcyone.com Mon Nov 3 15:39:16 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 03 Nov 2003 12:39:16 -0800 Subject: Selling Python Software References: <8765i1d2jb.fsf@pobox.com> Message-ID: <3FA6BCF4.9BC51DF@alcyone.com> "John J. Lee" wrote: > Whie this is all true, you seem to put undue emphasis on the fact that > it's always *possible* to decompile stuff. Isn't the point you make > in your last sentence actually crucial here? The game is to make your > opponent (customer ;-) incur more expense in decompiling it than it > would cost to just go ahead and pay you, is it not? And yeah, you > also have to take into account how much it costs you to come up with > the protection scheme, of course. The problem here is that it is almost certain that the efforts of dedicated crackers will be far greater than anything you can come up with. If someone really wants to crack your program, they will be able to do so, and there's not much you can do to stop them. Furthermore, in some senses the monetary analogy, though useful, is flawed. There are plenty of crackers who simply _will not pay you_ no matter what happens, even if they fail to compromise your copy protection scheme. And, if they fail, they may pass it on to friends who are more experience than they are, and the fruits of that labor will be shared among the cracker community. In essence the battle isn't one against many -- you vs. an individual cracker -- it's one against many -- you vs. an entire community of crackers -- and you're hopelessly outnumbered. Any amount of effort you're willing to spend to come up with a sophisticated copy protection scheme can be easily matched by a group of crackers if they so desire. Of course this brings up issues of how widely distributed and appealing your application is, but the bottom line here is that this is a battle you cannot win -- you simply hope you to avoid the fight in the first place. Most copy protection schemes these days, such as they are, are intended to discourage casual violations. Things like requiring a serial number or the right CD in the drive are usually considered fairly good common ground solutions, because they're well-known territory and the average customer won't be put off too much by them. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Exercise is wonderful. I could sit and watch it all day. \__/ Louis Wu From alan.gauld at btinternet.com Wed Nov 5 17:39:10 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 05 Nov 2003 22:39:10 GMT Subject: Advanced OOP tutorial References: Message-ID: <3fa979f3.86889770@news.blueyonder.co.uk> On 4 Nov 2003 10:33:34 -0800, iscaris at hotmail.com (Fernando) wrote: > Is there any advanced OOP tutorial that cover metaclass programming? You've been given some Python specific material. Other sources on metaclasses in general can be found at the portal for all thinks OO at http://www.cetus-links.org/ Also in the excellent OO FAQ, look under Basics at sections 1.4 and 1.6. http://www.objectfaq.com/ Also most Smalltalk tutors have a section on metaclasses and their use - a very common technique in Smalltalk... And finally there is the hard to find but excellent Metaclass book by Forman & Danforth. HTH, Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From hungjunglu at yahoo.com Sat Nov 22 15:15:37 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 22 Nov 2003 12:15:37 -0800 Subject: code blocks in Python Message-ID: <8ef9bea6.0311221215.804bdb3@posting.google.com> Hi, I know people have talked about it before, but I am still really confused from reading the old messages. When I talk about code blocks, I am not talking about Lisp/Ruby/Perl, so I am not making comparisons. If you have a file, in Python you could do: code = compile(code_string, 'FileName.py', 'exec') and obtain a code object, which later on you can execute. That's the kind of code block I have in mind. That is, no parameters, no specification of scopes, no nothing else. Just a plain block of code lines compiled into a code object. It's not too much work to write a code string like: my_codeblock = ''' x = x + 1 y = y + 2 ''' and then use compile() to turn it into a code object. But it seems to me that Python could perfectly allow this syntax directly into the language, something like: codeblock my_codeblock: x = x + 1 y = y + 2 so that users won't need to explicitly call the compile() function. The advantage is that the codeblock is compiled at compile time, not at run time, even if the codeblock is defined inside something else (a class, a function, etc.) Is there something obvious that I am missing here? Why isn't codeblock part of the language? It seems to be an important building element for meta-programming. Not only that, it seems to be much more fundamental than functions. So, why isn't it part of Python? Any intrinsic difficulties? regards, Hung Jung From peter at engcorp.com Sat Nov 1 21:02:52 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 01 Nov 2003 21:02:52 -0500 Subject: operator.isMappingType References: Message-ID: <3FA465CC.8F11293D@engcorp.com> John Roth wrote: > > "Raymond Hettinger" wrote in message > news:vgYob.46447$4O1.17443 at nwrdny01.gnilink.net... > > Since the advent of extended slicing, operator.isMappingType() returns a > > misleading result. > > > > >>> map(operator.isMappingType, ([], (), {}, '', u'')) > > [True, True, True, True, True] > > > > > > I recommend removing it from the operator module. > > I get the following on 2.2.3: > > >>> map (operator.isMappingType,([], {}, (), ", u")) > [0, 1, 0, 0] > > Where did the fifth True come from? That's really odd! Raymond used pairs of single quotes, while you used only individual double-quotes surrounding a string containing a comma, a space, and the letter u. His had an empty string and an empty unicode string... -Peter From aa at bb.cc Mon Nov 10 06:48:48 2003 From: aa at bb.cc (Ladvánszky Károly) Date: Mon, 10 Nov 2003 11:48:48 GMT Subject: simple float numbers problem References: Message-ID: Lisp does the right thing: (= (+ 10 15.99) 25.99) T Does Lisp not use the math processor? "Vio" az al?bbiakat ?rta a k?vetkezo h?r?zenetben: mailman.548.1068222897.702.python-list at python.org... > I need to test for equality between simple 2 decimal numbers. For example: > > if (10 + 15.99) == 25.99: > do some stuff... > > The preceding sentence should be TRUE, but to Python it appears FALSE. > Which is wrong. > > Perhaps because Python translates "25.99" to "25.98999999999999998" and > not "25.99", which may be the reason for this error (me guessing...). If > that's the case, how do I force Python to only use 2 decimal points, and > not "make up" superfluous decimals? Or if that's not the cause for the > problem, how do I make Python see my math expression as TRUE (as it > "should" be)? > > Cheers, > Vio > > PS. If it's of any help, I'm using Python2.3 (GCC 2.95.4 20011002 > (Debian prerelease)) > > > From email9898989 at yahoo.com Tue Nov 4 22:37:46 2003 From: email9898989 at yahoo.com (email9898989 at yahoo.com) Date: 4 Nov 2003 19:37:46 -0800 Subject: Pygame and TKinter References: Message-ID: Lane LiaBraaten wrote in message news:... > Does anyone know a way to insert a pygame surface into a tkinter gui? > I am writing a program similar to a mpeg player, i.e. i need the mpeg pla > ying > capabilities of pygame and the gui stuff from tkinter. See this page for how to do that in WxPython: http://wiki.wxpython.org/index.cgi/IntegratingPyGame To translate that code to Tkinter, you would use frame.winfo_id() to get the window handle instead of wxpython's GetHandle(). But these are both basically just hacks. Options for multimedia playing/editing are slim in python. You might use Java instead (see jython), using either the java media framework or quicktime for java (latter doesn't work on Linux). From http Wed Nov 19 16:38:50 2003 From: http (Paul Rubin) Date: 19 Nov 2003 13:38:50 -0800 Subject: Parsing HTTP messages References: Message-ID: <7x65hgdonp.fsf@ruckus.brouhaha.com> Chris Gray writes: > My initial question is, what Python library do I use to parse HTTP > messages? httplib From aleax at aleax.it Thu Nov 13 09:18:13 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 13 Nov 2003 14:18:13 GMT Subject: True inconsistency in Python References: <2i86rvk6v0gmqhgur5h61qmmlfdm1n3p0t@4ax.com> Message-ID: Ben Finney wrote: ... > This conflation of types is confusing, and (like many other languages) > Python has now "grown a Boolean type" to distinguish integer 0 and 1 > from Boolean False and True. However, the previous behaviour is still > supported -- for how long, I don't know. I've never heard of any plans (not even for the totally mythical "Python 3000") to remove or even deprecate Python's extremely useful and practical feature that: -- any value can be used as a true-or-false condition, -- zero numbers, empty containers, and user-coded objects defining __nonzero__ (or else __len__) and returning 0 are taken as false, -- all other values are taken as true. Alex From cbrown at metservice.com Mon Nov 3 16:35:50 2003 From: cbrown at metservice.com (Colin Brown) Date: Tue, 4 Nov 2003 10:35:50 +1300 Subject: Nested dictionary cleanup References: <3fa6c327$1@news.iconz.co.nz> Message-ID: <3fa6c957$1@news.iconz.co.nz> OOPS! Coding slip I'm afraid, sorry. I was thinking that the code was failing because keys() were being evaluated dynamically. I then tried to think how to queue the deletes to be done after the loop but could not figure out how to do this. Colin "Colin Brown" wrote in message news:3fa6c327$1 at news.iconz.co.nz... > My code fragment below: > > for key1 in dict1.keys(): > for key2 in dict1[key1]: > if dict1[key1][key2] == None: > del dict1[key1][key2] > > gives the following error: > RuntimeError: dictionary changed size during iteration > > Any suggestion on how to code this please. > > Thanks > Colin Brown > PyNZ > > > From mikit at zoran.co.il Thu Nov 27 11:17:05 2003 From: mikit at zoran.co.il (Miki Tebeka) Date: 27 Nov 2003 08:17:05 -0800 Subject: Newbie: wxPython GUI Help - Simple Login System References: Message-ID: <6250403b.0311270817.294b9e1a@posting.google.com> Hello Trinity, > However, I cannot work out how to read from > an edit box, or a user input box. For instance: If you mean TextControl then ctrl.GetValue() Have a look at the demo directory. HTH. Miki From mhammond at skippinet.com.au Thu Nov 13 16:46:47 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 14 Nov 2003 08:46:47 +1100 Subject: STrange error importing win32gui In-Reply-To: <3fb3b3de.136821542@news.cybermesa.com> References: <3fb27d5f.57321764@news.cybermesa.com> <87fzgtfm8c.fsf@pobox.com> <8360efcd.0311130042.60b25835@posting.google.com> <3fb3b3de.136821542@news.cybermesa.com> Message-ID: Jay O'Connor wrote: > On 13 Nov 2003 00:42:06 -0800, tim.golden at viacom-outdoor.co.uk (Tim > Golden) wrote: > > >>jjl at pobox.com (John J. Lee) wrote in message news:<87fzgtfm8c.fsf at pobox.com>... >> >>>joconnor at cybermesa.com (Jay O'Connor) writes: >>> >>> >>>>I'm using Python 2.3 on windows and trying to use the win32 libs. I >>>>keep getting the following error >>>> >>>> >>>>>>>import win32gui >>>> >>>>Traceback (most recent call last): >>>> File "", line 1, in -toplevel- >>>> import win32gui >>>>ImportError: DLL load failed: A device attached to the system is not >>>>functioning. >>>> >>>>I'm not sure what it means ot how to fix it. Any thoughts? >>> >>>Don't you just love those informative Windows error messages? >>> >>>I had that error message before (can't remember the circumstances), >>>and never found out what the problem was. Had to work around it >>>rather than fix it. >>> >>> >>>John >> >>When I've had these errors, it's usually indicated >>that -- at some point -- one of my network drives >>has gone down, especially but not limited to the >>one I'm hosting my python-site-packages directory >>on. Forcing a reconnection to the drive >>(ie net use /del followed by net use) seems to solve it, >>even if the drive is by now up and running again. > > > This is a standalone PC with only a dialup modem for connectivity. > It's an old Win95 machine. > > Basically I want to do GUI progrmaming in Python on windows to expand > my offerings as a programmer. I thuoght the win32 api would be good > but I'm also considering wxPython now (I really don't like Tkinter) > > FWIW - I'm an unemployed software developer who likes programming in > Python and Smalltalk if anyone needs a warm body. I'm afraid that win32all no longer supports Win95 - that is the cause of the error. Windows 98 or better works. I realize this sucks, but at some stage I have to let go - and if it is good enough for MS to call 95 "unsupported", it is good enough for me Mark. From aleax at aleax.it Tue Nov 4 12:09:31 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 04 Nov 2003 17:09:31 GMT Subject: variable assignment within a loop References: Message-ID: Michael Surette wrote: > On Mon, 03 Nov 2003 15:37:28 -0500, hokieghal99 wrote: > >> I have this for loop in a program that I'm writing: >> >> for bad_dir_char in bad_dir_chars: >> newdir = dir.replace(bad_dir_char,'-') ... >> I get a "local variable 'newdir' referenced before assignment" error. > > This has nothing to do with where variables live. What is happening is > when bad_dir_chars is empty, newdir doesn't get assigned in your for loop. Right -- and when bad_dir_chars has more than one character, all but the last one are basically ignored (they ARE used to laboriously compute many versions of newdir, but all versions except the last one are thrown away). Do, instead: import string transbad = string.maketrans(bad_dir_chars, '-'*len(bad_dir_chars)) newdir = dir.translate(transbad) this no doubt has the effect you were looking for... Alex From theller at python.net Thu Nov 27 03:03:04 2003 From: theller at python.net (Thomas Heller) Date: Thu, 27 Nov 2003 09:03:04 +0100 Subject: Problem with py2exe-frozen CGIHttpServer-based script References: Message-ID: "vincent wehren" writes: > Hi, > > as a small capabilities demo I coded the piece below to show how to use > Python for cgi'ing on localhost and it more or less does the trick :-). > However, I when I freeze it with py2exe, starting the resulting exe fires up > the server allright, > but fails execute cgi commands correctly (i.e. the expected output - let's > say from cgi.test()) - is no longer emitted to the browser...). > > Is there some py2exe-magic I need to do that I don't know of? Something in > the code that prevents the frozen version to work? That's an easy one! Look into CGIHTTPServer.py, near line 232: if self.is_python(scriptfile): => interp = sys.executable if interp.lower().endswith("w.exe"): # On Windows, use python.exe, not pythonw.exe interp = interp[:-5] + interp[-4:] cmdline = "%s -u %s" % (interp, cmdline) It tries to start 'sys.executable' with the python cgi script. Normally sys.executable is the Python interpreter, but for a py2exe'd script this is the running executable (which is no longer a usual Python interpreter). Changing this line to 'interp = r"c:\python23\python.exe"' makes the frozen script work (although then the Python installation is required again). (A few minutes later, looking at CGIHTTPServer.py again) It seems you have to hack this module so that the code block starting at line 270 is used, which says: else: # Other O.S. -- execute script in this process and then it works fine. Thomas From alan.gauld at btinternet.com Thu Nov 27 03:24:23 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 27 Nov 2003 08:24:23 GMT Subject: a newbie References: Message-ID: <3fc5b43e.314294701@news.blueyonder.co.uk> On Thu, 27 Nov 2003 03:30:28 -0000, "william_k_edwards2000" wrote: > I am new to python.I have familiarized myself with Python through Doc. > and, simple code.My question is really about pygame.Which is somthing > I am very unfamiliar with. I think there is a pygame mailing list, it is probably worth joining that. Also as a beginner its worth joining the python tutor mailing list where you will find lots of other beginners asking questions, some of them about pygame too. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From aleaxit at yahoo.com Fri Nov 7 02:18:04 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 07 Nov 2003 07:18:04 GMT Subject: QUESTION ABOUT PYTHON References: Message-ID: MAJED ASSAF wrote: > hello There > Please I need help !! I don't know why my command prompt won't change to > python even if I set the path it stays like the following Microsoft > Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. > > C:\Documents and Settings\Owner> it won't change it stays on the document > and settings The PATH determines where program are looked for, it does not run them automatically. So, at that command prompt, you need to enter the command python followed by hitting the Enter key, and THAT will give you a Python interpreter prompt if you have your PATH set right. Alternatively, \python23\python will work no matter how your PATH is set, as long as you have a standard installation of Python 2.3 (which you should). Alex From larry_Goodman at yahoo.com Wed Nov 26 11:12:03 2003 From: larry_Goodman at yahoo.com (Larry goodman) Date: Wed, 26 Nov 2003 11:12:03 -0500 Subject: In a bit of a pickle here :) References: <5777svgdl2kchbvg8idbm8kdefoan88o9j@4ax.com> Message-ID: <93k9sv07tukjekft3uuqb258gleerh0tsm@4ax.com> >What kind of attributes do your objects have? If they point to each >other, or to common objects, then pickling and unpickling can lead to >all sorts of undesirable effects, and you might be better of using a >different solution. > Yeh im going to have a lot of pointing going on and it confuses me how I am going to pickle this all. I guess i'll have to store the object id instead of a reference in the pickle and restore the reference myself? >You might want to look at the following (some of which I have never >looked at myself): > >1. ZODB (object database of http://www.zope.org/ ) This is pretty close to what I need to do. thx From huzzah at tampabay.rr.com Sat Nov 1 08:27:51 2003 From: huzzah at tampabay.rr.com (Todd Stephens) Date: Sat, 01 Nov 2003 13:27:51 GMT Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> Message-ID: On Sat, 01 Nov 2003 05:57:46 -0500, Alex Martelli wrote: > I do sometimes get asked for advice about "an Access-like product that's > cross-platform" and the like, but I couldn't in good faith suggest > Rekall if I thought that could potentially send the purchaser into the > midst of a legal controversy. Sigh. I don't see much controversy here. If the work was done for theKompany, then it is a work made for hire, no? In that case, theKompany owns the rights to the software. -- Todd Stephens From mwh at python.net Wed Nov 5 08:31:19 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 5 Nov 2003 13:31:19 GMT Subject: Pickling Objects inherited from dict (Bug?) References: Message-ID: <7h365hzhrnb.fsf@pc150.maths.bris.ac.uk> "Thomas Guettler" writes: > Hi! > > After unpickling the objects are not the same > any more. Is this a bug or feature? There's a bug report up on SF that may be relavent, try searching (unfortunately I don't remember the details...). Cheers, mwh -- The use of COBOL cripples the mind; its teaching should, therefore, be regarded as a criminal offence. -- Edsger W. Dijkstra, SIGPLAN Notices, Volume 17, Number 5 From talon2lm at yahoo.com Sun Nov 9 18:26:47 2003 From: talon2lm at yahoo.com (Rob) Date: Sun, 9 Nov 2003 16:26:47 -0700 Subject: Newbie question 2 References: Message-ID: Gentlemen, Thanks so much..I do appreciate it. I'm finding that this newsgroup, its members, is a wealth of knowledge. My next assignment is to use the TKinter GUI stuff...so far, so good but I'm sure you'll be hearing more from me! Thanks, Rob "Rob" wrote in message news:Bf6dnT_Ctq5FCTCiRVn-hA at comcast.com... > Ok, my two problems for this program that I can't seem to get are... > > 1)Why won't the program let me delete an entry after just entering it? If I > run the program, add an entry then quit, then restart the program it will > let me delete it. Otherwise it won't see it...Am I missing something??? > > 2)In the dele function I'm trying to add exceptions. The problem is if I try > to delete an entry that doesn't exist it will give me this error: > > Traceback (most recent call last): > File "C:\Python23\phone.py", line 118, in -toplevel- > dele(dn,dp) > File "C:\Python23\phone.py", line 67, in dele > del e[str(f)] > File "C:\Python23\lib\shelve.py", line 133, in __delitem__ > del self.dict[key] > File "C:\Python23\lib\bsddb\__init__.py", line 94, in __delitem__ > del self.db[key] > DBNotFoundError: (-30991, 'DB_NOTFOUND: No matching key/data pair found') > > Ok great...so I try to add the DBNotFoundError in my Except() only it tells > me: > > Traceback (most recent call last): > File "C:\Python23\phone.py", line 118, in -toplevel- > dele(dn,dp) > File "C:\Python23\phone.py", line 70, in dele > except (DBNotFoundError, NameError): > NameError: global name 'DBNotFoundError' is not defined > > How can it give me an error and then not allow me to enter that error in my > Except()? > > Thanks for your help! > > > From alan.gauld at btinternet.com Sat Nov 8 03:58:36 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 08 Nov 2003 08:58:36 GMT Subject: Can I hook a "file" to a python script? References: Message-ID: <3facafb0.297290300@news.blueyonder.co.uk> On Fri, 7 Nov 2003 20:39:49 -0800, Scott Chapman wrote: > I know how to do the database end of this but I'm not sure if a script > can be hooked to a "file" transparently. The script would probably > have to be run as a daemon. I doubt there's enough magic in the Linux > world to make it so that a read/write would actually launch the script. This can be done - indeed its how the ClearCase config management tool works on *nix - but it involves some low level magic. I believe you need to swap out the read/write system calls. I don't pretend to know how you do that but it can be done. Whether you could do it in pure Python I doubt, but a C program that called Python maybe. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From aleax at aleax.it Mon Nov 17 05:07:11 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 17 Nov 2003 10:07:11 GMT Subject: PyQt, Qt, Windows and Linux References: Message-ID: Jim wrote: ... > Edition but I think you just told me the opposite. If I buy the Personal > Edition and use it to write my program, I won't have the capability to run > that software on any other computer besides my own (personal to me) ... > not even my wife's computer downstairs, i.e., so the runtime elements > don't come with the Personal Edition - which makes it functionally > different? I think the difference is legal (contractual), not technical: you do not have the _permission_ to copy runtime elements to other computers, even though you may have the physical ability to do so. > theKompany web page says the Business Edition is "for commercial use." > From my understanding, commercial means of or relating to commerce and > commerce is buying and selling products and I'm not selling anything. This Qt (all the way from Trolltech) is peculiar that way: if you want to distribute programs that run under Microsoft Windows, then you do need a commercial license (there are other variants such as the "academic" license, etc, but I don't think they apply here). Presumably the concept is that if people choose to pay for their operating systems, rather than supporting free ones, they may well pay for applications too. > is really confusing. I want to honor whatever licence I buy but it doesn't > seem reasonable that I would have to pay $400 so I can give my own program > away freely. If you develop your Qt/PyQt applications with eric3 and distribute them as free software (GPL) then you do not need to pay anybody anything. If you distribute applications otherwise than under GPL, or distribute applications that run on Windows, then you do need to pay (purchase an appropriate license -- unless your case can be covered by an academic license or the like, I guess, but I don't know the details of that). If you use Blackadder for the development, you can still give away your sources (they are and remain your property); you just can't give away executables and libraries that are not your property and that you are not licensed to redistribute (such as those that come with Blackadder's Personal edition/license). Somebody's trying to develop a GPL version of Qt that runs under Windows (with cygwin, specifically for the purpose of using KDE on cygwin); if that effort matures (I don't know about its current status), then at least C++-coded applications running on Windows+cygwin, covered by GPL, and freely distributed, would become possible. If and when this happens, then for Python-coded applications to be distributable on the same terms you will only need a suitable GPL-licensed PyQt (or PyQt with some license that is at least GPL-compatible, of course). Alex From alanmk at hotmail.com Fri Nov 14 06:26:51 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 14 Nov 2003 11:26:51 +0000 Subject: Palindrome References: <20031112223135.29045.00000109@mb-m12.aol.com> <3FB3C016.56BCA546@hotmail.com> Message-ID: <3FB4BBFB.65AE0B9A@hotmail.com> [Alan Kennedy] >> ... There must be some way to have a >> single fixed regular expression that can be used to test every >> palindrome. [Andrew Dalke] > There isn't such a way. Regular expressions cannot match > strings of the form a**n b**n a**n (pumping lemma). That's > a palindrome so there are palindromes which cannot be > matched by regular expressions. Thanks Andrew. I read up on the topic after posting yesterday (because I had this vague niggling doubt). After finding that what you stated above is true, I realised that the vague niggling doubt was actually the memory of my old compiler-theory lecturer laughing at me :-D Here's a nice page I found that discusses this and other related topics. FINITE STATE AUTOMATA AND REGULAR EXPRESSIONS http://www.cs.princeton.edu/introcs/71regular/ > There are tricks. "regular expressions" aren't actually regular > and can be used to match things like a**n b**m a**n (because > of the \1 feature). However, there still isn't enough to match > a palindrome of arbitrary length. (It would be trivial to add such > a feature -- let \~1 match the reverse of the first match then > ^(.*).?\~1$ > would match all palindromes... slowly. But no such feature > exists in any regexp engine I know of.) The possibility of the same feature occurred to me. However, I'm still not sure if this would solve the problem. How would the "pivot point" be recognised by such an augmented regex engine? i.e. how would it recognise the point at which it should stop capturing, reverse the sequence and start matching again? Perhaps one would need to also implement a feature whereby the length of the entire string could be made available within expressions, so that the size of a capture group could be limited to the first half of the string? I.E. Something along the lines of ^(.{strlen/2}).?\~1$ One of these days I'll find the time to dig out my old course notes and books :#) regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From scott_list at mischko.com Mon Nov 10 18:33:34 2003 From: scott_list at mischko.com (Scott Chapman) Date: Mon, 10 Nov 2003 15:33:34 -0800 Subject: What do you think of this Python logo? In-Reply-To: References: Message-ID: <200311101533.34256.scott_list@mischko.com> On Monday 10 November 2003 14:16, Brandon J. Van Every wrote: > What do you think of this Python logo? > http://pythonology.org/logos > Good, bad, indifferent, love it, hate it? I like it. I like the font. It shrinks well and is not obnoxious. Perhaps you could make the color gradient start at the left of the O and go all the way through the text, or others could in their private variations on the logo. Of course, the world would not be included in the gradient. Perhaps shading it greener (or dark green -> light green) would be more in keeping with historical Python logos? Where'd the earth picture come from? I don't think it's an actual satellite photo? I think it would be very cool and appropriate if it was a real satellite photo! Scott From logan at phreaker.nospam Tue Nov 25 21:38:39 2003 From: logan at phreaker.nospam (Logan) Date: Wed, 26 Nov 2003 03:38:39 +0100 Subject: wxPython - wx package (new style wxPython?) References: Message-ID: On Tue, 25 Nov 2003 19:20:08 -0500, James Tanis wrote: > BTW, In the future you may want to use a real email address > so that you can receive an answer. Thanks for your comments regarding my question. About the 'real email address': I do use a real address! You can find the address in the signatures of my postings; just remove the part saying '(NoSpam)'. I don't use the real address in the headers of my postings (but: logan at phreaker.nospam) because the last time (about a month ago) I used my real address, I got thousands and thousands of SPAM mails, viruses etc. per week. This was really annoying. -- mailto: logan at phreaker(NoSpam).net From nessus at mit.edu Wed Nov 26 17:55:29 2003 From: nessus at mit.edu (Douglas Alan) Date: Wed, 26 Nov 2003 17:55:29 -0500 Subject: Python's simplicity philosophy References: <3FAC19F0.284DCB03@alcyone.com> <%N8tb.28277$hV.1041253@news2.tin.it> Message-ID: Alex Martelli writes: >> That would have a larger big O time growth value -- most likely >> O(n * log n) vs. O(n), for reasonable implemenations. And while I > If the sequence is carefully randomized, yes. If the sequence has > any semblance of pre-existing order, the timsort is amazingly good > at exploiting it, so that in many real-world cases it DOES run as > O(N). C'mon -- to make robust programs you have to assume the worst-case scenario for your data, not the best case. I certainly don't want to write a program that runs quickly most of the time and then for opaque reasons slows to a crawl occasionally. I want it to either run quickly all of the time or run really slowly all of the time (so that I can then figure out what is wrong and fix it). >> wouldn't sweat a factor of 2 for a feature of a RAD or scripting >> language, I would be more concerned about moving to a larger big O >> value. > Me too! That's why I'd like to make SURE that some benighted soul > cannot code: > onebigstring = reduce(str.__add__, lotsofstrings) The idea of aiming a language at trying to prevent people from doing stupid things is just innane, if you ask me. It's not just inane, it's offensive to my concept of human ability and creativity. Let people make their mistakes, and then let them learn from them. Make a programming language to be a fluid and natural medium for expressing their concepts, not a straight-jacket for citing canon in the orthodox manner. Furthermore, by your argument, we have to get rid of loops, since an obvious way of appending strings is: result = "" for s in strings: result += s >> Your proposed extension to max() and min() has all the same problems. > Not at all. Maybe you have totally misunderstood "my proposed > extension"? You are correct, sorry -- I misunderstood your proposed extension. But max() and min() still have all the same problems as reduce(), and so does sum(), since the programmer can provide his own comparison and addition operations in a user-defined class, and therefore, he can make precisely the same mistakes and abuses with sum(), min(), and max() that he can with reduce(). >> But reasonable programmers don't abuse this generality, and so there > So, you're claiming that ALL people who were defending 'reduce' by > posting use cases which DID "abuse this generality" are > unreasonable? In this small regard, at least, yes. So, here reduce() has granted them the opportunity to learn from their mistakes and become better programmers. >> this urge to be stiffled. Don't take my word for it -- ask Paul >> Graham. I believe he was even invited to give the Keynote Address at >> a recent PyCon. > However, if you agree with Paul Graham's theories on language > design, you should be consistent, and use Lisp. I don't agree with *everything* that anyone says. But if there were a version of Lisp that were as tuned for scripting as Python is, as portable as Python is, came with as many batteries installed, and had anywhere near as large a user-base, I probably *would* be using Lisp. But there isn't, so I don't. And Python suits me fine. But if it continues to be bloated with a large number special-purpose features, rather than a small number of general and expressive features, there may come a time when Python will no longer suit me. > If you consider Python to be preferable, then there must be some > point on which you disagree with him. In my case, I would put > "simplicity vs generality" issues as the crux of my own > disagreements with Dr. Graham. Bloating the language with lots of special-purpose features does not match my idea of simplicity. To the extent that I have succeeded in this world, it has always been by understanding how to simplify things by moving to a more general model, meaning that I have to memorize and understand less. Memorizing lots of detail is not something I am particurly good at, and is one of the reasons why I dislike Perl so much. Who can remember all that stuff in Perl? Certainly not I. I suppose some people can, but this is why *I* prefer Python -- there is much less to remember. Apparently you would have it so that for every common task you might want to do there is one "right" way to do it that you have to remember, and the language is packed to the brim with special features to support each of these common tasks. That's not simple! That's a nightmare of memorizing special cases, and if that were the future of Python, then that future would be little better than Perl. >> Just what is it that I don't grasp again? I think my position is >> clear: I have no intention to abuse reduce(), so I don't worry myself >> with ways in which I might be tempted to. > Yet you want reduce to keep accepting ANY callable that takes two > arguments as its first argument, differently from APL's / (which does > NOT accept arbitrary functions on its left); That's because I believe that there should be little distinction between features built into the language and the features that users can add to it themselves. This is one of the primary benefits of object-oriented languages -- they allow the user to add new data types that are as facile to use as the built-in data types. > and you claimed that reduce could be removed if add, mul, etc, would > accept arbitrary numbers of arguments. This set of stances is not > self-consistent. Either solution is fine with me. I just don't think that addition should be placed on a pedestal above other operations. This means that you have to remember that addition is different from all the other operations, and then when you want to multiply a bunch of numbers together, or xor them together, for example, you use a different idiom, and if you haven't remembered that addition has been placed on this pedestal, you become frustrated when you can't find the equivalent of sum() for multiplication or xor in the manual. >> So, now you *do* want multiple obviously right ways to do the same >> thing? > sum(sequence) is the obviously right way to sum the numbers that are > the items of sequence. If that maps to add.reduce(sequence), no problem; > nobody in their right mind would claim the latter as "the one obvious > way", exactly because it IS quite un-obvious. It's quite obvious to me. As is a loop. > The point is that the primary meaning of "reduce" is "diminish", and > when you're summing (positive:-) numbers you are not diminishing > anything whatsoever Of course you are: You are reducing a bunch of numbers down to one number. >> "summary" or "gist" in addition to addition. It also can be confusing >> by appearing to be just a synonym for "add". Now people might have >> trouble remember what the difference between sum() and add() is. > Got any relevant experience teaching Python? I have plenty and I > have never met ANY case of the "trouble" you mention. Yes, I taught a seminar on Python, and I didn't feel it necessary to teach either sum() or reduce(). I taught loops, and I feel confident that by the time a student is ready for sum(), they are ready for reduce(). >> In Computer Science, however, "reduce" typically only has one meaning >> when provided as a function in a language, and programmers might as >> well learn that sooner than later. > > I think you're wrong. "reduce dimensionality of a multi-dimensional > array by 1 by operating along one axis" is one such meaning, but there > are many others. For example, the second Google hit for "reduce > function" gives me: > http://www.gits.nl/dg/node65.html That's a specialized meaning of "reduce" in a specific application domain, not a function in a general-purpose programming. > where 'reduce' applies to rewriting for multi-dot grammars, and > the 5th hit is > http://www.dcs.ed.ac.uk/home/stg/NOTES/node31.html > which uses a much more complicated generalization: It still means the same thing that reduce() typically means. They've just generalized it further. Some language might generalize sum() further than you have in Python. That wouldn't mean that it still didn't mean the same thing. > while http://csdl.computer.org/comp/trans/tp/1993/04/i0364abs.htm > deals with "the derivation of general methods for the L/sub 2/ > approximation of signals by polynomial splines" and defines REDUCE > as "prefilter and down-sampler" (which is exactly as I might expect > it to be defined in any language dealing mostly with signal > processing, of course). Again a specialized domain. > Designing an over-general approach, and "fixing it in the docs" by > telling people not to use 90% of the generality they so obviously > get, is not a fully satisfactory solution. Add in the caveats about > not using reduce(str.__add__, manystrings), etc, and any reasonable > observer would agree that reduce had better be redesigned. You have to educate people not to do stupid things with loop and sum too. I can't see this as much of an argument. > Again, I commend APL's approach, also seen with more generality in > Numeric (in APL you're stuck with the existing operator on the left > of + -- in Numeric you can, in theory, write your own ufuncs), as > saner. While not quite as advisable, allowing callables such as > operator.add to take multiple arguments would afford a similarly > _correctly-limited generality_ effect. reduce + a zillion warnings > about not using most of its potential is just an unsatisfactory > combination. You hardly need a zillion warnings. A couple examples will suffice. |>oug From usenet at frogtoss.com Sun Nov 2 23:54:15 2003 From: usenet at frogtoss.com (Michael L. Labbe) Date: Mon, 03 Nov 2003 04:54:15 GMT Subject: Experienced programmer evaluating Python References: Message-ID: On Sun, 02 Nov 2003 22:32:13 -0500, Terry Reedy wrote: > Welcome to a community of generally friendly, helpful, enthusiasts -- > some with a sense of humor, even if subtle. Thanks - all of the responses have been very helpful so far. > People routinely distribute executables produced by py2exe that combines > interpreter, needed libraries, and custom source in one file. Period. > > The Python license is 'GPL compatible' but is intentionally different > from the GP and much more permissive. As I remember, there are > basically two provisos: give appropriate credit and take full > responsibility for the use you make of it. For instance, if you want to > sell software with a guarantee, then test until you are willing to > service said guarantee. Is this what you were asking about? > >> If I embed Python for >> Win32, I have read that I need to dynamically link it. > > AFAIK, this is a technical rather than legal issue. > >> If I do so with no modifications, am I free to not offer >> source code for download? > > Which source? CPython's or yours? ;-) I'm fine with accountability for my company's software. However, I cannot rule out the possibility of closing the source code of the software I produce, and not distributing any of the Python core code. My situation is that a third party, perhaps a publisher, will be interested in building a distribution of the software for end users. It would seriously weaken my ability to reach a reasonable agreement if I insisted upon any source code whatsoever being included. Publishers can be like that. So, to answer your question, can I amicably not distribute my source code or Python's alongside the binary distribution? :) From M.Waack at gmx.de Sat Nov 8 13:52:18 2003 From: M.Waack at gmx.de (Mathias Waack) Date: Sat, 08 Nov 2003 19:52:18 +0100 Subject: Can I hook a "file" to a python script? References: <3hru71-7p3.ln1@valpo.de> Message-ID: <2kqv71-9u4.ln1@valpo.de> Scott Chapman wrote: > I understand named pipes to be "one-way" only. Is that correct? Not for Linux. Linux named pipes are bidirectional. I assume this holds for all unices but I'm not sure. Mathias From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Mon Nov 10 14:39:19 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Mon, 10 Nov 2003 22:39:19 +0300 Subject: make order of function definitions irrelevant In-Reply-To: References: Message-ID: Joerg Schuster wrote: > Hello, > > according to > > http://mail.python.org/pipermail/tutor/2001-July/007246.html > > the order of function definitions does matter in python. Does anyone > know a trick to avoid this? Is there a way to "declare" functions > without defining them? > > (Making the order of function definitions irrelevant would be useful > for automatically generated python scripts.) > > > J?rg > > As was said, you usually don't need such a thing. If you desperatly looking for it, something like this might work: func = None def caller(): assert func, 'func is None' return func() def foo(): return 'foo' def bar(): return 'bar' func = foo print func() Of course, in this case you'd better pass an actual function as a parameter. But, again, almost for sureit's a flaw in your design. regards, anton. From john.abel at pa.press.net Tue Nov 18 22:35:32 2003 From: john.abel at pa.press.net (John Abel) Date: Wed, 19 Nov 2003 03:35:32 +0000 Subject: Looking for an http proxy server written in Python In-Reply-To: References: <3FBA38B9.42F93370@hotmail.com> Message-ID: <3FBAE504.7060207@pa.press.net> You might want to have a look at Willow from www.digitallumber.com. Regards John Chris Gray wrote: >Thanks, Alan, > >Your resource page is very helpful and your "Why" section explains exactly >why I'm interested in this. At first blush it looks like httpMonitor is >most in line with what I'm planning, namely, the ability to do arbitrary >processing on requests and responses. > >The problem I've run across so far is transparency and performance. I've >written my own proxy server and experimented with WebDebug and found that >some things slow down considerably and other things don't seem to pass >through at all. I want, as much as possible, for the proxy to pass >requests and responses through in a way that makes no difference to the >client, but gives me a hook to hang selective logging, storage, and other >processing on. > >That's why I specified production-quality and HTTP/1.1 compliance. If I >could just find a proxy server that forwarded requests and responses >seamlessly, I'd be happy. > >Thanks again, >Chris > >"Okey dokey.. free my mind. Right, no problem, free my mind, free my mind, >no problem, right... " -The Matrix > >On Tue, 18 Nov 2003, Alan Kennedy wrote: > > > >>[Chris Gray] >> >> >>>I'm looking for a >>>production-quality proxy server fully compliant with HTTP/1.1 written in >>>Python. >>> >>>If there isn't, is there anything that comes close? >>> >>> >>That depends on what you want the proxy to do. >> >>Check the following page for a list of python http proxies. >> >>http://xhaus.com/alan/python/proxies.html >> >>If there's nothing there that catches your eye, then give a clearer >>indication of what you need the proxy to do. >> >>regards, >> >>-- >>alan kennedy >>----------------------------------------------------- >>check http headers here: http://xhaus.com/headers >>email alan: http://xhaus.com/mailto/alan >> >> >> From s011362 at student.dtu.dk Thu Nov 20 03:33:19 2003 From: s011362 at student.dtu.dk (Halfdan Holger Knudsen) Date: Thu, 20 Nov 2003 09:33:19 +0100 (MET) Subject: It's a bug!...But is it me or the script? In-Reply-To: Message-ID: global statement missing...right. All I really have to say for myself is *DOH!* And thanks for straightening out my shortcircuit. H From SEE_AT_THE_END at hotmail.com Thu Nov 13 05:54:15 2003 From: SEE_AT_THE_END at hotmail.com (Georgy Pruss) Date: Thu, 13 Nov 2003 10:54:15 GMT Subject: Palindrome References: <20031112223135.29045.00000109@mb-m12.aol.com> Message-ID: "Ulrich Schramme" wrote in message news:bov86k$9hj$1 at online.de... | Georgy Pruss wrote: | > Knowing what your program should do, could also help. | > G-: | > | | As far as I know is a palindrome a word that you can read from both | sides. Sorry, but English is not my native language. So I don?t have an | English example handy. But the German name 'OTTO' is a palindrome. I know what is a palindrome, but I can make up dozen things the program could do with the palindrom. G-: | | | -- | -- Ulli | www.u-schramme.de | From aleaxit at yahoo.com Wed Nov 5 18:16:25 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 05 Nov 2003 23:16:25 GMT Subject: reduce()--what is it good for? (was: Re: reduce() anomaly?) References: <3fbqb.97878$e5.3584611@news1.tin.it> Message-ID: Francis Avila wrote: ... > Just out of curiosity, for what kind of problems do we find reduce to just > be the Right Way? I mean, summing a big list of numbers is fun and all, And best handled by sum (in Python 2.3). > reduce--the black sheep of the functional-Python herd? Nope -- apply beats it, given that in the last few years apply(f, args) is best spelled f(*args) ...!-) Alex From joconnor at cybermesa.com Sat Nov 29 09:18:06 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Sat, 29 Nov 2003 07:18:06 -0700 Subject: if - else In-Reply-To: References: <871xrtr8yb.fsf@pobox.com> <5ctxb.120283$Ec1.5141313@bgtnsc05-news.ops.worldnet.att.net> <87smk9mmgj.fsf@pobox.com> <3fc7a6dd.70951673@news.blueyonder.co.uk> Message-ID: Michael Geary wrote: >>>| if (10 == sum) {...} >>>| >>>| rather than >>>| >>>| if (sum == 10) {...} >>> >>> > > > >>>Yes, there's such a style, and it's considered by experienced C >>>programmers to be as weird as if( (a>> >>> > > > >>Dunno about that, I've been using C since 1986 and every C >>project I've worked on since 1991 (about half a dozen biggish >>ones) has mandated the >> >>if (CONST == variable)... >> >>style of if statement check, and most of the recent books >>recommend it. So an awful lot of experienced C >>programmers use it day in day out - and I haven't heard >>any loud complaints. >>Generally anything that saves bugs in C is "A Good Thing", >>its like running lint - you just build it into the make rules >>so that you never forget... >> >> > >The problem with "if( CONST == variable )" is that it reads unnaturally, >creating a mental speed bump when someone reads your code. Admittedly it's a >fairly minor speed bump, and avoiding coding errors is a good thing. >However, this contrivance is unnecessary with modern C compilers, which >issue a warning if you code "if( variable = CONST )". > > I was on a TCL project (ugh..one reason I don't use TKinter is simply guilt by association...I learned to hate TCL on that project) where I inherited code from a developer who did a lot of that "if 10==x" kinda stuff. Basically we said the same thing; "it doesn't read naturally" > It's certainly pleasant that Python sidesteps this issue completely! :-) True, but I'd still rather allow the assignment and catch the error by not allowing boolean comparison of non-boolean values. This would break a lot of other basic stuff in Python, though, such as using "if seq:" to determine if a sequence is empty, but I've never been a big fan of that shortcut (althuogh I use it myself). I'd rather the code have to be a bit more explicit. From pythonguy at Hotpop.com Wed Nov 5 05:14:52 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 5 Nov 2003 02:14:52 -0800 Subject: bash Vs python ?? References: Message-ID: <84fc4588.0311050214.4133e333@posting.google.com> bash vs python? Does it make sense to compare a rudimentary unix shell with minimal capabilities to a powerful programming language like python? I dont feel so. -Anand Ville Vainio wrote in message news:... > William Park writes: > > > It depends. My guess is Bash would be more suitable for "automated > > testing scripts", since you'll be calling lots of utilities. > > os.system, os.popen family, pexpect... > > In python it's much easier to process the output and produce the input > of the utilities. > > Bash is good for throwaway one liners, Python is good for scripts that > you *gasp* save to a file and might also execute later. You never > know, you might want to extend the testing system later on, perhaps > developy advanced logging facilities etc. > > The shell has one advantage over Python, though: it can be executed in > the environment of current shell (i.e. '. myscript.sh'), so you can > change the environment variables in the surrounding environment. In > python you would have to do > > export MYENVVAR = $(python calcvalforvar.py) > > If that is what you need, you might want to use bash. Otherwise, use > python. And even if you need that, you might want to generate the bash > script in a python script. > > A good rule of thumb is: The less non-python stuff you have around, > the better. Non-python parts of any given system are invariably the > ones causing most of the problems :-). From buzzard at urubu.freeserve.co.uk Wed Nov 26 10:35:00 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Wed, 26 Nov 2003 15:35:00 -0000 Subject: Pychecker under Windows References: <153fa67.0311252016.2e02b575@posting.google.com> Message-ID: "Kylotan" wrote in message news:153fa67.0311252016.2e02b575 at posting.google.com... > Is there a practical way to use Pychecker in Windows? It doesn't work > under IDLE. (In fact, it seems to end up breaking everything, and > every subsequent statement and expression I execute gets ignored.) > Running it from the Python interpreter in DOS means everything scrolls > off the screen. Ideally I'd like to redirect it to a file, or be able > to use it in IDLE. > > -- > Ben Sizer It seems to work for me in IDLE (well enough for my purposes, anyway). >>> import pychecker.checker C:\Python23\lib\site-packages\pychecker\checker.py:569: DeprecationWarning: the regex module is deprecated; please use the re module m = imp.init_builtin(moduleName) C:\Python23\lib\site-packages\pychecker\checker.py:569: DeprecationWarning: the rotor module uses an insecure algorithm and is deprecated m = imp.init_builtin(moduleName) >>> import table C:\Python23\lib\site-packages\Numeric\Precision.py:10: Imported module (string) not used C:\Python23\lib\site-packages\Numeric\Precision.py:17: Local variable (typecodes) shadows global defined on line 13 ... # loads of stuff relating to modules imported by table # then the stuff I'm interested in ... C:\Python23\table.py:324: (vars) shadows builtin C:\Python23\table.py:342: (vars) shadows builtin >>> Duncan From tjreedy at udel.edu Wed Nov 19 16:54:31 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Nov 2003 16:54:31 -0500 Subject: Leo + Python: the ultimate scripting tool: Conclusion References: <7N6dnUz1P9CKZTOiRVn-hQ@comcast.com><3FBA3FDA.C5385A9C@engcorp.com> Message-ID: "Brad Clements" wrote in message news:mailman.888.1069253598.702.python-list at python.org... > > Terry Reedy wrote: > > > I am somewhat flabbergasted that more people do not see the oddity of > > > "I will not read your first message (yet) but I will read a second > > > message from you in which you attempt to give me a reason that I find > > > 'acceptible', according to my unknown-to-you whims, that I do read > > > your first message." > Where did his message say this? I went through the web confirmation thingy > and I don't recall the original response message saying what you quoted > above, or even anything remotely close to that at all. The above is a paraphrase designed to expose the essence of what I see as an oddity. The key words 'acceptable' 'reason' are direct quotes from the original message, which I quoted in full in my original message (Nov 9, when I very briefly stated my objection reason). Here is the response message again.. ---""" You recently sent a message to me at the email address edreamleo at charter.net. To help cope with the ever increasing volume of junk e-mail, I am using ChoiceMail, a permission-based e-mail filtering tool. Your original e-mail is being held by ChoiceMail until you complete the following simple one-time process. Please click on the link [Click here to request approval] When your browser opens, fill in your name and a short reason for wanting to send e-mail to me. If your reason is acceptable, your first email and all subsequent e-mails from you will be delivered to me normally. """--- On Nov 13, in response to questions about my briefly stated objection, I noted that my reasons had nothing to do with EReam or Leo per se and then explained them in some detail. The paraphrase, which still looks pretty accurate to me, was part of that long post and might be better understood in context. > What's the difference between TMDA and what Edward is using? > Email vs. a Web confirmation. > While I prefer simply replying to an email message, I don't > see *that* much difference between the two. Some differences explained in the Nov 13 post: 1. Complete interaction with original system (email) versus requiring access to another system (web browser) which sender might not have immediately available or even at all. 2. Confirm authorship of original message versus give 'reason [that] is acceptible' that it should be read. 3. Keep interaction more or less private versus involve commercial third party. We may, of course, disagree on the importance of these even if we agree that they are accurate. Terry J. Reedy From reneaguirre at yahoo.com Fri Nov 14 12:08:59 2003 From: reneaguirre at yahoo.com (Rene Aguirre) Date: 14 Nov 2003 09:08:59 -0800 Subject: %1 is not a valid Win32 application? References: Message-ID: <18e22d94.0311140908.79b4aa0f@posting.google.com> Sel?uk Garanti wrote in message news:... > -- Sorry..., just an idea: """... The path needs quotes if it has spaces, and you need to add -u %s %s to the end ..." Anyway to avoid any strange windows "long filename" problem add the quotes to the full python.exe path. From see_signature__ at hotmail.com Wed Nov 19 05:57:36 2003 From: see_signature__ at hotmail.com (Georgy Pruss) Date: Wed, 19 Nov 2003 10:57:36 GMT Subject: New Guy References: Message-ID: "Duncan Booth" wrote in message news:Xns943867AB1ABFFduncanrcpcouk at 127.0.0.1... | "Georgy Pruss" wrote in | news:J6Hub.28594$C14.1117430 at twister.southeast.rr.com: | | Yup, I can see you are using Outlook Express, because you failed to trim my | sig from the quoted part. Conformant newsreaders will detect the sig and | automatically strip it. I didn't even know about this rule. Probably I never used a "conformant" newsreader for the last 12 years. :) | I think the significant information you are missing is that the OP used | tabs for indentation, so it may be that you see indentation when someone | posts using spaces but lose it for tabs. | | If so this should be indented: | | if 1 is None: | if str(2): | print "OE" | | But this has tabs, so it may not be: | | if 1 is None: | if str(2): | print "OE" OMG! The first rule about the source code - NEVER USE TABS! G-: -- Georgy Pruss E~mail: 'ZDAwMTEyMHQwMzMwQGhvdG1haWwuY29t\n'.decode('base64') From aleaxit at yahoo.com Sun Nov 2 04:56:28 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 02 Nov 2003 09:56:28 GMT Subject: another dictionary q References: Message-ID: ruari mactaggart wrote: > can this be tidied up ? > >>>>verb={} >>>>verb[infinitive]=[['','','','','',''],['','','','','',''],['','','','','' > ,''],['','','','','',''],['','','','','',''],['','','','','','']] > > it is to create a dictionary entry with six empty lists of six items as > values. verb[infinitive] = [ [""]*6 for i in range(6) ] is more concise and saves you from counting errors. > or is it unnecesary ? They represent six tenses with six persons in each > for an italian verb translator. Whether it's necessary or not depends on how your application uses those data, so I'm not sure how I can answer the question (despite being Italian:-). Alex From steve.coates at smiths-aerospace.com Mon Nov 24 02:59:22 2003 From: steve.coates at smiths-aerospace.com (Steve Coates) Date: 23 Nov 2003 23:59:22 -0800 Subject: update a word-bookmark with the win32.com extension References: <48bafd6d.0311180542.5f7582ea@posting.google.com> Message-ID: <621c6e53.0311232359.271d7909@posting.google.com> docelm at web.de (Christian Lehmann) wrote in message news:<48bafd6d.0311180542.5f7582ea at posting.google.com>... > Hello, > > I want to update a bookmark in a word file. > My code looks like this: > > def UpdateBookmark(BookmarkToUpdate, TextToUse): > FieldRange = Document.Bookmarks(BookmarkToUpdate).Range > FieldRange.Text = TextToUse # error message > ActiveDocument.Bookmarks.Add(BookmarkToUpdate,FieldRange) > > > UpdateBookmark ("Bookmarkname","newString") > > > when i assign the new string an error message occurs. > I m using Office XP... > > Thanks > Christian I've used the following in Word97. It isn't very pretty, but it does work:- def UpdateBookmark(App, Doc, Bookmark, Value): Doc.Bookmarks(Bookmark).Select() s = App.Selection s.Cut() s.InsertBefore(Value) Doc.Bookmarks.Add(Bookmark) Steve Coates Also somewhere in the West of England From logan at phreaker.nospam Fri Nov 21 20:47:53 2003 From: logan at phreaker.nospam (Logan) Date: Sat, 22 Nov 2003 02:47:53 +0100 Subject: Help Pliz ! stuck on page 4 of tutorial References: <91de052a.0311211610.48fdd0ea@posting.google.com> Message-ID: On Fri, 21 Nov 2003 16:10:11 -0800, Adolfo wrote: > Hello everyone, I am a newbie starting Fredrik Lundh .pdf tutorial. Running W2000. > > I am stuck in page four "Hello Again" program: > When I try running it, it shows the root Python window very fast and > dissapears. The intended Tk window with buttons: either does not > show, or dissapears fast before I can tell it is there. The first > program on the tutorial did run fine. > > Here's the program as shown on the tutorial: You had a lot of typos in your code; here's a corrected version which should work. HTH, Thomas. from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print "Hi there, everyone !" root = Tk() app = App(root) root.mainloop() -- mailto: logan at phreaker(NoSpam).net From bokr at oz.net Sat Nov 22 16:33:15 2003 From: bokr at oz.net (Bengt Richter) Date: 22 Nov 2003 21:33:15 GMT Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> Message-ID: On 22 Nov 2003 12:14:03 -0800, Paul Rubin wrote: >rkern at ucsd.edu (Robert Kern) writes: >> Note that the question is phrased as a "proprietary vs. GPL" >> dichotomy. I think the following entry is more appropriate: >> >> http://www.gnu.org/licenses/gpl-faq.html#TOCGPLModuleLicense > >No I don't think it's more appropriate. That entry is about adding >your own module to a GPL'd program. Such a module doesn't have to be >GPL'd, as long as its license is "GPL-compatible". The original >question was not about that. It was about using part of a GPL'd >program in another program. That is prohibited unless the second >program is also GPL'd. Yes, but even that wasn't the actual question the way I read it. To requote [with my annotation]: """ If a compiled Python extension module B includes code from some other software A which is licensed only under the GPL [resulting in B_GPLd_because_of_A], do other Python programmes, C, which import [this is the key relationship -- importing a GPL'd module, irrespective of how it became GLP'd] module B also need to be licensed under a GPL-compatible license (assuming C is/are to be distributed to third parties)? """ The question ISTM is whether importing a GPL'd module is enough to trigger GPL obligations on the part of the importing module. ISTM that is more like a program-program relationship than incorporation of code (unless it modifies the source. e.g., with an execfile and changes based on source knowledge). I.e., if a non-GPL module could be substituted without changing the importer, IWT that would mean plug-compatibility rather than incorporation. But IANAL. I haven't read the license recently, but I thought there there was some arms-length uses of GPL software by proprietary software that are allowed, or am I mistaken? I don't know how long the arm has to be though. Regards, Bengt Richter From robin at jessikat.fsnet.co.uk Thu Nov 13 15:00:32 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 13 Nov 2003 20:00:32 +0000 Subject: Python's simplicity philosophy References: <2259b0e2.0311112248.3be2d304@posting.google.com> <17lsb.109042$fl1.4548960@twister.southeast.rr.com> Message-ID: In article , Michael T. Babcock writes ...... >I'm hoping you were being sarcastic ... but I get the feeling you aren't. > >Why, pray-tell, would you want an OO program to do: > >results = [ func(x) for x in sequence ] > >... instead of ... > >results = sequence.map(func) ?? > .... well actually I'm quite happy with reduce as a function or as a method on sequences. I actually feel uncomfortable with all the plethora of iteration tools, comprehensions etc etc. However, I'm not forced to use them. -- Robin Becker From nav+posts at bandersnatch.org Mon Nov 10 14:32:40 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 10 Nov 2003 14:32:40 -0500 Subject: Outlook add-in required to sort messages References: <7d88291f.0311051132.4a9b4f0f@posting.google.com> Message-ID: jerry at sumpton.com (Jerry Sumpton) writes: > Can you offer suggestions on how to locate a suitable developer? > Another list, perhaps? This is not actually a bad place to mention that you're looking for someone to do some contract programming. (I'd offer myself, but I would really rather not do anything that makes Outlook more functional). You could also post a message on the Python Jobs board, at: http://python.org/Jobs.html Hope that's helpful, 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 dalke at dalkescientific.com Sun Nov 16 13:28:10 2003 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sun, 16 Nov 2003 11:28:10 -0700 Subject: Python's simplicity philosophy In-Reply-To: <20031116155635.10470.qmail@green.zadka.com> Message-ID: Moshe: > This would probably be done by what I might call DMU > (Decorate-Maximize-Undecorate) -- > def longest(seq): > return max([(len(x),x) for x in seq])[1] Almost. Your code requires that the 'x' be comparable, eg, suppose it's a sequence of complex numbers and the goal is to find a number with largest imaginary component. Then the following won't work def largest_imaginary(complex_seq): return max([(x.imag, x) for x in complex_seq])[1] There's also the worry that your code breaks ties by looking for the max object, when the one I spec'ed said I chose the first match. To fix these you would need to write your DMU as def longest(seq): return max([ (len(x), -i, x) for x, i in enumerate(seq) ])[2] which is identical (for obvious reasons) in style to the Decorate-Stable-Sort-Undecorate idiom. ("-i" done to get the first match.) Is such a thing common enough to warrant a new function somewhere in the standard library? Here are existing use cases (I'll use 'maxitem' as the function name): CGIHTTPServer.py: nobody = 1 + max(map(lambda x: x[2], pwd.getpwall())) could be replaced with nobody = 1 + maxitem(pwd.getpwall(), lambda x: x[2]) Slightly fewer characters, but requires knowing more of the standard library, and here the extra guarantees of "maxitem" aren't needed That's the only example I could find in the std. lib which uses a min or max on a map. I also looked for a 'for .* in ' followed within 6 lines by a ' > ' or ' < ' and only found this example from trace.py longest = "" for dir in sys.path: if path.startswith(dir) and path[len(dir)] == os.path.sep: if len(dir) > len(longest): longest = dir which could not be easily replaced with your max-of-a-list because of the filter and default value of "". It could be written using "maxitem" as longest = maxitem( [dir for dir in sys.path if path.startswith(dir) and path[len(dir)] == os.path.sep], len, "") However, I find that to be harder to understand than the original code and not significantly shorter. Therefore I find there to be few cases in the standard library which would be improved with a standard "DMU" function. That doesn't mean it shouldn't be added, only that the decision has little hard data to back up a gut feeling. Andrew dalke at dalkescientific.com From peter at engcorp.com Thu Nov 20 09:14:21 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Nov 2003 09:14:21 -0500 Subject: Misleading Python error message References: <3fbbcbfc$0$577$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <3FBCCC3D.E54D56CF@engcorp.com> Dennis Lee Bieber wrote: > > Brian Kelley fed this fish to the penguins on Wednesday 19 November > 2003 12:02 pm: > > > Shouldn't this report something like (TypeError: can't subclass from a > > module) It goes to the right line, but I coudn't see where the > > function was being called :) > > > Which version? Python 2.3, of course, as a result of the new types stuff. -Peter From grey at despair.dmiyu.org Fri Nov 14 19:34:47 2003 From: grey at despair.dmiyu.org (Steve Lamb) Date: Sat, 15 Nov 2003 00:34:47 -0000 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> <84fc4588.0311140319.3778de15@posting.google.com> Message-ID: On 2003-11-14, Ben Finney wrote: > What evidence do you have for this? What evidence do you have to the contrary? > How do you account for contrary evidence, such as the evident thought > processes of many (not least the OP of this thread) that "more books on X => > more interest in X => I should buy books on X"? Let me counter then. I recently got a new job which, if I were to perform to the expectations of the people who hired me, required me to learn two new technologies I have been looking at for a while but have not yet touched. PHP and MySQL. I spent 2 hours in the local Borders and B&N looking at PHP, MySQL, PHP+MySQL books. After looking at about a little over a dozen books total guess how many I bought? 2. _Core PHP Programming_ and _Core MySQL_. From what I could tell in just a quick riffle through the pages those offered the best format for me to learn from as well as use as a reference book. I also will not be buying any more books on PHP or MySQL for a while. Why? Because those, along with Sill's QMail book, topped $120 US Dollars. Those books certainly did compete for my dollars and ~12 of them lost out. For the record Barnes & Noble had about 6 Python book on their shelves and Borders about a dozen. I didn't pick up any of them even though the only Python book in my posession right now is Beazley's _Python Essential Reference_ which I bought several years ago. Why? Because I know v2.3 is just coming out and didn't want to get a book on v2.2 when the v1.5.2 book has held me in good stead thusfar. Now that we've presented anecdotal evidence both both sides care to share why you think that your way of thinking is the predominant one; IE more books on the shelf means you're going to buy more books on that topic? -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From aleax at aleax.it Mon Nov 10 15:45:03 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 10 Nov 2003 20:45:03 GMT Subject: True, False, None (was re. Pruss's manifesto) References: <20031110065915.07735.00000461@mb-m07.aol.com> Message-ID: Thomas Bellman wrote: > Alex Martelli wrote: > >> True, False and None may well become keywords in the future, because that >> might make things "even finer" in some respects. E.g., right now, >> while True: >> ... >> has to look-up 'True' at EACH step just in case the ... code rebinds >> that name. This _is_ a bit silly, when there is no real use-case for >> "letting True be re-bound". Nothing major, but...: > > That's a silly reason to make them keywords. A much better way > to achieve the same goal would be to make the optimizer recognize > that True isn't re-bound within the loop. Making the optimizer > better would improve the performance of much more code than just > 'while True' loops. You are heartily welcome to perform the dynamic whole-code analysis needed to prove whether True (or any other built-in identifier) may or not be re-bound as a side effect of functions called within the loop -- including the calls to methods that can be performed by just about every operation in the language. It seems a very worthy research project, which might take good advantage of the results of the pypy project (there is plenty of such advanced research that is scheduled to take place as part of pypy, but there is also surely space for a lot of other such projects; few are going to bear fruit, after all, so, the more are started, the merrier). Meanwhile, during the years in which this advanced research project of yours matures and (with luck) produces usable results, Python's mainstream implementation will stick to the general strategy that has served it so well and for so long: _simplicity_ first and foremost, optimization (and thus complication) only where it has provable great benefit/cost ratios (e.g., dictionary access and list-sorting). As there is really no good use case for letting user code rebind the built-in names None, True, and False, making them keywords has almost only pluses (the "almost" being related to backwards compatibility issues), as does "nailing down" many other popular built-in names (by techniques different from making them into keywords, most likely, as the tradeoffs are quite different in those cases). The process has already begun in Python 2.3, mind you...: [alex at lancelot bo]$ python2.3 -c 'None=23' :1: SyntaxWarning: assignment to None (True and False will take more time, because a program may try to assign them [if not already known] in order to be compatible with relatively recent Python releases which did not have them as built-in names). Alex From bokr at oz.net Thu Nov 20 19:27:14 2003 From: bokr at oz.net (Bengt Richter) Date: 21 Nov 2003 00:27:14 GMT Subject: rotor alternative? References: <7x8ymd4hwf.fsf@ruckus.brouhaha.com> <7xptfmyca4.fsf@ruckus.brouhaha.com> <3FBD3C78.3711CF5E@engcorp.com> <7x3cci1xlt.fsf@ruckus.brouhaha.com> <3FBD5633.20DAEB1@engcorp.com> Message-ID: On Thu, 20 Nov 2003 19:02:59 -0500, Peter Hansen wrote: >Paul Rubin wrote: >> >> Peter Hansen writes: >> > The docs for Py2.3 say: >> > """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. """ >> > >> > I wonder if the part about "since the first call to this function" would >> > make this dangerous for your purposes. >> >> I don't run Windows and don't want to use something Windows specific. >> Although, "since the first call to this function" is probably ok. All >> that's needed is to get a unique number to initialize the internal >> PRNG with. Hopefully sometime, the Python library will include a C >> extension to get secure random numbers from the Windows Crypto API. >> On *nix, they are already generally available from /dev/urandom. > >It just struck me that if it's the first call to the function during >a given program invocation which matters (as opposed to during a power-on >cycle of the whole PC), then it seems possible that you'll get exactly the >same valueeach time you call it if it's called only once by the program. > Ugh, you're right: ====< firsttimes.py >======= import time c = time.clock() t = time.time() print c,t ============================ [16:27] C:\pywk\ut\crypto>firsttimes.py 1.25714266558e-005 1069374432.09 [16:27] C:\pywk\ut\crypto>firsttimes.py 1.25714266558e-005 1069374437.29 [16:27] C:\pywk\ut\crypto>firsttimes.py 1.25714266558e-005 1069374445.84 [16:27] C:\pywk\ut\crypto>firsttimes.py 1.25714266558e-005 1069374449.78 [16:27] C:\pywk\ut\crypto>firsttimes.py 1.17333315454e-005 1069374454.33 Why'd they do that? On my platform it ought to go back to either to the rdtsc pentium instruction, which reads a 64-counter of CPU cycles since power on (I assume it starts from zero) or maybe to the clock chip time counter, which is probably ~55ms/2**16 or so resolution. But this looks like python gets and stores a value on _python_ startup as a reference. Well, at least the least significant bits ought to be fairly random after some time has gone by. Hm, ... except that NT scheduling may group sampling towards the beginning of the 10-ms slice times anyway. Phooey. Sorry Paul, I didn't realize it was re-zeroed like that. Regards, Bengt Richter From emile at fenx.com Sat Nov 29 22:23:45 2003 From: emile at fenx.com (Emile van Sebille) Date: Sat, 29 Nov 2003 19:23:45 -0800 Subject: list: from 2 to 3 dimensions..looking for a nice way References: Message-ID: Sven: > I got values from a db in this way -> [[id, date, value1, value2, > value...],[id,date,value1,value2,value..],...] > > I'd like to group the arrays if they have the same id and the date is > nearby(+-1 sec) to one array(so that they stand for an order)-> > [[[],[],[]],[[],[],[]]] > > I don't mind if it would be these structure > {id:[[],[]],id:[[],[]]} > but in the end they should be sorted by date How about: ---8<------ data = [ ['id1', 'date4', 'val1', 'val2', 'val3'], ['id1', 'date3', 'val1', 'val2', 'val3'], ['id3', 'date2', 'val1', 'val2', 'val3'], ['id3', 'date1', 'val1', 'val2', 'val3'], ] data.sort(lambda ii,jj: cmp(ii[1],jj[1])) target = [] priorid = '' for rec in data: if rec[0] == priorid: target[-1].append(rec) else: priorid = rec[0] target.append([priorid,rec]) from pprint import pprint pprint(target) ---8<------ This sorts by date and groups by id if adjacent. It wouldn't take much to change the test on priorid to be near. -- Emile van Sebille emile at fenx.com From seberino at spawar.navy.mil Sat Nov 22 14:44:40 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 22 Nov 2003 11:44:40 -0800 Subject: How send LIST to C extension? References: Message-ID: Vincent Thanks. Your example with "0" will make *seq point to the list I believe. Can I extract the elements of the list into C variables with PyArg_ParseTuple if I didn't want to work with PyObject directly?? Perhaps this is a bad idea and your way is always better??? (python.org docs had example of extracting elements of a tuple with PyArg_ParseTuple but I couldn't do it.) Chris "vincent wehren" wrote in message news:... > "Christian Seberino" schrieb im Newsbeitrag > news:bf23f78f.0311211356.7368197c at posting.google.com... > | I already sent a post about problems sending list as argument in a C > extension. > | > | I think I'll start over and just ask if anyone has done this successfully. > | > | Can you send me code that does this?? > | > | (I tried PyArg_ParseTuple("[ii]",...) but apparently there is more to it > than > | just adding brackets. > > > In your function you need something like > > PyObject* seq; > > if(!PyArg_ParsTuple(args, "O", &seq)) > return 0; > > > To do something useful with seq, you might want to look at the PySequence_* > function family in the Python/C API Reference Manual (s. > http://www.python.org/doc/current/api/sequence.html) > > HTH, > Vincent Wehren > > > > > > | > | chris From jjl at pobox.com Wed Nov 19 09:09:41 2003 From: jjl at pobox.com (John J. Lee) Date: 19 Nov 2003 14:09:41 +0000 Subject: rotor alternative? References: Message-ID: <87u150cuvu.fsf@pobox.com> "Dave Brueck" writes: > Robin wrote: > > It seems that the rotor module is being deprecated in 2.3, but there > > doesn't seem to be an obvious alternative. I'm using it just for [...Dave has switched to AES] > Since I'm not going to great lengths to hide the key, it works out to be about > the same strength of encryption as rotor. ;-) Quite. I don't understand why it's deprecated. We've known since the fifties that the algorithm is broken, so wasn't it clear from the start that this was for obfuscation, not strong encryption? Shouldn't we just add a warning to the docs (if there's not one there already)?? John From bokr at oz.net Wed Nov 19 17:28:53 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Nov 2003 22:28:53 GMT Subject: Callable generators (PEP 288: Generator Attributes, again) References: <55688f89.0311180211.7ab1bc30@posting.google.com> <2259b0e2.0311180616.5980fabc@posting.google.com> <95aa1afa.0311191028.77aa02a3@posting.google.com> Message-ID: On 19 Nov 2003 10:28:27 -0800, michele.simionato at poste.it (Michele Simionato) wrote: >"Francis Avila" wrote in message news:... >> I'm suggesting the PEP's functionality, not its syntax and semantics. My >> contention is that the PEP regards generators as too class-like, when they >> are more naturally considered as function-like. >> >> For example, your iterator class/instance would look like this: >> >> def iterator(x=1)(x): >> yield x >> yield x >> >> print iterator.next() # -> 1 >> print iterator(5) # -> 5 >> >> The local name "x" is updated (according to the second parameter list in the >> function definition) right after the yield of the previous call when >> iterator is called, behaving like a state-persistent callable function. If >> it's just "nexted", it behaves like a plain old iterator. > >I see what you mean, now. Still, the notation is confusing, since I >do think an iterator as something which it obtained by "instantiating" >a generator. On the other hand, your iterator(5) would not be a newly >"instantiated" iterator, but the same iterator with a different >parameter x. So, you would need a different syntax, as for instance >iterator[5]. Still, I do think this would be confusing. The class >solution would be more verbose but clearer. I really like generators, but I am not really happy with the magic transmogrification of an ordinary function into a generator-instance factory as a magic side effect of defining a state machine with yields in the function body. Sorry to complain about a past decision, but one effect was also to exclude yield-ing in a subroutine of the generator (which would in general require suspending a stack of frames, but would open a lot of possibilities, ISTM). But, trying to live with, and extend, current realities, we can't call the generator factory function name again to pass values into the generator, since that merely creates another generator. But if we have gen = factory(some_arg) where factory could be e.g., (I'm just using 'factory' instead of 'iterator' for semantics) def factory(x=1): yield x; yield x we could potentially call something other than gen.next(), i.e., if gen had a gen.__call__ defined, gen(123) could be a way to pass data into the generator. But what would it mean w.r.t. backwards compatibility and what would be different? Obviously the calls to gen.next() generated by for x in factory(123): print x would have to work as now. But consider, e.g., for x in itertools.imap(factory(), 'abc'): print x presumably it would be equivalent to gen = factory() for x in itertools.imap(gen, 'abc'): print x and what we'd like is to have some local variables (just x in this case) set to whatever is passed through gen.__call__(...) arg list, in this case successively 'a', 'b', and 'c'. Since gen is the product of a factory (or implicit metaclass operating during instantiation of the function??) it should be possible to create a particular call signature for gen.__call__. One syntactic possibility would be as Francis suggested, i.e., def iterator(x=1)(x): yield x yield x but, BTW, I guess Francis didn't mean print iterator.next() # -> 1 print iterator(5) # -> 5 since it is not iterator that has the .next method, but rather the returned generator. So unless I misunderstand it would have to be gen = iterator() print gen.next() # -> 1 print gen(5) # -> 5 IIRC, this is what I was getting at originally (among other things;-) If we live with the current parameter list definition mechanism, we are forced to pass default or dummy values in the initial factory call, even if we intend to override them with the very first call to gen('something'). We have the option of using them through next(), but we don't have to. I.e., gen = iterator() print gen('hoo') # -> hoo (default 1 overridden) print gen('haw') # -> haw also, incidentally, gen = iterator() print gen('hoo') # -> hoo (default 1 overridden) print gen.next() # -> hoo (x binding undisturbed) That doesn't seem so hard to understand, if you ask me. Of course, getting gen.__call__ to rebind the local values requires real changes, and there are some other things that might make usage better or worse depending -- e.g., how to handle default parameters. On the call to the factory, defaults would certainly act like now, but on subsequent gen() calls, it might make sense to rebind only the explicitly passed parameters, so the default would effectively be the existing state, and you could make short-arg-list calls. Hmmm... This might be a good combination use of defaults in the factory call to set initial defaults that then are optionally overridden in the gen() calls. I kind of like that ;-) > >> Here's an efficient reversable generator: >> >> def count (n=0)(step=1): >> while True: >> yield n >> n += step My way would be def count (step=1, count=0): while True: yield n n += step ctr = count() ctr() # -> 0 ctr() # -> 1 ctr() # -> 2 ctr(-1) # -> 1 ctr() # -> 0 ctr() # -> -1 > >Yeah, it is lightweight, but a class derived from "Iterator" >would be only one line longer, so I am not convinced. Also, >people would start thinking that you can define regular >functions with two sets of arguments, and this would generate >a mess ... Well, what do you think of the above? BTW, thanks Francis for the citation ;-) PS, I wonder if a co_yield would be interesting/useful? (Think PDP-11 jsr pc,@(sp)+ ;-) Regards, Bengt Richter From matt_gerrans at hp.com Thu Nov 6 15:52:16 2003 From: matt_gerrans at hp.com (Matt Gerrans) Date: Thu, 06 Nov 2003 20:52:16 GMT Subject: stop program References: <3faab121$0$58705$e4fe514c@news.xs4all.nl> Message-ID: <4wyqb.8585$_87.2948@news.cpqcorp.net> > other platforms: I have no idea. On Windows, use win32api.TerminateProcess() From SBrunning at trisystems.co.uk Mon Nov 10 09:57:10 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Mon, 10 Nov 2003 14:57:10 -0000 Subject: win32.com problem to unprotect a word document Message-ID: <31575A892FF6D1118F5800600846864D01200CC1@intrepid> > From: docelm at web.de [SMTP:docelm at web.de] > I?m trying to unprotect a word document with python for reading all form > fields. > But it doesn?t work. > > Here?s a simple code sample: > > > wordapp = win32com.client.Dispatch("Word.Application") > docfile = wordapp.Documents.Open(file) > > protecttype = docfile.ProtectionType # protected delivers 2 > docfile.Unprotect > protecttype = docfile.ProtectionType # anyway 2 > > # do some work > > docfile.Protect > protecttype = docfile.ProtectionType # anyway 2 Just a wild guess - docfile.Unprotect looks like a it might well be a function, but you aren't *calling* it. Try using "docfile.Unprotect()" instead. Cheers, Simon Brunning, http://www.brunningonline.net/simon/blog/ --LongSig ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From guettli at thomas-guettler.de Wed Nov 26 09:21:47 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 26 Nov 2003 15:21:47 +0100 Subject: pyUNO: Converting doc/sxw to html/ps References: Message-ID: Am Wed, 26 Nov 2003 11:44:20 +0100 schrieb Thomas Guettler: > Hi! > > The introduction on > http://udk.openoffice.org/python/python-bridge.html > is very good. Nice to see, that python is integrated > into OpenOffice1.1. I found an example myself: http://udk.openoffice.org/python/samples/ooextract.py Export to PS or PDF seems a bit more difficult. I am till interested if someone has experience with this. thomas From not.available at na.no Tue Nov 4 14:01:19 2003 From: not.available at na.no (Noen) Date: Tue, 04 Nov 2003 19:01:19 GMT Subject: XORing long strings opimization? Message-ID: <3ISpb.24447$BD3.4566933@juliett.dax.net> def XOR(s1,s2): """ XOR string s1 with s2 """ output = "" # Argument check if (type(s1) and type(s2)) != type(""): raise TypeError, "Arguments are not strings" if len(s1) != len(s2): raise ValueError, "Size differs in strings" # Xoring for c1 in s1: for c2 in s2: output += chr(ord(c1) ^ ord(c2)) return output This way is very slow for large strings. Anyone know of a better and faster way to do it? From warlock at eskimo.com Tue Nov 4 20:53:27 2003 From: warlock at eskimo.com (Jim Richardson) Date: Tue, 4 Nov 2003 17:53:27 -0800 Subject: nearest neighbor in 2D References: Message-ID: On Tue, 04 Nov 2003 17:13:58 +0100, Peter Otten <__peter__ at web.de> wrote: > Alex Martelli wrote: > >> Andrew Dalke wrote: >> >>> Ron Adam >>>> for point in p: >>>> distance = math.sqrt((new_point[0]-point[0])**2 \ >>>> +(new_point[1]-point[1])**2) >>> >>>> I really don't know how you can make this faster. There might be a >> >> Hmmm, that's what math.hypot is for, isn't it...? >> >> [alex at lancelot Lib]$ timeit.py -c -s'import math; p=1.6,2.5; np=2.4,1.3' >> 'math.sqrt((np[0]-p[0])**2 + (np[1]-p[1])**2)' >> 100000 loops, best of 3: 3 usec per loop >> >> [alex at lancelot Lib]$ timeit.py -c -s'import math; p=1.6,2.5; np=2.4,1.3' >> 'math.hypot(np[0]-p[0], np[1]-p[1])' >> 100000 loops, best of 3: 1.9 usec per loop >> >> >>>> library that has a distance between two points function that could >>>> speed it up. >>> >>> An easy way is to move the math.sqrt call outside the loop, since >>> sqrt(d1) < sqrt(d2) iff d1 < d2 (when d1,d2>=0) >> >> Yes, omitting the math.sqrt gives the same speed as calling math.hypot, >> and it's the classic solution to speed up minimum-distance problems. >> >> I vaguely suspect you could shave some further fraction of a microsecond >> by saving those differences as dx and dy and then computing dx*dx+dy*dy -- >> since another classic tip is that a**2 is slower than a*2. Let's see...: >> >> [alex at lancelot Lib]$ timeit.py -c -s'import math; p=1.6,2.5; np=2.4,1.3' >> 'dx=np[0]-p[0]; dy=np[1]-p[1]; disq=dx*dx+dy*dy' >> 1000000 loops, best of 3: 1.39 usec per loop >> >> ...yep, another small enhancement. Ain't measuring _FUN_?-) > > Finally found an application for complex numbers: > > ...> timeit.py -s"p= 1.6+2.5j; np=2.4+1.3j" "d=abs(p-np)" > 1000000 loops, best of 3: 0.436 usec per loop > > ...> timeit.py -s"p= 1.6,2.5; np=2.4,1.3" "dx=np[0]-p[0]; > dy=np[1]-p[1];d=dx*dx+dy*dy" > 1000000 loops, best of 3: 1.15 usec per loop > > This is of course all premature optimization as the most promising approach > is to try hard to reduce the number of candidate points, as David Eppstein > seems to have done. But then, he could use complex numbers, too. > > Peter > I am new to timeit.py, but this is odd. jim at grendel:~$ /usr/lib/python2.3/timeit.py -c ' p=1.6+2.5j;np=2.4+1.3j; d=abs(p-np)' 100000 loops, best of 3: 3.1 usec per loop vs jim at grendel:~$ /usr/lib/python2.3/timeit.py -c -s'import math; p=1.6+2.5j;np=2.4+1.3j; d=abs(p-np)' 10000000 loops, best of 3: 0.141 usec per loop Is it because the builtin math functions are much slower? -- Jim Richardson http://www.eskimo.com/~warlock Televangelists: The Pro Wrestlers of Religion From mwilson at sarcastic-horse.com Sat Nov 22 09:06:11 2003 From: mwilson at sarcastic-horse.com (Matthew Wilson) Date: Sat, 22 Nov 2003 14:06:11 GMT Subject: HTMLParser handler_starttag misses lots of tags! References: Message-ID: In article , Robert Brewer wrote: > When I try it like this: > > import HTMLParser > > class HP(HTMLParser.HTMLParser): > > def handle_starttag(self, tag, data): > print "tag is %s." % (tag) > > def handle_comment(self, data): > print "caught a comment: %s." % (data) > > def handle_data(self, data): > if "IP" in data: > print "Caught %s." % data > > toParse = """ > > > > content="text/html;charset=ISO-8859-1"> > > ------- 8< Much html snipped here for this email --------- > > > > >""" > > for line in toParse.split(u'\n'): > HP().feed(line) > > > > I get: > > tag is html. > tag is head. > tag is meta. > tag is meta. > tag is meta. > tag is meta. > tag is meta. > tag is title. > tag is link. > tag is script. > tag is body. > tag is form. > tag is table. > tag is tr. > tag is td. > tag is h1. > caught a comment: RULE //. > tag is tr. > tag is td. > tag is img. > caught a comment: END RULE //. > tag is tr. > tag is td. > tag is b. > tag is td. > tag is tr. > tag is td. > tag is b. > tag is td. > caught a comment: RULE //. > tag is tr. > tag is td. > tag is img. > caught a comment: END RULE //. > tag is tr. > tag is td. > tag is span. > tag is tr. > tag is td. > tag is b. > tag is td. > tag is tr. > tag is td. > tag is b. > Caught IP Address . > tag is td. > tag is tr. > tag is td. > tag is b. > tag is td. > tag is tr. > tag is td. > tag is b. > Caught IP Subnet Mask . > tag is td. > tag is tr. > tag is td. > tag is b. > tag is td. > tag is tr. > tag is td. > tag is b. > tag is td. > caught a comment: RULE //. > tag is tr. > tag is td. > tag is img. > caught a comment: END RULE //. > tag is tr. > tag is td. > tag is span. > tag is tr. > tag is td. > tag is b. > tag is td. > tag is tr. > tag is td. > tag is b. > Caught IP Address . > tag is td. > tag is tr. > tag is td. > tag is b. > tag is td. > tag is tr. > tag is td. > tag is b. > Caught IP Subnet Mask . > tag is td. > tag is table. > tag is tr. > tag is td. > tag is img. > tag is tr. > tag is td. > tag is span. > tag is table. > tag is tr. > tag is td. > tag is b. > tag is td. > tag is table. > tag is td. > tag is b. > tag is td. > tag is td. > tag is b. > tag is td. > tag is td. > tag is b. > tag is td. > tag is table. > tag is tr. > tag is td. > tag is img. > tag is tr. > tag is td. > tag is input. > tag is input. > > My guess is the problem lies in your line-separation logic, not > HTMLParser. IIRC, open() doesn't split by line automatically. Note that > this doesn't answer the entire question. My guess is that HTMLParser, > once it encounters the form tag, treats everything inside that form tag > (even other tags) as data to be consumed by handle_data(). Once it > encounters the closing form tag, it might stop. Either re-feed() that or > get the line-splitting right. > > Just some out-loud thoughts. > > > Robert Brewer > MIS > Amor Ministries > fumanchu at amor.org > Thanks for the help. I tried running the program just as you wrote it, and I still get the same results. I also tried feeding the whole file at once: hp = HP() hp.feed(infile.read()) and this gave me the same results. From rmunn at pobox.com Sat Nov 29 12:06:51 2003 From: rmunn at pobox.com (Robin Munn) Date: Sat, 29 Nov 2003 17:06:51 GMT Subject: How to call functions with list and keyword arguments? References: Message-ID: John Z. Smith wrote: > Thanks. I didn't event know that's legal syntax. Just checked the tutorial > and reference > manual but didn't find it. Could you point me to it? Thanks again. Looking through the manual myself, it's a little hard to find. The tutorial mentions the *args syntax in section 4.7.4: http://www.python.org/doc/current/tut/node6.html#SECTION006740000000000000000 but never mentions the **kwargs syntax at all that I could find. I believe the tutorial could stand to be updated in that respect, maybe by expanding section 4.7.4. If the *args syntax is in there, **kwargs should be also. The language reference has mentions the syntax in the section on callable objects, 5.3.4: http://www.python.org/doc/current/ref/calls.html And finally, the extended call syntax is mentioned in the description of the builtin function apply(), as the reason why apply() is now deprecated: http://www.python.org/doc/current/lib/built-in-funcs.html -- Robin Munn rmunn at pobox.com From ameLista at telia.com Fri Nov 28 12:16:52 2003 From: ameLista at telia.com (Anders Eriksson) Date: Fri, 28 Nov 2003 17:16:52 GMT Subject: Strange behavior in PythonWin IDE References: <1fa1hqqgi2xas.dlg@morateknikutveckling.se> Message-ID: <16wrnk5xurid6$.dlg@amez.homeip.net> On Fri, 28 Nov 2003 11:02:42 -0500, John Roth wrote: > 1. To eliminate the depreciation warning, you do need to put in the > correct pep-0263 character set declaration line. I believe this will > become a fatal error in 2.4 > Ok! I understand how to enter the encoding line, but I can't find any list of which encodings that are legal. Is there such a list? // Anders -- At-home-but-still-working From danb_83 at yahoo.com Thu Nov 13 20:04:16 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 13 Nov 2003 17:04:16 -0800 Subject: checking for ASCII character References: Message-ID: "Daniel" wrote in message news:... > Hi, is there a way to check if a letter entered is an uppercase ASCII > character? letter.isupper() From sqbassNOSPAM at free.fr Sat Nov 8 12:23:06 2003 From: sqbassNOSPAM at free.fr (ivan le magnifique) Date: Sat, 8 Nov 2003 18:23:06 +0100 Subject: running a script like a daemon References: <3fad23ea$0$235$636a55ce@news.free.fr> <8w9rb.437945$R32.14532589@news2.tin.it> Message-ID: <3fad26a0$0$229$636a55ce@news.free.fr> many thanks ! From Mike at DeleteThis.Geary.com Wed Nov 12 04:43:31 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 12 Nov 2003 01:43:31 -0800 Subject: screensaver References: <2259b0e2.0311060704.754a4b6e@posting.google.com> Message-ID: Thomas Heller: > A google search for 'disable screensaver windows' turns up VB code, > which easily translates into this Python code: > > ----- > import ctypes > SPI_SETSCREENSAVEACTIVE = 17 > > def StartScreenSaver(on): > ctypes.windll.user32.SystemParametersInfoA( > SPI_SETSCREENSAVEACTIVE, on, None, 0) > > StartScreenSaver(1) > ----- > > Unfortunately, it doesn't seem to work (for me, on XP. At least it has > no visible effect). Your StartScreenSaver() function should probably be called EnableScreenSaver(). Call it with a 0 parameter to disable the screen saver, or 1 to enable it. The function won't have any immediate visible effect--it simply enables or disables the screen saver, it doesn't start or stop it. Try setting your screen saver timeout to one minute. Let the computer sit for a minute to verify that the screen saver is working. Then call EnableScreenSaver(0) to disable the screen saver, and let the computer sit for a minute again to see if you've disabled it. -Mike From docelm at web.de Tue Nov 11 03:42:50 2003 From: docelm at web.de (Christian Lehmann) Date: 11 Nov 2003 00:42:50 -0800 Subject: win32.com problem to unprotect a word document References: Message-ID: <48bafd6d.0311110042.5df4d72f@posting.google.com> Oh damn, you?re right. Thank you very much... how could I forget this?! Greets Christian From edreamleo at charter.net Fri Nov 7 23:39:29 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 7 Nov 2003 22:39:29 -0600 Subject: Problems with regexps References: <87fzgz98vh.fsf@internal.daycos.com> Message-ID: Actually, I misspoke a little. Script-find is fully compatible with re, because re can appear in any script. Anyway, there is nothing particularly wrong with re for simple tasks. So it's not the end of re; it's the end of re for complex tasks for which re just isn't suited. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From duncan at NOSPAMrcp.co.uk Tue Nov 25 06:31:03 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 25 Nov 2003 11:31:03 +0000 (UTC) Subject: Parsing strings -> numbers References: Message-ID: tuanglen at hotmail.com (Tuang) wrote in news:df045d93.0311250127.67395ae at posting.google.com: >>>> locale.getdefaultlocale() > ('en_US', 'cp1252') >>>> locale.atoi("-12345") > -12345 > > Given the locale it thinks I have, it should be able to parse > "-12,345" if it can handle formats containing thousands separators, > but apparently it can't. > > If Python doesn't actually have its own parsing of formatted numbers, > what's the preferred Python approach for taking taking data, perhaps > formatted currencies such as "-$12,345.00" scraped off a Web page, and > turning it into numerical data? > The problem is that by default the numeric locale is not set up to parse those numbers. You have to set that up separately: >>> import locale >>> locale.getlocale(locale.LC_NUMERIC) (None, None) >>> locale.getlocale() ['English_United Kingdom', '1252'] >>> locale.setlocale(locale.LC_NUMERIC, "English") 'English_United States.1252' >>> locale.atof('1,234') 1234.0 >>> locale.setlocale(locale.LC_NUMERIC, "French") 'French_France.1252' >>> locale.atof('1,234') 1.234 Unless I've missed something, it doesn't support ignoring currency symbols when parsing numbers, so you still can't handle "-$12,345.00" even if you do set the numeric and monetary locales. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From gerson.kurz at t-online.de Tue Nov 4 15:43:22 2003 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Tue, 04 Nov 2003 20:43:22 GMT Subject: Mixing generators and recursion References: <3fa808c3.20995000@news.t-online.de> <3FA80AB2.2E4C17EE@engcorp.com> Message-ID: <3fa80eaa.22505703@news.t-online.de> No, it has nothing to do with the pathname. Try this: def f(nested): if not nested: f(True) else: yield 42 for k in f(False): print k Step through it in the mind: - f(False) gets called - it is not nested, so f(True) gets called - it is nested, so should yield 42 - but it doesn't! - instead, you get an empty list. From klappnase at web.de Wed Nov 19 20:21:06 2003 From: klappnase at web.de (klappnase) Date: 19 Nov 2003 17:21:06 -0800 Subject: MP3-Player in Python? References: Message-ID: "Thorsten Pferdek?mper" wrote in message news:... > Hi, > I am currently trying to code a little MP3-Player in Python. I do not try to > do all the decoding stuff in Python, I am just looking for a (more or > less...) platform independent way to play MP3s. I also want to display > information like these stored in the ID3-tag and information like the length > in seconds, the scan frequency etc. > So far, I have found the following solutions, but I am not really happy with > all of them: > > 1. pygame.mixer.music: > Pros: Seems to be very platform independent > Cons: I was not able to get the length in seconds etc. > > 2. tksnack > Pros: Lots of functionality. Really cool. > Cons: Needs Tkinter to run. (I would like to run this without X in > Linux.) > > > If Tkinter is the only problem you have with snack, you actually can run it without X: from Tkinter import Tk import tkSnack r = Tk() r.withdraw()#removes the window from the screen tkSnack.initializeSnack(r) etc... Regards Michael From gandalf at geochemsource.com Thu Nov 27 08:25:04 2003 From: gandalf at geochemsource.com (Gandalf) Date: Thu, 27 Nov 2003 14:25:04 +0100 Subject: SAP DB and Python Message-ID: <3FC5FB30.6080600@geochemsource.com> Hi! Does anyone know how to get a working version of sapdb.dbapi for Python 2.3 and SAP DB 7.4? Apparently, SAP DB 7.4 is the latest but the python module is for Python 1.5. Is there a compiled version around? If not, can I get the source and compile it with MinGW? Thanks, Laci 1.0 From elena.schulz at gmx.net Mon Nov 17 11:35:55 2003 From: elena.schulz at gmx.net (Elena Schulz) Date: Mon, 17 Nov 2003 17:35:55 +0100 Subject: Dictionary problem Message-ID: <004401c3ad28$e6d01700$010aa8c0@PCA> Hi, I've the following code: myList = [] for i in range(3) : myDict['id']=i myList.append(myDict) myList becomes: [{'id':2}, {'id':2}, {'id':2}] but I want: [{'id':0}, {'id':1}, {'id':2}] thanx for any hint how to achieve that -- Greetings, Elena (Please answer to my mail address directly as I am currently not subscribed to this list, thanks) From jjl at pobox.com Sun Nov 2 18:17:39 2003 From: jjl at pobox.com (John J. Lee) Date: 02 Nov 2003 23:17:39 +0000 Subject: PyQt, Qt, Windows and Linux References: <200311021949.34594.phil@riverbankcomputing.co.uk> Message-ID: <87ad7e7430.fsf@pobox.com> Ken Godee writes: [...] > Maybe I'm missing something new here......... > > But as far as I know, you "DO NOT" need to buy a license > from TrollTech or PyQt or buy anything to give it a try, as > long as use is personal and not used in a commercial enviroment. > The only thing is you would have to make do with the older > ver.2.3(?) on windows and many do. [...] Yes: if (you're only using unix/linux) OR (you're happy to stick to Qt 2.x AND you're non-commercial), you don't need a license. They were talking about using Qt 3 on Windows: in that case, you do need a license from both TT and Phil (ie. you need to buy BlackAdder, unless you want to spend large quantities of cash for no reason). John From fredrik at pythonware.com Tue Nov 25 05:36:43 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 Nov 2003 11:36:43 +0100 Subject: Hidden files/folders on Windows References: Message-ID: Antoon Pardon wrote: > Can someone explain how I can check whether a file or > folder is hidden, using python. I have found references > to win32api on the web, which would provide what I need > but I couldn't find the module itself? the python download page on python.org points you to this page: http://starship.python.net/crew/mhammond/ From ulope at gmx.de Sun Nov 9 06:17:39 2003 From: ulope at gmx.de (Ulrich Petri) Date: Sun, 9 Nov 2003 12:17:39 +0100 Subject: how to read in an array in text file? References: Message-ID: "Yun Mao" schrieb im Newsbeitrag news:bokiea$bn00$1 at netnews.upenn.edu... > Hi, what's the easy way of reading in a two-dimentional array from a text > file? > The text file looks like this: > 0.1 1.1 2.3 12.1 > 0.3 33.0 4.1 1.1 > > I'm using Numeric Python now. Other solutions are also welcome. Thanks a > lot! > Yun f = file("myfile", "r") data = [line.split() for line in f] f.close() HTH Ciao Ulrich From noahd at juno.no.spam.com Fri Nov 7 12:40:11 2003 From: noahd at juno.no.spam.com (Mr. Costington) Date: Fri, 7 Nov 2003 11:40:11 -0600 Subject: Writing an image References: <7h3y8usdxsk.fsf@pc150.maths.bris.ac.uk> Message-ID: "Alex Martelli" wrote in message news:pQPqb.107854$e5.3894406 at news1.tin.it... > Michael Hudson wrote: > > > "Mr. Costington" writes: > > > >> Hi all, I was trying to hava a CGI script return an image, but it was > ... > > sys.stdout is not usually a binary-mode file. > > Right; one can change that with the -u switch to python (e.g., starting > the cgi script with > #!c:\python23\python.exe -u > if one's webserver recognizes and applies hashbang conventions). > Thanks. My server ignores hashbangs, but I was able to set sys.stdout to binary-mode with the following line: msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) From peter at engcorp.com Sun Nov 9 16:44:16 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Nov 2003 16:44:16 -0500 Subject: Bad docs for os.path.isabs() References: Message-ID: <3FAEB530.D67D27BC@engcorp.com> Ben Allfree wrote: > > The docs for os.path.isabs() state: > > isabs( path) > > Return True if path is an absolute pathname (begins with a slash). > > This is false becase os.path.isabs("C:\\foo") == True > > It should read: > > isabs( path) > > Return True if path is an absolute pathname (begins with a slash or drive > letter). As Bengt says, that revision is still insufficient/incorrect. Probably the only way it can really be said is something like "returns True if os.path.abspath() would leave the path unchanged". (Or some variation on that... i.e. leave the actual specification to the nuts-and-bolts of the platform-dependent code, rather than trying to rewrite it in English and risk duplication/errors.) -Peter From radam2 at tampabay.rr.com Sun Nov 2 23:47:48 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Mon, 03 Nov 2003 04:47:48 GMT Subject: hex oct int string coversions? References: Message-ID: On Mon, 03 Nov 2003 03:41:16 +0100, "Martin v. L?wis" wrote: >Ron Adam wrote: > >> How do I covert a string hex or oct value to the correct int value? > >http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-41 > >Martin That tells me how to convert an int to a hex or oct string using the hex() and oct() functions, which I already know. The int() function will convert a string to an integer. But it doesn't understand hex or oct from a string., You can type the hex, or oct value as an argument for the int() function on the command line and that works correctly. So there must be a way to do it? Am I missing a step? _Ron From bignose-hates-spam at and-benfinney-does-too.id.au Thu Nov 20 17:01:52 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 21 Nov 2003 08:51:52 +1050 Subject: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com> <3FBC2025.B2A33B6F@alcyone.com> <87d6bncbaj.fsf@einstein.electron.net> Message-ID: On 21 Nov 2003 08:50:14 +1050, Ben Finney wrote: > On 20 Nov 2003 16:25:08 +0100, Curt wrote: >> curty at einstein:~$ man uniq >> >> NAME >> uniq - remove duplicate lines from a sorted file > > Your OS needs a better 'man uniq', since that description doesn't say > what the expected behaviour is with unsorted input. The GNU 'man uniq' > doesn't mention sorted input, but applies to any input. Bah, I spoke too soon; you're looking only at the 'NAME" section. Read the 'DESCRIPTION' section and I'll bet it's clear what happens on unsorted input. -- \ "I went to court for a parking ticket; I pleaded insanity. I | `\ said 'Your Honour, who in their right mind parks in the passing | _o__) lane?'" -- Steven Wright | Ben Finney From tweedgeezer at hotmail.com Mon Nov 10 05:26:35 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 10 Nov 2003 02:26:35 -0800 Subject: Bad docs for os.path.isabs() References: Message-ID: <698f09f8.0311100226.11ae3076@posting.google.com> "Ben Allfree" wrote in message news:... > The docs for os.path.isabs() state: > > isabs( path) > > Return True if path is an absolute pathname (begins with a slash). > > This is false becase os.path.isabs("C:\\foo") == True > > It should read: > > isabs( path) > > Return True if path is an absolute pathname (begins with a slash or drive > letter). Since no one's mentioned it yet, this is something you should file as a bug on SF.net. Jeremy From claird at lairds.com Wed Nov 12 14:03:29 2003 From: claird at lairds.com (Cameron Laird) Date: Wed, 12 Nov 2003 19:03:29 -0000 Subject: a python book hint References: Message-ID: In article , Alex Martelli wrote: >Eduardo Patto Kanegae wrote: . . . >Hetland's "Practical Python" is a good book, particularly if you like >_meaty_ examples (my own "Python in a Nutshell" has less purely tutorial >material, and the examples are small, illustrating single simple points; >thus, it's more of a "concise desktop reference" than an introduction). > >Most other books are unfortunately a bit dated, but these two do cover >Python 2.2 (and the current 2.3 has basically no language-level changes >wrt to 2.2 -- it's mostly faster and more robust, with small additions >to the built-ins and more substantial ones to the standard library). . . . David's book is as current as any, but lacks the GUI-for-Windows emphasis the original poster ap- parently wishes. David Mertz, that is, not David Ascher. If this were a voice posting it'd be obvious. -- Cameron Laird Business: http://www.Phaseit.net From mathew at yeates.tv Tue Nov 25 14:03:36 2003 From: mathew at yeates.tv (Mathew) Date: Tue, 25 Nov 2003 19:03:36 GMT Subject: looking for 2.1.3 Windows binary with large file support Message-ID: the version that is distributed with Zope/Plone does not handle large files. TIA Mathew From max at alcyone.com Wed Nov 5 17:06:09 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 05 Nov 2003 14:06:09 -0800 Subject: Template-engine References: Message-ID: <3FA97451.71395463@alcyone.com> Miika Keskinen wrote: > I was in need for a simple template engine (like PEAR::IT.php) and > didn't > find any suitable. Yes, there is many templating engines available but > most are far too complex or does implement some additional features in > their syntax. EmPy has a lot of additional features, but they're all optional. Basic use of EmPy for templating is as lightweight, if not more, as your approach: http://www.alcyone.com/software/empy/ -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I just don't know why they're shooting at us. \__/ Capt. Benjamin "Hawkeye" Pierce From belred1 at yahoo.com Fri Nov 28 17:57:42 2003 From: belred1 at yahoo.com (Bryan) Date: Fri, 28 Nov 2003 22:57:42 GMT Subject: newbie : using python to generate web-pages In-Reply-To: References: Message-ID: Rene Pijlman wrote: > biner: > [Generating HTML] > >> Is there anything like that in Python. > > > "Python does not come with tools to generate HTML. If you want an advanced > framework for structured HTML generation, I recommend Robin Friedrich's > HTMLGen 2.2 (available at > http://starship.python.net/crew/friedrich/HTMLgen/html/main.html), > [...] > If your favorite approach is to embed Python code within HTML in the > manner made popular by JSP, ASP, and PHP, one possibility is to use Python > Server Pages (PSP) as supported by Webware, mentioned in Chapter 20. > Another package, focused more specifically on the embedding approach, is > Spyce (available at http://spyce.sf.net/). > [...] > For advanced templating tasks, I recommend Cheetah (available at > http://www.cheetahtemplate.org)." > > Source: Python in a Nutshell By Alex Martelli > http://safari.oreilly.com/0596001886/pythonian-CHP-22-SECT-4 > > Based on this recommendation I've just started using Cheetah. It looks > like a great tool to me. > http://www.cheetahtemplate.org/ > i also recommend looking at cheetah. i used it for a project at work and it was great. bryan From tismer at tismer.com Sat Nov 15 21:36:05 2003 From: tismer at tismer.com (Christian Tismer) Date: Sun, 16 Nov 2003 03:36:05 +0100 Subject: No limit! (was: pickle complexity limit?) In-Reply-To: References: Message-ID: <3FB6E295.2060005@tismer.com> Martin v. L?wis wrote: > "Mark Hahn" writes: > > >>I don't understand how this could happen with pickle. Isn't it supposed to >>stop when it runs into an object it has already pickled? > > Yes, and it does. > >>Couldn't it have been coded in a stackless way? > > Yes, but it doesn't. Please look at save_inst implementation; it ends > with > > save(stuff) > write(BUILD) > > This is where the recursion happens. You run into the limit only if > you can find a path through your object graph that does not visit the > same object twice. > >>What do I do now? I don't want to recompile with a deeper stack as this >>will obviously only help in limited cases, not solve the real problem. There are limitations, and there are ways to cope with them. See below. > Read the pickle code, understand why it is recursive, and implement an > alternative that isn't recursive, yet preserves the original semantics > in terms of pickling order and sequence in which methods are called on > objects. When you are done, please contribute your changes back, to > sf.net/projects/python. The reason why pickling is recursive was of course a thing that I never really understood. For me, this is a bit like asking for problems. But well, the same was true with recursive destructors of objects, until I came up with the Py_Trashcan structure. It has been changed very much, but the idea is still alive: try to limit recursions as much as possible. Back to your problem: You have a chance to avoid recursions. I had the same problem with Stackless. I support pickling of frame chains to any extent, together with tracebacks. The recursion problems would be there, if I didn't take some action. ANd for Stackless, these problems are in fact harder, since it doesn't have any restriction in recursion depth by nature. Let me give you an example from my recent efforts: For Stackless, I implemented pickling of frames and tracebacks, besides many others. With the standard approach of pickling them as they come, I would have got into recursion problems. Although I got different advice of Armin Rigo ("do it right, trash the pickler and build a stackless engine for it"), I didn't, since I'm not trying to convince the stack-bound heads any longer. I will do that for PyPy, when the time has come. Keeping the current recursive pickling engine, I did this for pickling of Tasklets, which are just small header objects for frame chains: Frames are pickled alone. They don't care about their f_back field, therefore not introducing any recursive calls. Tasklets are frame chains. They know which frames they contain. And instead of causing recursions, tasklets simply build a list of all the frames they need to be pickled, and exactly that will happen, in an iterative manner. Analogously it works with tracebacks, which also can show very serious nesting. The problem with tracebacks is a bit harder than with tasklets, since they don't have the tasklet serving like a header. Therefore, I added a flag to tracebacks, which marks the leading traceback object. That is, this leading one will pickle all the other ones into a list, again avoiding deep recursions. The trick was to modify PyTraceBack_Here to tag the leading traceback object. Under the (reasonable) assumption that this leading traceback object will show up in your pickle, things work very smoothly. If you want to know about how to pickle certain stuff, download the Stackless CVS and have a look. There is support for pickling tasklets, frames, code objects, iterators, tracebacks, and some more to come. The most straight forward thing for you to look into would probably be tracebackobject.c . CVSROOT=:pserver:anonymous at centera.de:/home/cvs export CVSROOT cvs co stackless cheers - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From google.com.112139 at satilla.com Fri Nov 21 13:23:00 2003 From: google.com.112139 at satilla.com (Eric Baker) Date: Fri, 21 Nov 2003 13:23:00 -0500 Subject: small, fast and cross-platform flat-file database for python References: <425cc8d1.0311210915.33eb10e0@posting.google.com> <3FBE4940.BD960E76@engcorp.com> Message-ID: <4Ksvb.20$pr5.692@eagle.america.net> "Peter Hansen" schrieb im Newsbeitrag news:3FBE4940.BD960E76 at engcorp.com... > mir nazim wrote: > > > > i want to know if there is any flat-file relational database system > ^^^^^^^^^ ^^^^^^^^^^ > > I'm no database expert, but aren't these two terms contradictory in > some important way? > > -Peter Depends what your definition if the word "is" is :) In my early perl days, i used a simple text file based SQL "database". http://search.cpan.org/~shgun/Sprite-3.21/Sprite.pm Now with Python, i would probably use SQLite, which isnt exactly a "flat text file", but still a nice lightweight database for *nix and win32 IMHO. http://www.hwaci.com/sw/sqlite/ Eric From theller at python.net Thu Nov 13 05:45:54 2003 From: theller at python.net (Thomas Heller) Date: Thu, 13 Nov 2003 11:45:54 +0100 Subject: can't run py app after compile to exe by py2exe , gettext References: <43e3984e.0311120110.2bea96cc@posting.google.com> <43e3984e.0311121700.1a7e642e@posting.google.com> Message-ID: ulysses_dm at yahoo.com.cn (ulysses) writes: > I do a small test app for this. Still can't run. > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > full source package > please download from > > http://211.90.187.42/ourbt/gettexttest.rar > > you test in in your computer. Thanks. I tried it, and it seems you have to make sure that the en.mo file is in the same directory as the exe, and you have to manually include the 'encodings' package - there's a command line switch for that. To help to find these types of problems, it's always useful to build the exe as a console version first with the --console command line flag to py2exe. There's no way for the --windows exe to notify you of the tracebacks. And if you want to try the 0.5.0 version of py2exe (which requires Python 2.3), here is the setup script you would use: """ from distutils.core import setup import py2exe setup(name='testgettext', options = {"py2exe": {"packages": ["encodings"]}}, windows = ['main.py'], data_files = [("", ["en.mo"])], ) """ The latest py2exe 0.5.0 creates windows programs in such a way that tracebacks are routed into a log file (that would be 'main.exe.log' in the above case), and even displayes a message box when the program ends pointing the user to the logfile. Thomas From jjl at pobox.com Sun Nov 9 11:26:49 2003 From: jjl at pobox.com (John J. Lee) Date: 09 Nov 2003 16:26:49 +0000 Subject: ANN: PyKDE now does KDE plugins References: <87sml01hgc.fsf@pobox.com> <87llqrgiva.fsf@pobox.com> <9y9rb.3612$xr.997430341@twister2.starband.net> <87wuaainlg.fsf@pobox.com> <6Ilrb.3754$yd6.1052428423@twister2.starband.net> Message-ID: <87oevlfqye.fsf@pobox.com> Jim Bublitz writes: > John J. Lee wrote: > > > Have you seen GCC-XML and pyste (part of Boost Python)? > > I've looked at both just out of curiousity, but not in enough > detail to say anything intelligent about either. I'm very > comfortable with sip, and from that bias didn't see anything > that would make me want to switch methods. [...] I was thinking of it as a way to generate sip files, not to replace sip. John From dw-google.com at botanicus.net Sun Nov 9 19:47:29 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 9 Nov 2003 16:47:29 -0800 Subject: Rekall and associated software go 100% GPL References: <3fae9c76$0$12714$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <99dce321.0311091647.3e9e8165@posting.google.com> "John Dean" wrote in message news:<3fae9c76$0$12714$fa0fcedb at lovejoy.zen.co.uk>... > It gives me great pleasure to inform you that Rekall, the cross-platform > alternative to MS Access, is now totally GPL. What is TheKompany's stance on this? Did you come to an amicable agreement before release? > So please visit > http://www.totalrekall.co.uk and download download a copy for yourself. In > order for you to be able to download you must register with the Total Rekall > Portal. The reason we have have made this a requirement is because we would > like to be able to notify everybody when a new version becomes available. I'm sure you are aware, that this is unenforcable under the GPL. People are free to redistribute without registration requirements. It is also interesting to see that after going to great (and controversial) lengths to give your users more freedom through this new license, you apply this 'petty' restriction of registration and mandatory notifications of new releases. This seems a little contradictory to me, 'sall. David. From logan at phreaker.nospam Fri Nov 28 14:53:16 2003 From: logan at phreaker.nospam (Logan) Date: Fri, 28 Nov 2003 20:53:16 +0100 Subject: Tkinter question References: <3FC79B0B.B9ED8894@mdstud.chalmers.se> Message-ID: On Fri, 28 Nov 2003 19:59:23 +0100, Ali El Dada wrote: > i am using Tkinter in my application, and i have a button > that, when clicked, opens a new window as in: > > b1 = Button(someframe, text="bla", command = someFunction) > > def someFunction(): > newWindow = Toplevel() > '''the new window widgets go here''' > > of course, whenever the button is clicked, a new window > opens. what do you recommend as a neat way to allow only one > window to open?? It depends on what kind of behavior you want: if newWindow is e.g. a dialog (like 'find', 'find & replace' etc. in an editor), you want the new window to pop up, but any older dialog should get destroyed. To achieve this, you can make newWindow a *global variable* and use e.g. the following (not very elegant, but it works): # here, the 'find'-dialog is created (e.g. inside some class) try: newWindow.destroy() except: pass newWindow = Toplevel() # widgets for the 'find'-dialog # here, the 'find&replace'-dialog is created (e.g. inside some class) try: newWindow.destroy() except: pass newWindow = Toplevel() # widgets for the 'find&replace'-dialog If you want, that your window gets created only once (and whenever such a window is already open, no new window should be created) you could either use an approach similar to the one above (i.e. with newWindow being a global variable) or e.g. use a class which keeps track on how many instances of itself were already created and which behaves accordingly (Google: python, singleton). There are other solutions, too. The 'right' solution for you depends mainly on the design of your whole program (OO or not etc.). HTH, L. -- mailto: logan at phreaker(NoSpam).net From jepler at unpythonic.net Sat Nov 29 10:00:36 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 29 Nov 2003 09:00:36 -0600 Subject: Tkinter "Expected boolean value" In-Reply-To: References: Message-ID: <20031129150036.GC28350@unpythonic.net> You'd do better with tk8.3 than 8.4. There were some incompatible changes in Tk 8.4's "bind" command that cause Python problems. I'm not sure in what version of Python this problem is fixed. As for your 'expected boolean value' problem, there's not enough information for me to guess the cause. It's not something I've heard of before. If you want help, your best bet would be to post a small program that is runnable and demonstrates the problem. Jeff From oliver.walczak at momatec.de Fri Nov 28 04:34:24 2003 From: oliver.walczak at momatec.de (Oliver Walczak) Date: Fri, 28 Nov 2003 10:34:24 +0100 Subject: Buffer restriction in dom.minidom? Message-ID: Dear list, In one of my projects i use dom.minidom as XML parser. I recently had a problem when the value of a text node as a child of an element node was larger than 1024 characters. It created 2 or more child nodes out of it so i had to concatenate both items again manually. On another machine it only created one child node out of the text node as i further expected although both are running Python 2.2.3 on WinXP. Does anyone know whats going on there? Best regards Oliver From robin at jessikat.fsnet.co.uk Sat Nov 8 08:52:15 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 8 Nov 2003 13:52:15 +0000 Subject: Tk version changes Message-ID: I have some tkinter code that used to work in 2.2, but is failing in 2.3. I guess it's because the Tcl version is different. Looking in the text.tcl file I see that we now have ::tk::Priv and ::tk::TextClosestGap. I can get this to work reasonably in 2.3.2, but how should I make this kind of code version independent? Should I rely on the python version or attempt to check which variables are present in Tk? If the latter does anyone know which version of Tk this changed? def _textB1(self,event): '''special binding for our disabled texts Allows dragging to select and copy, but not editing ''' w, x, y = event.widget, event.x, event.y call = w.tk.call call('set','::tkPriv(selectMode)','char') call('set','::tkPriv(mouseMoved)',0) call('set','::tkPriv(pressX)',x) call('set','::tkPriv(pressX)',x) w.mark_set('insert',call('tkTextClosestGap',str(w),x,y)) w.mark_set('anchor','insert') w.focus() w.tag_remove('sel','0.0','end') return 'break' -- Robin Becker From mwilson at the-wire.com Wed Nov 19 16:43:26 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 19 Nov 2003 16:43:26 -0500 Subject: Using 'string.ljust' to try and hold a fixed width....... References: <2c82369d.0311190538.3789f2a1@posting.google.com> <2c82369d.0311191041.e5b1fa6@posting.google.com> Message-ID: <+P+u/ks/KbFI089yn@the-wire.com> In article <2c82369d.0311191041.e5b1fa6 at posting.google.com>, John_Dutcher at urmc.rochester.edu (John F Dutcher) wrote: >In my CGI script where I retrieve 'form' data nothing works.. >The use of a string to receive the form field first, and >then appending to 'recd'...or appending to 'recd' directly, both fail >to preserve the spaces....(which are preserved very well in the >IDLE mode using a string literal to start with, rather than 'form' data). > > >recd = [] >lname = string.ljust(form.getfirst("lname",' '),15) >fname = string.ljust(form.getfirst("fname",' '),15) > >recd.append(lname) >recd.append(fname) > >recstr = string.join(recd,'') >print recstr ------------------> no ending spaces Are you viewing your CGI program's output with an HTML browser? Regards. Mel. From tim.hochberg at ieee.org Tue Nov 4 13:10:31 2003 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Tue, 04 Nov 2003 11:10:31 -0700 Subject: breaking iteration of generator method In-Reply-To: References: Message-ID: Brian wrote: > Hello; > > What happens when a program breaks (think keyword 'break') its iteration > of a generator? Is the old state in the generator preserved? > > Ex: > > # .gen() is generator method. > > for i in myObject.gen(): > if i == specialValue: > break > > Do subsequent calls to .gen() start off with new locals? It depends on how you do it. This:: for i in myObject.gen(): if i == specialValue: break # ... for i in myObject.gen(): if i == otherSpecialValue: break # ... Will start start with a new generator with new local each time since each call to gen() creates a fresh generator. If you want to preserve generator state between loop, what you do is:: generator = myObject.gen() for i in generator: if i == specialValue: break # ... for i in generator: if i == otherSpecialValue: break # ... In this case, the same generator is used in each loop and the state is preserved. -tim > Or, would > the iteration begin after the yielded 'i' that caused the for-statement > to exit? > > > Many thanks, > > Brian. From bucodi at wanadoo.fr Tue Nov 25 05:33:40 2003 From: bucodi at wanadoo.fr (Rony Steelandt) Date: Tue, 25 Nov 2003 11:33:40 +0100 Subject: Hidden files/folders on Windows References: Message-ID: Win32file.GetFileAttributesEx Rony "Antoon Pardon" a ?crit dans le message de news: slrnbs6a04.l1h.apardon at trout.vub.ac.be... > Can someone explain how I can check whether a file or > folder is hidden, using python. I have found references > to win32api on the web, which would provide what I need > but I couldn't find the module itself? > > Thanks in advance! > > -- > Antoon Pardon From R.Byrom at rl.ac.uk Wed Nov 26 08:15:29 2003 From: R.Byrom at rl.ac.uk (Byrom, R (Rob) ) Date: Wed, 26 Nov 2003 13:15:29 -0000 Subject: problems with popen (linux7.3 python2.2.2) Message-ID: hi, When I use: os.popen('ssh -l root at something tomcat4 stop') I find the command always hangs. The 'something' host contains the correct key in the authorized_hosts file and works ok on the command prompt. I've tried os.system() but this also hangs. I notice that the 'tomcat4 stop' is being executed but when I do a 'ps -ef' I notice the popen process is still alive. I've also noticed this command sometimes works (ie it doesnt hang) but I've no idea why. Has anyone experienced similar problems with this? Or does anyone have any alternative suggestions? I'm really at my wits end with this one! thanks alot, Rob From http Wed Nov 19 20:02:16 2003 From: http (Paul Rubin) Date: 19 Nov 2003 17:02:16 -0800 Subject: Python's simplicity philosophy References: <3FAC19F0.284DCB03@alcyone.com> <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <7xoevcf1u2.fsf@ruckus.brouhaha.com> <7xznesm1l8.fsf@ruckus.brouhaha.com> Message-ID: <7xznerrgx3.fsf@ruckus.brouhaha.com> "Andrew Dalke" writes: > needed yours. And I've used what can now be > written as > > unique_keys = dict.from_keys(lst).keys() This from_keys operation must be something new, and consing up a dictionary like that is a woeful amount of overhead. But I guess it would do the job. From jegenye2001 at fw.hu Wed Nov 12 16:52:43 2003 From: jegenye2001 at fw.hu (Jegenye 2001 Bt) Date: Wed, 12 Nov 2003 22:52:43 +0100 Subject: Python programmers required (High tax free savings package) References: <3fb2a615.67745913@news.cybermesa.com> Message-ID: Jay O'Connor wrote in message news:3fb2a615.67745913 at news.cybermesa.com... > On Wed, 12 Nov 2003 22:26:50 +0100, "Jegenye 2001 Bt" > > > >tglinternational wrote in message > >news:mailman.655.1068634052.702.python-list at python.org... > >> Please check details on www.tgl-international.com/jobs.html Send > >> your CV / resumes alongwith covering letter to steve at tgl- > >> international.com > >> > >Huh, they have to really pay a lot so that one would work in the Saudi > >Arabian desert... ;) > > If a telecommute would be possible, I'd jump on it. But relocation to > Dhahran is probably not in my career path these days > Hey, you want to take the easy way out.. ;-) Well, if telecommute would be possible then they wouldn't advertise this job at all.. :D Mikl?s From helterskelter482000 at yahoo.com Sat Nov 15 12:11:47 2003 From: helterskelter482000 at yahoo.com (Evan Patterson) Date: Sat, 15 Nov 2003 09:11:47 -0800 (PST) Subject: Tuple to list? Message-ID: <20031115171147.97178.qmail@web60401.mail.yahoo.com> How do you convert a tuple to a list? Thanks in advance. --------------------------------- Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard -------------- next part -------------- An HTML attachment was scrubbed... URL: From missive at frontiernet.net Tue Nov 4 15:56:11 2003 From: missive at frontiernet.net (Lee Harr) Date: Tue, 04 Nov 2003 20:56:11 GMT Subject: Pygame and TKinter References: Message-ID: > I need buttons, text inputs, and scrolling text output. All I've found is the > text input from the pygame code repository site. Rather than make my own > widgets I am planning to have one window for the mpeg viewer and one for the > rest of the GUI (although one window would be better). > > Can you point me to any source code for buttons, or a scrolling textbox? > http://savannah.nongnu.org/projects/pygsear/ From try_vanevery_at_mycompanyname at yahoo.com Mon Nov 10 17:16:38 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Mon, 10 Nov 2003 14:16:38 -0800 Subject: What do you think of this Python logo? Message-ID: What do you think of this Python logo? http://pythonology.org/logos Good, bad, indifferent, love it, hate it? -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA Brandon's Law (after Godwin's Law): "As a Usenet discussion grows longer, the probability of a person being called a troll approaches one RAPIDLY." From wester at ilt.fraunhofer.de Thu Nov 6 03:02:00 2003 From: wester at ilt.fraunhofer.de (Rolf Wester) Date: Thu, 06 Nov 2003 09:02:00 +0100 Subject: C STDOUT -> IDLE? (Windows) Message-ID: Hi, I have some C-extension that write to C-STDOUT. When running python in IDLE (under Windows) IDLE doesn't show the output of the C-extensions. Is there a (simply?) way to get the extensions output displayed in IDLE? Thanks in advance. Regards Rolf Wester From martin at v.loewis.de Sat Nov 22 07:11:16 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 22 Nov 2003 13:11:16 +0100 Subject: Problems sending list/tuple to a C extension. References: Message-ID: seberino at spawar.navy.mil (Christian Seberino) writes: > python.org docs seem to suggest that sending in lists and tuples > was as simple as changing string in PyArg_ParseTuple to contain > parens or brackets.... What documentation are you specifically referring to? PyArg_ParseTuple does not support square brackets. Regards, Martin From __peter__ at web.de Sun Nov 2 07:56:14 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Nov 2003 13:56:14 +0100 Subject: None References: Message-ID: Daniel Sch?le wrote: > def executer(func, para): > func(para) > > def foo(): > print "function without parameter" > > def bar(a): > print "function with 1 parameter" > print a > > #executer(foo, None) #error > > executer(bar, 100) [...] > is there a way to allow parameterless functions as parameter in executer? You can change executer() to accept and pass and arbitrary number of arguments: def executer(func, *args): func(*args) executer(bar, 100) executer(foo) However, excecuter(foo, None) will still fail. See http://www.python.org/doc/current/tut/node6.html for the details. As an aside, do the newsgroup - and yourself - a favour and increase your block indent to 4 spaces. Peter From adalke at mindspring.com Thu Nov 13 16:13:08 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 13 Nov 2003 21:13:08 GMT Subject: Palindrome References: <20031112223135.29045.00000109@mb-m12.aol.com> <3FB3C016.56BCA546@hotmail.com> Message-ID: Alan Kennedy: > I'm not too happy with it though. There must be some way to have a > single fixed regular expression that can be used to test every > palindrome. There isn't such a way. Regular expressions cannot match strings of the form a**n b**n a**n (pumping lemma). That's a palindrome so there are palindromes which cannot be matched by regular expressions. There are tricks. "regular expressions" aren't actually regular and can be used to match things like a**n b**m a**n (because of the \1 feature). However, there still isn't enough to match a palindrome of arbitrary length. (It would be trivial to add such a feature -- let \~1 match the reverse of the first match then ^(.*).?\~1$ would match all palindromes... slowly. But no such feature exists in any regexp engine I know of.) Andrew dalke at dalkescientific.com From newsgroups at jhrothjr.com Mon Nov 17 17:11:55 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 17 Nov 2003 17:11:55 -0500 Subject: Origin of the term "first-class object" References: <8ef9bea6.0311171335.356a7af6@posting.google.com> Message-ID: "Hung Jung Lu" wrote in message news:8ef9bea6.0311171335.356a7af6 at posting.google.com... > Hi, > > Does anybody know where this term comes from? > > "First-class object" means "something passable as an argument in a > function call", but I fail to see the connection with "object class" > or with "first-class airplane ticket". I just find the name a bit > strange. Also, if there are first-class objects, what would the > second-class objects or economy/tourist class objects be? :) > > Just wondering, I'm not sure who started to use it, but to me it means that there are no restrictions on the object's use. It's the same as any other object. I'm also not sure what being able to pass it in a function call has to do with it; I'm used to being able to use them in a lot of other ways. For example, in Python both classes and functions are objects (there are no second class citizens in Python...) This means that I can rebind a class object into another module at run time, and access it under its new name. I can thow functions around with wild abandon, and even add attributes to them for some meta-data scheme, for example. In Java, neither classes nor methods are first class objects, even though you can get a "class" object if you ask politely, it's simply a special construct for the reflection mechanism. In C++, neither is an object, first class or not. John Roth > > Hung Jung From srinathava_news at yahoo.com Fri Nov 7 22:43:44 2003 From: srinathava_news at yahoo.com (Srinath Avadhanula) Date: Fri, 7 Nov 2003 19:43:44 -0800 Subject: GUI toolkit selection for a text editor widget Message-ID: Hello, Sorry to be bringing up what seems to be a somewhat beaten up topic... This is what I wanted to do: Create a _simple_ text editor widget which supports VI(M) style keybindings but works with arbitrary fonts/unicode characters. Vi(m) unfortunately, does not support Devanagari (or proportional fonts) and it looks like it will take quite some time for these things to work. As and when Vim supports Devanagari on Windows, I will give up this effort. My current aims are: 1. Simple Vi(m) style keybindings. 2. Syntax highlighting for arbitrary files based on Vim-style syntax highlighting definitions. Vim defines syntax highlighting for files based on a very flexible regexp style approach. Thus you can define syntax hightlighting for new file types just by writing some regexps. 3. Should be able to load/edit files written in unicode. 4. Macro capability. 5. I want to implement this purely in python. 6. Should work on windows. 7. I do not really care much about speed/looks etc as long as the thing is functional. The choice of the GUI toolkit is therefore almost exclusively depends on how these conditions can be met. This is my take so far: 1. PyQT: Unfortunately, the qtext module which extends the scintilla module to QT is available only under a commercial license for windows. The QMultiLineEdit widget does not support any text styling at all. Hence PyQT seems to be ruled out straight away. 2. wxPython: The wxStyledTextCtrl widget showed great promise. It has almost everything one would wish for. Except for a _major_ bug while editing unicode. The text caret which shows where the text insertion will happen is offset from the actual insertion point in complex scripts like devangari or arabic. This looks like its a problem with calculating text extents. Robin Dunn has acknowledged this bug, but unfortunately, unless there is a workaround, I cannot do anything with wxStyledTextCtrl at all. wxPython also has wxTextCtrl which has far lesser features than wxStyledTextCtrl, but at least does not have the bug with the text caret. Unfortunately, it looks like it does not provide some necessary functions. For one, if I desire to do syntax highlighting based on it, I would need to find out the current range of text displayed in the window. But I couldn't find any way of finding out which lines are actually displayed. The various wxScrollBar functions (which wxTextCtrl inherits) do not give useful information. 3. Tkinter: I looked briefly at Tkinter and the Text widget looked very impressive indeed! It looks like the way it highlights text is even more powerful than Vim in that each character (or range) has multiple "tags" associated with it and the most recent tag takes precedence. This looks like something which might be very handy. It even supports inserting bitmaps etc. All in all, very neat looking. But there seems to be some limitations: 1. How do I recognize control key inputs? I tried self.bind('', function) but how to find out if CTRL-a has been pressed in the function. When I ran a simple app, event.char reports 'a' when I press CTRL-A. So does event.keysym and event.keycode... wxPython has something called event.ControlDown() for keyEvents... 2. There seems to be a problem with displaying unicode which Text suffers from too :( The problem is not as severe as the one wxStyledTextCtrl suffers from and it looks like it can be "lived with". When moving over certain "composing character" strings in unicode, the caret seems to move _between_ the characters. Ideally, each sequence of composing characters would be considered a single "glyph"... I will elaborate if someone needs clarification. 3. Although the Text widget itself is powerful, from what I gather in this newsgroup and on the web, Tkinter does not provide things like a tree control widget which might be essential later on. This looks like something which can be worked around, because idle, the editor provided with Python 2.3 seems to have all these things constructed using the basic primitives... Infact, I am wondering whether I should just modify Idle to accept Vi style key-bindinds... I would greatly appreciate any comments. Thank you, Regards, Srinath From tzot at sil-tec.gr Wed Nov 19 06:03:46 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 19 Nov 2003 13:03:46 +0200 Subject: Conversion of 24bit binary to int References: <3FB0FC09.BEFB0D95@engcorp.com> Message-ID: On Wed, 12 Nov 2003 10:53:17 +0100, rumours say that Idar might have written: >But if you know how to convert this format (the file is about 6MB) >effeciently, pls do give me a hint. The data is stored binary with the >format: >Ch1: 1536B (512*3B) >.. >Ch6 1536B (512*3B) >Then it is repeated again until end: >Ch1 1536B (512*3B) >.. >Ch6 1536B (512*3B) So it's some audio file with 6 channels, right? (I missed the first post) I would take every chunk of 512*3 bytes, and for every 3 bytes, struct.unpack('i', _3_bytes+'\0')[0] is the 32bit value (assuming Intel's little endianness). Hope this helps (no, really :) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From jack at performancedrivers.com Tue Nov 4 15:11:32 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Tue, 4 Nov 2003 15:11:32 -0500 Subject: nearest neighbor in 2D In-Reply-To: ; from jdhunter@nitace.bsd.uchicago.edu on Tue, Nov 04, 2003 at 01:02:36PM -0600 References: Message-ID: <20031104151131.D22751@localhost.localdomain> On Tue, Nov 04, 2003 at 01:02:36PM -0600, John Hunter wrote: > >>>>> "Ron" == Ron Adam writes: > > Ron> I really don't know how you can make this faster. There > Ron> might be a library that has a distance between two points > Ron> function that could speed it up. > > If you only had to compare one point to all the other points, then the > brute force approach -- check every point -- will work great. This is > O(N) and I don't think you can beat it. The idea is that I will be > repeatedly checking and adding points to the list, so it is worthwhile > at the outset to set up a data structure which allows a more efficient > search. > > The analogy is a binary search in 1D. If you plan to repeatedly > search a (possibly growing) list of numbers to see whether it contains > some number or find the nearest neighbor to a number, it is worthwhile > at the outset to put them in a data structure that allows a binary > search. Setting up the initial data structure costs you some time, > but subsequent searches are O(log2(N)). See google for 'binary > search' and the python module bisect. > > So roughly, for a list with 1,000,000 elements, your brute force > approach requires a million comparisons per search. If the data is > setup for binary search, on average only 13-14 comparisons will be > required. Well worth the effort if you need to do a lot of searches, > as I do. > > John Hunter Breaking into the thread late, I've been busy enough to put down c.l.py for a couple weeks. If you only need to compare 10-1000 points, try this approach below. I wrote it for the ICFP programming contest where I was sorting lots and lots of points lots and lots of times. It sorts a list of points for their manhattan distance from a particular point. I tweaked it until it was just fast enough to do what I wanted. I won't pretend it is optimal for all N, just that it was good enough for _my_ N. The speed trick is that the point we are sorting around is stored in an object that is created only once, and then we make the object's __call__ be the comparison function. Since it uses the list.sort() method we don't have to do anything more clever than write our comparison function in C. I trust the Timbot has written a better list.sort() than I ever will, so let's use it. it is used thusly: import icfp l = [your big list of point tuples like (1, 10)] p = (99, 22) # find nearest point in l to p sort_ob = icfp.manhattan_sort(p) # creates a callable Manhat object that remembers p l.sort(sort_ob) # sorts around p print "closest", l[0] print "farthest", l[-1] The below code is from my CVS tree, so it should probably work. It was written in a rush for a contest (JDH, you may recognize parts that are cut-n-pasted from "probstat") so YMMV. -jack NB, if there is a boost or pyrex guy listening you might want to throw in an easilly derived class that makes this [ab]use of __call__ easy. It was a big performance win for me for very little effort. """ icfp_module.c """ #include "Python.h" #include #include /* * stats module interface */ static PyObject *ErrorObject; PyObject *manhat_new(PyObject *self, PyObject *args); static PyTypeObject Manhat_Type; static PyObject * heur1(PyObject *self, PyObject *args) { PyObject *tup1; PyObject *tup2; long x,y; if (!PyArg_ParseTuple(args, "O!O!", &PyTuple_Type, &tup1, &PyTuple_Type, &tup2)) { return NULL; } x = PyInt_AsLong(PyTuple_GET_ITEM(tup1,0)) - PyInt_AsLong(PyTuple_GET_ITEM(tup2,0)); y = PyInt_AsLong(PyTuple_GET_ITEM(tup1,1)) - PyInt_AsLong(PyTuple_GET_ITEM(tup2,1)); return PyInt_FromLong(labs(x * x) + labs(y * y)); } static PyMethodDef stats_methods[] = { {"manhattan", heur1, METH_VARARGS}, {"manhattan_sort", manhat_new, METH_VARARGS}, {NULL, NULL} /* sentinel */ }; DL_EXPORT(void) initicfp(void) { PyObject *m, *d; PyPQueue_Type.ob_type = &PyType_Type; Manhat_Type.ob_type = &PyType_Type; /* Create the module and add the functions */ m = Py_InitModule("icfp", stats_methods); /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); ErrorObject = PyErr_NewException("icfp.error", NULL, NULL); } """ manhattan.c """ #include "Python.h" #include #define ManhatObject_Check(v) ((v)->ob_type == &Manhat_Type) staticforward PyTypeObject Manhat_Type; typedef struct { PyObject_HEAD long x; long y; } ManhatObject; static void Manhat_dealloc(ManhatObject *self) { PyObject_Del(self); } static PyObject * Manhat_call(ManhatObject *self, PyObject *args) { PyObject *tup1; PyObject *tup2; long a; long b; long x; long y; if (!PyArg_ParseTuple(args, "O!O!", &PyTuple_Type, &tup1, &PyTuple_Type, &tup2)) { return NULL; } x = PyInt_AsLong(PyTuple_GET_ITEM(tup1,0)) - self->x; y = PyInt_AsLong(PyTuple_GET_ITEM(tup1,1)) - self->y; a = labs(x * x) + labs(y * y); x = PyInt_AsLong(PyTuple_GET_ITEM(tup2,0)) - self->x; y = PyInt_AsLong(PyTuple_GET_ITEM(tup2,1)) - self->y; b = labs(x * x) + labs(y * y); if (a == b) return PyInt_FromLong(0); else if (a < b) return PyInt_FromLong(-1); else return PyInt_FromLong(1); } static PyMethodDef Manhat_methods[] = { {NULL, NULL} /* sentinel */ }; statichere PyTypeObject Manhat_Type = { /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ PyObject_HEAD_INIT(&PyType_Type) 0, /*ob_size*/ "Manhat", /*tp_name*/ sizeof(ManhatObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)Manhat_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, //(setattrfunc)Permute_setattr, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ (ternaryfunc)Manhat_call, /*tp_call*/ 0, /*tp_str*/ PyObject_GenericGetAttr, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ Manhat_methods, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ 0, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ }; // not static so ifcp_module.c can see it PyObject * manhat_new(PyObject *self, PyObject *args) { ManhatObject *mh; PyObject *tup1; if (!PyArg_ParseTuple(args, "O!", &PyTuple_Type, &tup1)) { return NULL; } // call object create function and return mh = PyObject_New(ManhatObject, &Manhat_Type); if (mh == NULL) return NULL; mh->x = PyInt_AsLong(PyTuple_GET_ITEM(tup1,0)); mh->y = PyInt_AsLong(PyTuple_GET_ITEM(tup1,1)); return (PyObject *)mh; } """ setup.py """ from distutils.core import setup, Extension files = [ 'manhattan.c', 'icfp_module.c', ] libraries = [] #libraries = ["efence"] # uncomment to use ElectricFence includes = [] if (__name__ == '__main__'): setup(name = "icfp", version = "0.2", ext_modules = [Extension("icfp", files, libraries = libraries, include_dirs = includes, ) ] ) From kirk at strauser.com Mon Nov 17 12:55:05 2003 From: kirk at strauser.com (Kirk Strauser) Date: Mon, 17 Nov 2003 17:55:05 GMT Subject: line number var like perl's $.? References: Message-ID: <87islig9yb.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2003-11-17T15:51:52Z, Matthew Wilson writes: > Tracking line numbers is such a common thing to do when parsing files that > it makes sense for there to be a builtin for it. OTOH, I don't know that I've ever needed to track line numbers, other than to do something like 'print "Lines:", linenum' after reading a bunch of stuff from stdin. I only mention this to illustrate that what's common to you is not necessarily common to others. Your essential feature is another's cruft. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/uQqh5sRg+Y0CpvERAm6XAJwOsjML/se7yf6PGeNmHEqc8PvnmACcCllx rkneNtVmVNKNiW3QPQ0i21Y= =oaZV -----END PGP SIGNATURE----- From fredrik at pythonware.com Mon Nov 24 05:01:01 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Nov 2003 11:01:01 +0100 Subject: getting float from PyObject References: <20031124095437.GA18936@mf.uni-lj.si> Message-ID: Bostjan Jerko wrote: > Is there a way to get C float from PyObject (in C extension)? val = PyFloat_AsDouble(obj) see: http://www.python.org/doc/current/api/floatObjects.html From eric.wichterich at gmx.de Mon Nov 3 08:55:00 2003 From: eric.wichterich at gmx.de (Eric Wichterich) Date: Mon, 3 Nov 2003 14:55:00 +0100 Subject: Malformed Header In-Reply-To: <20031103133233.6101.qmail@web14007.mail.yahoo.com> Message-ID: <50F7F7B4-0E05-11D8-AD24-00039315E356@gmx.de> Hello Kiran, hmmm. Ensure that MySQL-DB-accesses are allowed for python (maybe use PHPMyAdmin to administrate MySQL and select the appropriate options). You can set from which IPs MySQL-accesses are allowed (e. g. "localhost" if Python and MySQL are running on same computer) and which privileges are granted for this IP. Have you checked PYTHONPATH whether the right MySQLdb-module is imported (if you have more than one versions of python or mysqldb installed)? Hmmm. I think a password statement is missing in your code " connection = MySQLdb.connect( db = "try" ) " Here is an example of my statement which works fine: "db = MySQLdb.connect(host="localhost", db="mydatabase", user="thegreatestuser", passwd="mypassword")" Maybe this helps? Cheers, Eric Am Montag, 03.11.03 um 14:32 Uhr schrieb Kiran Budhrani: > hello eric, > Im getting this error: > [error] [client 127.0.0.1] malformed header from script. Bad > header=*** You don't have the (right): c:/program files/apache > group/apache/cgi-bin/fig28_18.py > > I have connected all databases already. If I remove the import MySQL > statement, theres no problem. But i need to use the database. . what > could possibly be wrong??? > > pls help.. I have the MySQLdb installed in my Python directory > already.. > > > #!c:\Python23\python.exe > > import cgi > import MySQLdb > > > def printContent(): > ?? print "Content-type: text/html\n\n" > ?? print > ?? print """ > ?? lang="en"> > ?? Registration results > ?? > ?? > def printReply(): > ?? from convert import genPrime, genPrimeE > ?? p1 = genPrime() > ?? q1 = genPrime()??? > ?? e1 = genPrimeE() > ?? N1 = p1 * q1 > ?? M1 = (p1-1)*(q1-1) > ?? print 'e1 %d, m1 %d' %(e1,M1) > ?? > ?? while(e1 % M1 == 0): > ????? e1 = genPrimeE() > > ?? connection = MySQLdb.connect( db = "try" ) > ? > ?? cursor = connection.cursor() > ?? cursor.execute("insert into trials (p,q,n,m) values > ('p1','q1','n1','m1');") > ?? authorList = cursor.fetchall() > ?? cursor.close()????????????????? # close cursor > ?? connection.close()????????????? > > > printContent() > form = cgi.FieldStorage() > > personInfo = { 'firstName' : form[ "firstname" ].value, > ????????????????? 'lastName' : form[ "lastname" ].value, > ????????????????? 'email' : form[ "email" ].value, > ????????????????? 'phone' : form[ "phone" ].value, > ????????????????? 'book' : form[ "book" ].value, > ????????????????? 'os' : form[ "os" ].value, > ????????????????? 'message' : form["message"].value } > printReply() > > Eric Wichterich wrote: > > Hi Kiran, > > could you post the exact error entry from your error_log, please? > > Cheers, > Eric > > > Am Montag, 03.11.03 um 06:18 Uhr schrieb Kiran Budhrani: > > > Hi eric, I havent solved my problem... do u have any suggestions? > > what could possibly be wrong.. Im using Apache as my server and the > > error appears in the error log. > > ? > > pls help.. thanks! =) > > > > Eric Wichterich wrote: > > > > Hello Kiran, > > > > just wanted to ask whether your problem is already solved (if found > not > > further postings to this thread). > > > > Greetings, > > Eric > > > > > Do you Yahoo!? > Exclusive Video Premiere - Britney Spears -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 3625 bytes Desc: not available URL: From jay at jaydorsey.com Mon Nov 3 16:46:24 2003 From: jay at jaydorsey.com (Jay Dorsey) Date: Mon, 03 Nov 2003 15:46:24 -0600 Subject: timeoutsocket.py In-Reply-To: <878ymx9j0t.fsf@pobox.com> References: <878ymx9j0t.fsf@pobox.com> Message-ID: <3FA6CCB0.3060601@jaydorsey.com> Missed part of this thread, but I just remembered that I had it on one of my former employers servers -- I just e-mailed someone still with the company to see if its still there. Also, I just checked on archive.org for http://www.timo-tasi.org/python/timeoutsocket.py and it came up with revisions as recent as feb 2 of this year-- revision 1.23 seems to be the most recent. Regards, Jay From hemanth_sethuram at yahoo.com Fri Nov 28 08:21:15 2003 From: hemanth_sethuram at yahoo.com (Hemanth P.S.) Date: 28 Nov 2003 05:21:15 -0800 Subject: How to GetClassName in Python References: Message-ID: <9be5e130.0311280521.1334b276@posting.google.com> "bala" wrote in message news:... > Hi, > I want to know how to getclassname of application from python..In > python There is no method like GetClassName... > Is there any other Method ...I kindly give some example in python.. > If anyone answer to the above problem....I will be very > thankfull to you... > > Note:- Using Python Application, I want to Get the ClassName of any > Application. > -- You can access it by the attribute __class__ of the object. --Hemanth From relee_s at hotmail.com Tue Nov 4 18:34:26 2003 From: relee_s at hotmail.com (Relee Squirrel) Date: Tue, 04 Nov 2003 23:34:26 -0000 Subject: New to Python - Compiled Language? In-Reply-To: <20031103233637.08116.00000268@mb-m15.aol.com> Message-ID: --- In python-list at yahoogroups.com, keflimarcusx at a... (KefX) wrote: > >The impression I get from www.python.org is that it is a compiled > >very high level language, which is extendable via C++. I'm a C++ > >programmer and the tools and utilities referred to existing in Python > >would increase the development time of my projects. However, what I'm > >creating are programs, not just scripts. > > > >Is Python a language which can be compiled into an executable program? > > Well, Python isn't a compiled language in the sense of native code compilation > (that is, making an EXE on Win32, or a normal binary executable on Unix, etc.), > though there is a tool called py2exe that you may want to look into in order to > bundle your program into an executable on Win32. > (http://starship.python.net/crew/theller/py2exe/) I think that would be very useful, thank you. :) When I say compiled language, I do mean a language like C++ which is transformed into machine code by a compiler. I was under the impression that Python had no such compiler, and that the end user of my programs would be required to install the Python Interpreter. Is that true in most cases? > The best advice I can give is just give it a shot. Write something small but > nontrivial and see how it works for you. Any more questions? I'm a video game programmer and the applications I'm hoping to use Python for are the games themselves as well as the utilities used in making the games, such as level editors. There are several programming concepts which I haven't studied in depth which I read Python can handle easily, such as handling the Windows GUI, using and even creating internet transfer protocols, and compressing and decompressing files. Also, can Python support Linked Lists? I believe someone said in one of the other emails that Python doesn't support pointers. Thanks for your assistance! From pf_moore at yahoo.co.uk Wed Nov 12 17:41:09 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Wed, 12 Nov 2003 22:41:09 +0000 Subject: What's an "atomic" operation (in a threaded context)? Message-ID: I can't find anything which spells this out in the manuals. I guess that, at some level, the answer is "a single bytecode operation", but I'm not sure that explains it for me. This thought was triggered by a comment on the Python Cookbook site, which basically said that it was OK to do tss = {} ... id = thread.get_ident() tss[id] = {} (where tss is a global) without a lock, because id is unique to the thread. But couldn't this result in 2 threads allocating a new entry in tss at the same time, and so get tss in an inconsistent state? I tried to understand this with the dis module: >>> import dis >>> d = {} >>> def f(n): ... d[n] = {} ... >>> dis.dis(f) 2 0 BUILD_MAP 0 3 LOAD_GLOBAL 0 (d) 6 LOAD_FAST 0 (n) 9 STORE_SUBSCR 10 LOAD_CONST 0 (None) 13 RETURN_VALUE But I'm not sure to make of that. Can anyone clarify this for me? I'd like to avoid littering my threaded code with huge numbers of unnecessary locks... Thanks, Paul. -- This signature intentionally left blank From aleax at aleax.it Wed Nov 12 12:43:53 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 12 Nov 2003 17:43:53 GMT Subject: a python book hint References: Message-ID: Eduardo Patto Kanegae wrote: > Hello, > > I have been programming with Visual Basic and PHP in the last 5 years and > some folks had recommended Python a free language.... > > I had looked for a Python book to start up but found many titles... > > so, my question finally is: what book could be for a Python beginner - > but NOT a programming beginner - which intends to develop *windowed* > Python programms and intends to develop for Windows and for Linux? > > for example, look at Thuban software ( http://thuban.intevation.org/ ) > which runs on Linux and Win plataforms. Hetland's "Practical Python" is a good book, particularly if you like _meaty_ examples (my own "Python in a Nutshell" has less purely tutorial material, and the examples are small, illustrating single simple points; thus, it's more of a "concise desktop reference" than an introduction). Most other books are unfortunately a bit dated, but these two do cover Python 2.2 (and the current 2.3 has basically no language-level changes wrt to 2.2 -- it's mostly faster and more robust, with small additions to the built-ins and more substantial ones to the standard library). Alex From __peter__ at web.de Mon Nov 24 12:58:48 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Nov 2003 18:58:48 +0100 Subject: complex Numeric arrays References: Message-ID: Christian Kristukat wrote: >> how can I evaluate a expression like the following: >> 1/(a + jb) where j is the imaginary unit and a and b are Numeric real >> float arrays. I don't want to have to split up the expression in real >> and imaginary parts. > > I just found it out by myself: > > 1/(a+b*1j) Or >>> a = 1 >>> b = 2 >>> 1/complex(a,b) (0.20000000000000001-0.40000000000000002j) Peter From tim.ronning at start.no Tue Nov 4 05:42:03 2003 From: tim.ronning at start.no (Tim Ronning) Date: Tue, 04 Nov 2003 11:42:03 +0100 Subject: TypeError: can't multiply sequence to non-int In-Reply-To: <20031103151451.BC13.PYTHON@essene.com> References: <20031103133306.BC11.PYTHON@essene.com> <20031103151451.BC13.PYTHON@essene.com> Message-ID: P? Mon, 03 Nov 2003 15:15:56 -0700, skrev Python : > That works perfect ;) Thanks! I am really enjoying learning Python. It > has to be the most fun computer language around. > > Jim > Glad to help Jim. I'm a newbie just like yourself, just happend to know the answer to your problem. Yes, Python is fun. I'm sometimes amazed over it's butifull syntax. When I run into "problems" the first thing I try is to write the code in a "human" way and behold it often works! This I think is unique to Python. It's great. Another great "attribute" to Python is it's friendly and highly skilled user community on the net and everywhere else. Someone is always there with a smile to give you a hand. Keep on learning. Regards Tim R. -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From bokr at oz.net Sat Nov 8 19:10:23 2003 From: bokr at oz.net (Bengt Richter) Date: 9 Nov 2003 00:10:23 GMT Subject: Precise calculations References: <0e547e2582633f8ea23d0b5e5d337128@news.meganetnews.com> Message-ID: On Fri, 07 Nov 2003 13:17:44 GMT, "Ladv?nszky K?roly" wrote: >Could anybody help me on how to do precise calculations with Python the way >hand-held calculators do? > >A small example to show the impreciseness coming from the floating point >arithmetics: > >(100000000000000.4*3)*100 gives 30000000000000124.0 > By coincidence I just posted a module (very alpha code, see "prePEP: Decimal data type" thread) that does exact decimal floating point, so you can do better than hand calculators ;-) First, let's use it to show what the full floating point bits ('all') show when converted to an exact representation: >>> from exactdec import ED >>> ED(100000000000000.4,'all') ED('100000000000000.40625') ^ +--the _actual_ floating point value represented >>> ED(100000000000000.4,'all')*3 ED('300000000000001.21875') ^ +-- an exact multiple by 3 >>> ED(100000000000000.4*3,'all') ED('300000000000001.25') ^ +--the exact value of the inexact floating point product >>> ED(100000000000000.4*3,'all')*100 ED('30000000000000125') ^ +--times 100 exactly >>> ED(100000000000000.4*3*100,'all') ED('30000000000000124') ^ +--the result of the additional floating point multiply Now doing the math starting with an exact string literal for your starting value: >>> ED('100000000000000.4') ED('100000000000000.4') ^ +--value is exact >>> ED('100000000000000.4')*3 ED('300000000000001.2') ^ +--product is exact (the right operand of 3 is converted like ED(3) which is exact since integer is exact. >>> (ED('100000000000000.4')*3)*100 ED('30000000000000120') ^ +--similarly with the 100 factor, which is converted to exact before multiplying as well. Now try this on your calculator (note the binomial thing): >>> b = ED('1001001001001001001001001001') >>> b ED('1.001001001001001001001001001e27') >>> b*b ED('1.002003004005006007008009010009008007006005004003002001e54') >>> b*b*b ED('1.003006010015021028036045055063069073075075073069063055045036028021015010006003001e81') ;-) Regards, Bengt Richter From jkrepsBEAR at FISHneb.rr.com Thu Nov 6 19:24:50 2003 From: jkrepsBEAR at FISHneb.rr.com (GrayGeek) Date: Thu, 06 Nov 2003 18:24:50 -0600 Subject: import cx_Oracle References: <3fa32966$0$1118$6c56d894@feed0.news.be.easynet.net> <7lgqb.119692$%C5.21026@twister.rdc-kc.rr.com> Message-ID: Andy Todd wrote: > [snip] >>>>mmm... the only Oracle onnection on my box is for the 9i database. >>>> >>> >>>So, just to clarify, on your Windows box you now have *only* Python 2.2 >>>and the Oracle 9i client? I'm presuming also that your database is on >>>another machine. And you've installed the appropriate cx_Oracle binary? >>>Works for me; >> >> >> Your assumptions are correct. But, it doesn't work for me. >> >> >>>PythonWin 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on >>>win32. Portions Copyright 1994-2001 Mark Hammond >>>(mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further >>>copyright information. >>> >>> import cx_Oracle >>> >>> cx_Oracle.version >>>'3.1' >>> >>> db=cx_Oracle.connect('andy/andy at melchett') >>> >>> cursor=db.cursor() >>> >>> cursor.execute("SELECT user FROM dual") >>>[] >>> >>> print cursor.fetchall() >>>[('ANDY',)] >>> >>> >>> >>>I also tried it with cx_Oracle version 2.5a, and then on my other >>>machine with Python 2.3, the 9i client and version 3.0a of cx_Oracle. >>> >>>So, my guess is that you are still suffering from a DLL confusion >>>(somewhere). >> >> >> Probably true, but JDev9 and PSQLDeveloper doesn't have any connection >> problems. >> ?? >> > > Well, you've got me beaten. I tried to break my system by downloading > the Windows binary for Python 2.2 and Oracle8i, even though I have the > 9i client - and it still worked. > > The only combination I haven't tried, and I'm not going to, is the > cx_Oracle binary built against the Oracle9i client with the Oracle8i > client software which I suspect would break in the manner you describe. > > As many people are successfully using cx_Oracle and you are the only one > seeing this problem I still suspect the solution to your problem is in > the combination of software you have running on your machine rather than > a bug in cx_Oracle, Python or Oracle. > > Officially-throwing-in-the-towel-ly y'rs, > Andy Thanks for the effort, Andy. I think I will uninstall everything (except my Oracle client) and reinstall.... again. Ya never know. That MS register can do funny things.... -- - GrayGeek From aleax at aleax.it Tue Nov 11 05:39:32 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 11 Nov 2003 10:39:32 GMT Subject: Am I the only one who would love these extentions? - Python 3.0 proposals (long) References: Message-ID: Alexander Schmolck wrote: ... > IMHO, this is a not such a good way to define enums. Why not do > > AND, ASSERT, BREAK, CLASS, etc == "AND, ASSERT, BREAK, CLASS, > etc".split(", ") Unfortunately, this breaks the "once, and only once" principle: you have to ensure the sequence of words is the same on both sides -- any error in that respect during maintenance will cause small or big headaches. > and you've got the significant advantage that screw-ups are less likely I disagree with you on this point. Any time two parts of a program have to be and remain coordinated during maintenance, screw-ups' likelihood unfortunately increases. Keeping enum values in their own namespace (a class or instance) is also generally preferable to injecting them in global namespace, IMHO. If you want each constant's value to be a string, that's easy: class myenum(Enum): AND = ASSERT = BREAK = CLASS = 1 with: class Enum: __metaclass__ = metaEnum and: class metaEnum(type): def __new__(mcl, clasname, clasbases, clasdict): for k in clasdict: clasdict[k] = k return type.__new__(mcl, clasname, clasbases, clasdict) The problem with this is that the attributes' _order_ in the classbody is lost by the time the metaclass's __new__ runs, as the class attributes are presented as a dictionary. But if the values you want are strings equal to the attributes' names, the order is not important, so this works fine. But many applications of enums DO care about order, sigh. > in combination with iterators).I'd also like to have the apply-* work in > assignments, e.g. ``first, second, *rest = someList``. This would also > make python's list destructuring facilities much more powerful. Yes, I agree on this one. Further, if the "*rest" was allowed to receive _any remaining iterable_ (not just necessarily a list, but rather often an iterator) you'd be able to use itertools.count() and other unbounded-iterators on the RHS. Alex From john at rygannon.com Mon Nov 3 14:06:44 2003 From: john at rygannon.com (John Dean) Date: Mon, 3 Nov 2003 19:06:44 GMT Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0310312008.ce341ea@posting.google.com> <87r80sdyb1.fsf@pobox.com> <7xn0bg6njb.fsf@ruckus.brouhaha.com> <7x7k2jpti9.fsf@ruckus.brouhaha.com> Message-ID: <3fa6a720$0$12675$fa0fcedb@lovejoy.zen.co.uk> Rekall is total dependant on Python, hence the reason for the discussion Kapital is based on KDELibs, Python not included nor is there any Python in any embedded app, save tkcRekall and tkcRekallLite -- Best Regards John From noemail at noemail4u.com Mon Nov 24 12:52:06 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Mon, 24 Nov 2003 17:52:06 GMT Subject: Bug or Feature? References: <2259b0e2.0311240603.549943b3@posting.google.com> Message-ID: <9cf48f3e1bcf524ab4ad581a061d1852@news.teranews.com> On Mon, 24 Nov 2003 18:13:34 +0100, Stephan Diehl wrote: ... >This is probably more a theoretical question, but if I decide to have an >operation within one specific domain, I want the result in that domain too. >Otherwise, there would be no point at all to define such a numeric class at >all. > >Stephan I understand what you're saying, but there's no universal rule that says that the result of operations between members of a set are also members of the set. Obvious examples include division on the set of integers, and division over the set of real numbers, i.e.division by zero is not a real number. --dang From CousinStanley at hotmail.com Mon Nov 10 18:59:13 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Mon, 10 Nov 2003 16:59:13 -0700 Subject: Get more from Google (was: programming languages (etc) "web popularity" fun) References: <9Vvob.74272$e5.2721707@news1.tin.it> Message-ID: || Perhaps in the future we can look forward || to Google dot Net for the Masses .... | Declined by the folks a Google, thank Goddess. | http://www.smh.com.au/articles/2003/11/02/1067708070338.html Nick .... I could probably translate .... Declined the bid .... As .... Add another X% and a Partridge in a Pear Tree and we MIGHT reconsider .... -- Cousin Stanley Human Being Phoenix, Arizona From http Tue Nov 18 17:55:34 2003 From: http (Paul Rubin) Date: 18 Nov 2003 14:55:34 -0800 Subject: rotor alternative? References: Message-ID: <7xy8uduw0p.fsf@ruckus.brouhaha.com> hwlgw at hotmail.com (Will Stuyvesant) writes: > Deprecation is a very serious matter. I love the Python language but > I have questions about the deprecation decisions. The two > deprecations I hate most are rotor and xmllib. Unfortunately deprecation happens so often because crap makes it into the library that should have been done right to begin with. I don't know about xmllib but rotor really should be deprecated, and no one should use it, because of its security shortcomings. From jarrodhroberson at yahoo.com Fri Nov 7 00:09:38 2003 From: jarrodhroberson at yahoo.com (Y2KYZFR1) Date: 6 Nov 2003 21:09:38 -0800 Subject: Python versus VB References: <3fa057e2.14061399@news.dsl.pipex.com> Message-ID: simon at uggs.demon.co.uk (Simon Foster) wrote in message news:<3fa057e2.14061399 at news.dsl.pipex.com>... > I am meeting with a potential client next week to > discuss starting a new project. His preference is for > VB whereas I would prefer Python for obvious reasons ;-) > > Could anybody come up with a short list of the pros and > cons of the two languages (I am not terribly familiar > with the strengths/weaknesses of VB). This will be a > general-purpose text-processing type application with no > GUI required. if there is no gui required then Python is a no brainer. Unless the support and maintance staff refuse to learn Python. From aleax at aleax.it Mon Nov 3 05:28:07 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 03 Nov 2003 10:28:07 GMT Subject: Selling Python Software References: Message-ID: Will Stuyvesant wrote: > Suppose I want to sell a (small, 1000 lines) Python program. It is a > commandline program for database applications and I have a customer. > The customer wants to "try it out" before buying. The try-out version > should be a full, complete, version. > > As much as I like the opensource movement, I have a problem now. If I > just give them the Python source code then they can show it to their > programmers and they have no reason anymore to pay money to me. Sure > that would break our agreements, but you know bussiness, legal issues. > The thing the customer is interested in is the algorithm used in the > program. Not much I could do about such a scenario effectively. > > I tried py2exe before, but someone told me it is always possible to > decompile...revealing the source code. Yes, exactly as could be done if you coded your precious algorithm in C, machine-language, or whatever: if you distribute executable code it CAN be cracked and the algorithm reverse-engineered (see any warez site: game companies go to HUGE length to defend their programs and they STILL get cracked anyway). > Anybody has a solution to this, besides more legal paperwork (I am in > europe...forget about claiming your rights here)? Is it not possible > to give away a Windows .exe file that can not be decompiled (or only > with *extreme* difficulty)? "Can not be decompiled" is impossible whatever language you're using. "*extreme* difficulty" is in the eye of the beholder. You can e.g. add layers of encryption/decription to the bytecode, etc, but whatever you do somebody else can undo. Depending on the relative skills of you and the "somebody else" the ratio (your effort to keep things secret, to theirs to uncover them) can be any. Couldn't you keep some crucial part of your precious algorithm OFF the code you distribute, and have said code access said part via webservices towards your personally-controlled, secure host? Alex From huzzah at tampabay.rr.com Sat Nov 1 18:15:19 2003 From: huzzah at tampabay.rr.com (Todd Stephens) Date: Sat, 01 Nov 2003 23:15:19 GMT Subject: Rekall not longer available from theKompany.com - a fabrication References: <3fa0fd21$0$12688$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0310312008.ce341ea@posting.google.com> <87r80sdyb1.fsf@pobox.com> <7xn0bg6njb.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 01 Nov 2003 11:50:32 -0500, Paul Rubin wrote: > The claim that I see is that: > > Basically, the answer is TKC is bankrupt. TKC's team of developers > have not been paid for over 5 months (some even longer). > > The word "bankrupt" is qualified by the word "basically" which I take to > mean that TKC is out of money but there has not yet necessarily been a Regardless of the OP's intentions, I think the word "bankrupt" is not qualified by "basically" so much as it is qualified by "is". -- Todd Stephens From luis_ at iname.com Thu Nov 6 14:58:55 2003 From: luis_ at iname.com (Lupe) Date: Thu, 06 Nov 2003 19:58:55 +0000 Subject: return multiple values from fuction Message-ID: hi, if someone can help me I would be grateful when I do def function kjklj llkl? return variableA, variableB how can I assign the two return values to two distinct variables, as for ex. varC = variableA varD = variableB ?? From ferrell at diablotech.com Wed Nov 19 17:23:33 2003 From: ferrell at diablotech.com (Robert Ferrell) Date: 19 Nov 2003 14:23:33 -0800 Subject: Package organization References: <73b00f0c.0311181638.49a5997d@posting.google.com> Message-ID: <73b00f0c.0311191423.3c946fdc@posting.google.com> Graham Ashton wrote in message news:... > On Tue, 18 Nov 2003 16:38:15 -0800, Robert Ferrell wrote: > > > I have a question about how to organize modules in a package. I think > > there is something fundamental that I am missing. Say I'm creating a > > package, > > GreatPackage, which has three sub-packages, myUtilities, GoodStuff, > > MoreGoodStuff. > > > > The directories look like: > > > > GreatPackage > > | > > |-- myUtilities > > | > > |-- GoodStuff > > | > > |-- MoreGoodStuff > > > > What is the right way for modules in GoodStuff and MoreGoodStuff to > > refer to modules etc... in myUtilities? > > There's a PEP that recommends that when importing things you refer to them > explicitly; i.e. inside GoodStuff you'd say > > import GreatPackage.myUtilities > > rather than just > > import myUtilities > > I've only benefitted from doing it that way myself in large apps that have > had many packages with sub packages. It keeps you safe from module name > clashes at different levels of the hierarchy (not that I think they're a > sensible thing to have). By name clashes I mean if you have modules > set up like this: > > lib > shoe.lib > shoe.fruit > > then you can't get at the top level lib module from inside shoe.fruit. > > > from GreatPackage.myUtilities import aUtilityThingy > > > > in a module in GoodStuff, then the whole package gets loaded, > > including MoreGoodStuff. > > MoreGoodStuff won't get loaded if you import GreatPackage, unless > GreatPackage/__init__.py causes it to be loaded. Obviously, if something > in myUtilities imports something from MoreGoodStuff then python will > attempt to load MoreGoodStuff when importing myUtilities. Ah Ha! Somehow I'd convinced myself that GreatPackage/__init__.py had to import all the submodules. So that's what I was doing. That's obviously wrong. Now that I've corrected that mistake I see that what I was having trouble with is not an issue. > Also, because you're importing something from inside a module using the > "from" style imports you're risking running into circular reference > problems. In my experience from imports are best avoided, unless you're > importing a module from a package. I don't understand this comment. How does "from" style importing increase the risk of circular imports? Thanks for the clarification! -robert From tarball at phreaker.foo Sun Nov 2 09:23:01 2003 From: tarball at phreaker.foo (Thomas F.B.) Date: Sun, 02 Nov 2003 15:23:01 +0100 Subject: Newbie Question References: Message-ID: On Sun, 02 Nov 2003 12:42:22 +0000, PythonRAD wrote: > > How can I do for insert a text into Entry widget? > Have a look at the Tkinter tutorial by Fredrik Lundh at: http://www.pythonware.com/library/tkinter/introduction/index.htm In section 25, you will find a short description of all methods of the 'Entry widget' (including the method: 'insert'). -- mailto: tarball at phreaker.foo (foo = net) From lucik at pt.dn.ua Thu Nov 6 04:20:51 2003 From: lucik at pt.dn.ua (Lucik) Date: 6 Nov 2003 01:20:51 -0800 Subject: Please Help Explain References: Message-ID: <41caa72a.0311060120.67cb389e@posting.google.com> n=0 while you_wish_to_eat # eat couple of hotdogs n = n+2 return n # total number of hotdogs You can not return to the same state in the loop. Natural and without depth. "Jakle" wrote in message news:... > I was at a job interview one day and the owner of the start up company asked > me if I'd rather make $1000 dollars a day, or start off with a penny a day > and double the amount every day for 30 days. I was too lazy to sit down with > paper and pen to figure out how much the second choice came out to. But now > I'm learning python and just learned about recursive functions and > iteration, I figured I'd use those theories to figure out the problem. After > racking my brain trying to figure it out (I'm a noob to this stuff, and math > isn't my strong point), I came up with this formula: n = n*2. So I messed > around with it and came up with the following code: > > +++++++++++++++++++++++++++++++++++++++ > # penny.py 11-05-03 > > days = raw_input("How many days: ") > > def calc(n, days): > i = 1 > while i <= days: > n = n*2 > i = i+1 > return n/float(100) > > print calc(1, int(days)) > +++++++++++++++++++++++++++++++++++++++ > > I completely stumbled across it and it works. I just don't understand how > the value of n is assigned to the second n in "n=n*2" once it loops back > again. I would understand if it was a recursive function and passed as an > argument, but I don't think I completely understand how the "while" > statement handles variable values. I am learning from "How to Think Like a > Computer Scientist: Learning With Python", and it doesn't go into too much > depth about it, at the moment at least. I was wondering if anyone could shed > some light on my dilema. :-) > > Thanks ahead of time. From tim.hochberg at ieee.org Thu Nov 13 12:31:51 2003 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Thu, 13 Nov 2003 10:31:51 -0700 Subject: case-sensitivity (was Re: True, False, None) In-Reply-To: <3gNsb.20789$hV.759234@news2.tin.it> References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <2259b0e2.0311122135.62359cc0@posting.google.com> <3gNsb.20789$hV.759234@news2.tin.it> Message-ID: Alex Martelli wrote: > Michele Simionato wrote: [SNIP] >>For instance, I can define a matrix type, overload "*" and write the >>multiplication of a matrix "A" times a vector "a" as >> >>b=A*a >> >>Much more readable to me, that something like > > > Please note that here you are suddenly and undocumentedly _switching > conventions on the fly_ regarding capitalization. Non issue, relatively speaking. Context makes this clear. > One moment ago, > leading cap had to mean "type" and all caps had to mean "numeric > constant" (which in turn made a single-caracter capital identifier > ambiguous already...) -- now suddenly neither of these conventions > exists any more, since that uppercase A means 'matrix' instead of > 'vector' (and a _number_, i.e. even lower dimensionality, would be > indicated *HOW*? Number crunching with Python, by which I mean implementing big nasty formulas from obscure journals. It's a hard game all the way around. The problem is over constrained and making things case insensitive would just make things worse. One would like to keep your formulas as close as possible to their sources. This helps both to get the formulate correct, but allows future readers of the code to be referred to the relevant journal and have some prospect of matching up code to article. This is impossible to do exactly of course since python doesn't support arrows and overbars, boldface and italic in identifiers. Using case sensitivity can help here, although it certainly doesn't solve all problems. The convention of capitalizing the matrices, lower-casing the vectors and writing out the scalars (see below) is often effective. > Don't you EVER multiply your matrices by scalars?! Scalars in my experience are frequently represented using Greek characters, so they get written out and are therefore easy to distinguish. They also tend to represent only a small portion of the typical equation, so that fact that they are written out doesn't have that large an effect. When the scalars are not represented using Greek, you just do the best you can. > Or is it so crucial to distinguish matrices from vectors but totally > irrelevant to distinguish either from scalars?!). Just because it's difficult to represent formulas well using ASCII is not reason to make it more difficult, nor to throw up our hands and not try to represent them as best we can. >>b=a_matrix*a >> >>or even >> >>b=c*a # c is a matrix >> >>Mathematical formulas are the first reason why I like case sensitivity. > > > My opinion is that, while _habit_ in mathematical formulas may surely > make one hanker for such case-sensitivity, the preference just does not > stand up to critical analysis, as above. In theory, there is no difference between theory and practice. In practice.... I've tried many ways over the years to represent equations legibly using Python and my experience that case sensitivity, while certainly no panacea, helps. > You're trying to overload WAY > too many different and conflicting "conventions" onto a meager "one bit > [at most] per character" (about 0.87 bits I believe, in fact) of > "supplementary information" yielded by case-sensitivity. I believe it's much closer to 1 full bit for length-1 sequences since numbers cannot start an identifier, decreasing relatively quickly to 0.87 (I'll take your word for the 0.87 being the asymptotic value.) [SNIP] > Most paladins of case sensitivity would probably be horrified to see > that the main point in its "favour" now appears to be that it > encourages you to use shorter (e.g. 1-letter) identifiers (and thus > more cryptic ones) because it gives you more of them to choose from...!!! I find this argument silly. I have all the freedom I need to make my code illegible by using short identifiers without exploiting case. I'm certain I could rewrite all my code to use two letter lowercase identifiers and the lack of mixed case certainly wouldn't make it any clearer. > I disagree -- once you have to spell out e.g. pi, capital-sigma, etc, > in Ascii letters anyway, having to make sure you do so in letters that > are unambiguous in terms of capitalization differences is no big loss. Interestingly all of the math typesetting programs I've seen, including LaTex and MathML us Sigma (or SIGMA) and sigma for upper and lower case sigma respectively. None write it out. [SNIP] In the end, this is a tools issue. If people spent half the time working on their favorite editor as discussing case-sensitivity, the problem would be long solved. SciTe comes pretty close with its auto completion stuff, but it doesn't order the completions appropriately. The correct order would be to ignore both captitalization and underscores. Or, perhaps, just non-leading underscores. I once fixed one of wxPython IDEs to do this mostly right, but sadly I've forgotten which one. I suppose it's time to dig into SciTe, but it's unfortunately not in Python. Which brings me to something I can't understand about the great capitalization debate. Why is 'runmethod' versus 'runMethod' confusing, while 'runmethod' vs 'run_method' is not? To do a full job I'd think you'd have to axe underscores as well. Far better to just improve the tools. -tim From donn at u.washington.edu Wed Nov 12 19:47:56 2003 From: donn at u.washington.edu (Donn Cave) Date: Wed, 12 Nov 2003 16:47:56 -0800 Subject: program surgery vs. type safety References: <9a6d7d9d.0311120822.553cd347@posting.google.com> Message-ID: In article <9a6d7d9d.0311120822.553cd347 at posting.google.com>, aaron at reportlab.com (Aaron Watters) wrote: > I'm doing a heart/lung bypass procedure on a largish Python > program at the moment and it prompted the thought that the > methodology I'm using would be absolutely impossible with a > more "type safe" environment like C++, C#, java, ML etcetera. > > Basically I'm ripping apart the organs and sewing them back > together, testing all the while and the majority of the program > at the moment makes no sense in a type safe world... Nevertheless, > since I've done this many times before I'm confident that it > will rapidly all get fixed and I will ultimately come up with > something that could be transliterated into a type safe system > (with some effort). It's the intermediate development stage > which would be impossible without being able to "cheat". A type > conscious compiler would go apopleptic attempting to make sense of > the program in its present form. > > If I were forced to do the transformation in a type safe way > I would not be able to do as much experimentation and backtracking > because each step between type safe snapshots that could be tested > would be too painful and expensive to throw away and repeat. > > This musing is something of a relief for me because I've lately > been evolving towards the view that type safety is much more > important in software development than I have pretended in the past. It's interesting that you lump ML in with the rest of those languages. There are at least a few people around who reject any thinking on type safety if it's cast in the context of C++ or Java, because the strict static typing, type inference and other tools you don't get with either of those languages make them poor representatives. But ML has that stuff. I have the sources here for a largeish Python program. We have been using it here in production for some months, and I have a collection of changes to adapt it to our environment. A lot of changes, by my standards - 4560 lines of context diff, plus some new modules and programs. I have a minor upgrade from the author, and this afternoon I finished patching in our changes. That is, I have run the context diffs through patch, and hand patched what it couldn't deal with. So I have one automated structural analysis tool helping me out here - patch. I will also be able to run them through the "compiler" to verify that they're still syntactically correct, but that won't help much here - patch already noticed the kind of local changes that would make for syntactical breakage. I'm more concerned about non-local changes - some other function that now behaves differently than it did in when we wrote a change around it. There's no guarantee that if this program were written in ML instead, I'd find every upgrade error, but it would be a hell of a lot better than patch. If I were as confident as you that ``it will rapidly all get fixed,'' then I guess it would not be an issue. But my experience is that too much of it won't get fixed until it breaks in production, and I hate to mess with it for that reason. I find Haskell and Objective CAML kind of liberating in this way - I can go in and really tear it up, and the compiler won't let me call it finished until all the boards are back, wires and fixtures re-connected - stuff that I can't see but it can. Donn Cave, donn at u.washington.edu From jjl at pobox.com Sun Nov 30 10:37:24 2003 From: jjl at pobox.com (John J. Lee) Date: 30 Nov 2003 15:37:24 +0000 Subject: Python bug? Named parameters in recursive calls sometimes confuses python? References: <258fd9b8.0311271503.c134a25@posting.google.com> Message-ID: <87ptf9q34b.fsf@pobox.com> magnus at thinkware.se (Magnus Lyck?) writes: > Something really strange is happening to me (sometimes). > I'm using Python 2.3.2 on NT 4.0 as well as win32all-157, > adodbapi and db_row. > > During a recursive call to a method, it seems Python messes > up its variable bindings once in a while. Suddenly, one of > several local variables gets rebound to the object it was bound > to one step up in the recursion. [...] Try sticking in an extra parameter to the recursive function, recursion_level=0, print and incrementing it at the start of the function, and make sure every recursive call passes that optional argument. John From aleax at aleax.it Fri Nov 14 07:54:54 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 14 Nov 2003 12:54:54 GMT Subject: Python's simplicity philosophy References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> Message-ID: BW Glitch wrote: ... > It wasn't obvious for me until later. reduce() is more likely to be used > for optimization. IIRC, some said that optimization is the root of all > evil. That's *PREMATURE* optimization (and "of all evil IN PROGRAMMING", but of the two qualifications this one may be less crucial here) -- just like misquoting "The LOVE OF money is the root of all evil" as "MONEY is the root of all evil", so does this particular misquote trigger me;-). Optimization is just fine IN ITS PROPER PLACE -- after "make it work" and "make it right", there MAY come a time where "make it fast" applies. It's extremely unlikely that 'reduce' has a good place in an optimization phase, of course -- even when some operator.foo can be found: [alex at lancelot tmp]$ timeit.py -c -s'import operator' -s'xs=range(1,321)' 'r=reduce(operator.mul, xs)' 1000 loops, best of 3: 450 usec per loop [alex at lancelot tmp]$ timeit.py -c -s'import operator' -s'xs=range(1,321)' 'r=1' 'for x in xs: r*=x' 1000 loops, best of 3: 440 usec per loop reduce shows no advantage compared with a perfectly plain loop, and when no operator.bar is around and one must use lambda: [alex at lancelot tmp]$ timeit.py -c -s'import operator' -s'xs=range(1,321)' 'r=reduce(lambda x, y: pow(x, y, 100), xs)' 1000 loops, best of 3: 650 usec per loop [alex at lancelot tmp]$ timeit.py -c -s'import operator' -s'xs=range(1,321)' 'r=1' 'for x in xs: r = pow(r, x, 100)' 1000 loops, best of 3: 480 usec per loop reduce gets progressively slower and slower than the pian loop. It's just no bloody good, except maybe for people short-sighted enough to believe that it's "more concise" than the loop (check out the lengths of the timed statements above to dispel THAT myth) and who'd rather slow things down by (say) 35% than stoop to writing a shorter, plainer loop that every mere mortal would have no trouble understanding. > Just because it's _obvious_ to you, it doesn't mean it's obvious to > people who self taught programming. That may be the real motivation for the last-ditch defenders of reduce: it's one of the few (uselessly) "clever" spots in Python (language and built-ins) where they may show off their superiority to mere mortals, happily putting down as sub-human anybody who doesn't "get" higher-order functions in 10 seconds flat (or less)...;-) Alex From ryasko at gator.net Wed Nov 5 19:32:00 2003 From: ryasko at gator.net (Greg Yasko) Date: Wed, 05 Nov 2003 19:32:00 -0500 Subject: Perl file::find module equivalent in Python? In-Reply-To: References: Message-ID: <9Dgqb.3003$0d2.1203@lakeread06> Skip Montanaro wrote: > Greg> Hi. Does anyone know if there's an equivalent of Perl's file::find > Greg> module in Python? It traverses a directory. I've googled > Greg> extensively and checked this newsgroup and can't find anything > Greg> like it for Python. > > I've never used file::find, but from your short description ("traverses a > directory"), I suspect you're looking for os.listdir, os.path.walk or > perhaps glob.glob: > > Skip > Thanks for answering my question. I knew there had to be some way to do it:-) From roy at panix.com Mon Nov 24 16:22:38 2003 From: roy at panix.com (Roy Smith) Date: Mon, 24 Nov 2003 16:22:38 -0500 Subject: Adding new methods at runtime to a class References: Message-ID: In article , "Delaney, Timothy C (Timothy)" wrote: > > From: Fernando Rodriguez > > > > How can I add new methods at runtime to a class? > > Before we send you into what most would consider black magic in Python, you > should explain why you want to. > > In most cases, this is *not* what you want to do - there are better, more > elegant and much more Pythonic ways of doing it. > > Tim Delaney > Why is it unpythonic to add methods at runtime? That's the nature of a dynamic language. If foo.bar doesn't have to exist until the moment it's evaluated, why should foo.bar() have to? Or maybe a better way to ask it is why should foo.bar have to be callable at any other time than when you evaluate foo.bar()? I would say that the fact that all of a class's methods have to be declared at once is itself somewhat unpythonic. From aleax at aleax.it Wed Nov 5 09:51:56 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 05 Nov 2003 14:51:56 GMT Subject: PEP 289: universal and existential operators References: <5d83790c.0310231158.65595858@posting.google.com> <698f09f8.0311050646.8767d19@posting.google.com> Message-ID: Jeremy Fincher wrote: ... > I think these names also read somewhat more clearly: > > # Check if someone is yelling: > if all(str.isupper, line.split()): > print "Must be a flamewar." > > and: > > # Check if someone yelled at all: > if any(str.isupper, line.split()): > print "Someone yelled." I'm not sure what these calls are meant represent -- maybe an interface similar to filter, i.e. a callable then a sequence? The functions we're considering, whatever their names, would in any case just take an iterator, so, e.g.: if all(x.isupper() for x in line.split()): and the like. > I believe both these examples are more easily readable with "all" and > "any" than they would be with "forall" and "exists." I'll pass on that. Maybe. I think I still prefer alltrue and anytrue... Alex From aahz at pythoncraft.com Wed Nov 19 13:51:00 2003 From: aahz at pythoncraft.com (Aahz) Date: 19 Nov 2003 13:51:00 -0500 Subject: Callable generators (PEP 288: Generator Attributes, again) References: <55688f89.0311180211.7ab1bc30@posting.google.com> Message-ID: In article , Francis Avila wrote: >Aahz wrote in message ... >>In article <55688f89.0311180211.7ab1bc30 at posting.google.com>, >>Francis Avila wrote: >>> >>>A little annoyed one day that I couldn't use the statefulness of >>>generators as "resumable functions", [...] >> >> But generators *are* resumable functions; they just >>don't permit injection of new values into their state. > >I see then that I don't need to convince you. :) But it is because you >can't inject new values into their state that they are not resumable >functions. They're pure state, not functions-with-persisting-state. >If they were resumable functions, we could call them like functions >and be returned values based upon passed parameters, except that the >algorithm used would depend upon the generator's internal state. Enh. Depends on how one looks at it. They *are* functions with persisting state; the state stays around until the generator's iterator exits. Sounds to me like you're trying to conflate two different mechanisms for managing function state. >>The problem with injecting values is that there's no way to pick them >>up; it's a "push" solution rather than a "pull" solution. > >You mean "pull" rather than "push"? No, I do mean push. >Well, I just suggested a way to pick them up which is no different >than how a function picks up parameters--they're pushed in rather than >pulled in, by overwriting the local namespace before advancing the >generator's state. Would you care to comment on my suggestion? The problem is that a function declares what parameters are to be pushed in, so that from the standpoint of the function, it really is a pull solution. When you instantiate a generator iterator, the bytecodes in the function do *not* get executed until the first call to the iterator's next() method. What's supposed to happen when someone pushes additional values in before the first call to next()? How is the function supposed to declare what values may be pushed in? You're simply not going to persuade Guido that arbitrary values should be pushed. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From reply.in.the.newsgroup at my.address.is.invalid Mon Nov 24 19:12:41 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 25 Nov 2003 01:12:41 +0100 Subject: Adding new methods at runtime to a class References: Message-ID: val: >In the *real-world* programming, including embedded systems and >environment-driven systems, often you have no idea what may >happen next This is true. >and you don't have a luxury to design and build your program ahead. You mean in the real world programs are build afterwards? >You still can analyze the current (run-time) situation and build >your response on-the-fly, dynamically. Right. Firtst let it run, than implement it once its running, and finally design it when its done :-) -- Ren? Pijlman From a.schmolck at gmx.net Sat Nov 15 20:00:20 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 16 Nov 2003 01:00:20 +0000 Subject: plotting data against a time axis References: Message-ID: Gerrit Holl writes: > Hi, > > I have a dictionairy containing DateTime objects as keys and integers as > values. What would be the easiest way to create a simple plot of these, > with a number axis versus a time axis? What library is the most > suitable for this? 'plot' on parnassus yields 18 hits, but since I have > zero experience, I don't know where to start. What makes it difficult > is that I have a time axis instead of a simple integer x-axis. Gnuplot > doesn't seem to be able to do this, or does it? > gnuplot G N U P L O T Version 3.8j patchlevel 0 last modified Wed Nov 27 20:49:08 GMT 2002 Terminal type set to 'x11' gnuplot> help time Ambiguous request 'time'; possible matches: time/date time_specifiers timefmt timestamp Not what you want? 'as From jjl at pobox.com Wed Nov 5 10:57:35 2003 From: jjl at pobox.com (John J. Lee) Date: 05 Nov 2003 15:57:35 +0000 Subject: bash Vs python ?? References: <84fc4588.0311050214.4133e333@posting.google.com> Message-ID: <87llquyfio.fsf@pobox.com> Ville Vainio writes: > pythonguy at Hotpop.com (Anand Pillai) writes: [...] > Some people's idea of optimization is selecting the worst tool that is > tolerable for any particular tasl. That way, no tool feels > neglected. If no language of "just right" amount of suckage is > available at the moment, it needs to be implemented. :-))) You have that right! John From dw-google.com at botanicus.net Thu Nov 13 06:53:26 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 13 Nov 2003 03:53:26 -0800 Subject: Python array syntax in PHP References: Message-ID: <99dce321.0311130353.534e061a@posting.google.com> Dave Benjamin wrote in message news:... > There was a recent proposal on the PHP-DEV list to add a syntax similar to > Python's for arrays (in PHP, arrays serve as both lists and dictionaries, > though usually not at the same time. ;) Though several of the language > developers were marginally positive about the idea, I found it interesting > how much of a controversy ensued. I find it interesting that the lead arguments against the syntax are that of "there shouldn't be more than one way of doing things", and "this is an unnecessary change", coming from a development team who recently added iterators to their language after it had gone into beta. I promised myself that I would write an HTML hate-rant on PHP for my web site. I'll get around to it someday. Roughly, the conclusion would be: a) Don't ever touch PHP. b) Don't ever mention your PHP 'skills' or experience on your CV or to your friends. Rest assured someone will find a steaming pile of crap for you to work on. c) If you are handed an existing PHP project to work on, rewrite in another (say 'any other') language immediately. Don't port, you will only carry the satanic anti-structure of the PHP application with you. Rewrite all related documentation, schemas, and concepts. Don't spare a single byte - you won't be free of the curse until all the children are dead.. d) Time and cost are no exception to c). If this argument is proposed, dispel it with: "how much time and cost will be involved in keeping this application maintained, and running on future PHP releases?" Shoot to kill if they don't accept this. Follow these simple steps and you will find true peace. :) David. From FBatista at uniFON.com.ar Wed Nov 12 08:56:39 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 12 Nov 2003 10:56:39 -0300 Subject: Automating FTP file transfers Message-ID: Limey Drink wrote: #- Basically I need to... #- 1. Check on the local system for new files in a specific directory #- If new files exist then... #- 2. Connect to a remote FTP server. #- 3. Transfer local files to a specific directory on the #- remote FTP server. #- 4. Then remove/archive local files and end session. Little piece of code that automates FTP, putting files whose names were passed as args: import sys from ftplib import FTP lnomarch = sys.argv[1:] dir = '/local/BACKUP/logs' machine = 'masbue' transported = [] print "Opening conection" ftp = FTP(machine) ftp.login('myUsername', 'myPassword') ftp.cwd(dir) for nomarch in lnomarch: print "Putting", nomarch arch = open(nomarch, 'r') nombrebase = os.path.basename(nomarch) transported.append(nombrebase) ftp.storbinary('STOR ' + nombrebase, arch) arch.close() ftp.quit . Facundo From mis6 at pitt.edu Sat Nov 15 09:45:29 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 15 Nov 2003 06:45:29 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> <2u1tb.25127$hV.934365@news2.tin.it> <2259b0e2.0311142313.62a73078@posting.google.com> Message-ID: <2259b0e2.0311150645.58cb9a17@posting.google.com> "Andrew Dalke" wrote in message news:... > Michele Simionato: > > I lived < 50 meters from Barnes & Noble, still I bought my Python books > > from Amazon.com. For instance "Python in a Nutshell" was available on-line > > before than in the libraries, with 30% discount and free shipping. It > > arrived in a couple of days. > > Try also bookpool.com for technical books. PiaN is 43% off. With > 3-4 day UPS ground it's $24.12, which for a book with list price of > $34.95 means it's 31% off. And you can get cheaper shipping if you > are willing to wait longer. > > Andrew > dalke at dalkescientific.com Unfortunately I am in Italy now, and we don't have Amazon.it or something equivalent yet (I am hoping I am wrong ...) Michele From max at alcyone.com Mon Nov 17 14:24:54 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 17 Nov 2003 11:24:54 -0800 Subject: True inconsistency in Python References: <3FB8847F.6CB1BECA@alcyone.com> Message-ID: <3FB92086.9CBD0761@alcyone.com> Ron Adam wrote: > To me the usefulness of using True and False is that it is defined to > values consistent with the programming language that you are using. I agree, insofar as the value of True and False as constants is that now have values set aside which mean _nothing_ but their Boolean values. This is very helpful for writing self-documenting code, something which I've always been a strong supporter of. If I have code where 0 or 1 gets assigned to a variable, I'm going to have to look at the whole block to tell precisely what that's being used for: Is it a counter variable, a three-state value (say, -1, 0, and +1), is it an enumerated value type, or is it a Boolean? If I'm scanning code and I see x = True then I know right away that what I'm looking at is a variable used as a Boolean. (Of course, in proper self-documenting code, the variable would be named something more helpful than `x', but you see my point.) > So using them to assign x = True, or x = False. insures that when I > do: > > x = True > if x: > .... > > So I get consistent results for the language and platform I'm using > now and in the future. If down the road someone decided to make True > = 3, and False = -5, and they change the language so that any boolean > comparisons return 3 and -5 respectively, my use of True and False > will still work. If I tested for 1 or 0 using the 'if x:' method, > then my program will break. While this may be true in some sense, I don't think this is a powerful argument for using True/False. The chances of this happening are utterly remote, since it would break practically all code. (Obviously you weren't suggesting it was a real possibility given your choices of the alternate constants, but still.) I don't consider insulation from something utterly implausible happening very persuasive, since I'm not worried about that utterly implausible thing happening. I find explicit Boolean constants available for writing self-documenting code much more compelling. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ Why don't you grow up for crying out loud? -- Capt. Benjamin "Hawkeye" Pierce From dave at pythonapocrypha.com Wed Nov 12 18:00:41 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 12 Nov 2003 16:00:41 -0700 Subject: What's an "atomic" operation (in a threaded context)? References: Message-ID: <075401c3a970$cc650670$891e140a@YODA> Paul Moore wrote: > I can't find anything which spells this out in the manuals. I guess > that, at some level, the answer is "a single bytecode operation", but Bytecode instructions are atomic in that you won't switch to another Python thread "mid-bytecode", but that's only sorta interesting. ;-) > This thought was triggered by a comment on the Python Cookbook site, > which basically said that it was OK to do > tss = {} > ... > id = thread.get_ident() > tss[id] = {} > > (where tss is a global) without a lock, because id is unique to the > thread. > > But couldn't this result in 2 threads allocating a new entry in tss at > the same time, and so get tss in an inconsistent state? This is what's more interesting: object access is threadsafe in the sense that you can't get Python's internal data structures into an inconsistent state via pure Python code (or, for that matter, well-behaved C extensions). IOW, the above code won't ever crash the interpreter or screw up Python's internal state. Even if two different threads did tss[5] = (both setting a value using the same key) you wouldn't get an inconsistent internal state, although you would obviously have no guarantees about the ordering of the operations - you'd never know if thread A or thread B changed it last. > Can anyone clarify this for me? I'd like to avoid littering my > threaded code with huge numbers of unnecessary locks... The above applies to CPython - I'm not too sure about Jython. If you're pretty familiar with multithreading in other languages and view Python's built-in data types as fundamental types like integers, then the rules for when to use locking are pretty much the same as in other languages. -Dave From theller at python.net Fri Nov 14 15:07:48 2003 From: theller at python.net (Thomas Heller) Date: Fri, 14 Nov 2003 21:07:48 +0100 Subject: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <653b7547.0311121826.65b6b2d4@posting.google.com> Message-ID: Alex Martelli writes: > Terry Reedy wrote: > ... >>> personally argued that reduce() should be removed from the language, >>> but I do agree that it does not have to be part of "core" Python, >>> and could easily be relegated to a module.) >> >> If the builtins are reduced in 3.0, as I generally would like, I would >> be fine with moving apply, map, filter, and a repaired version of >> reduce to a 'fun'ctional or hof module. But the argument of some >> seems to be that this batteries-included language should specifically >> exclude even that. > > A functional module would be neat. A great way to enhance the chance > that there will be one would be starting one today (e.g. on sourceforge), > ideally with both pure-Python and C-helped (or pyrex, etc) implementations, > and get it reasonably-widely used, debugged, optimized. I would suggest: don't move the implementation to C too fast or too much of the code. With pypy on the horizon, this may never be needed (?). Thomas From peter at engcorp.com Mon Nov 24 22:41:10 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Nov 2003 22:41:10 -0500 Subject: import freeze References: <3fc2c417$1@news.iconz.co.nz> Message-ID: <3FC2CF56.4312A00E@engcorp.com> Colin Brown wrote: > > I have a Pyro server thread that is not starting and I have traced the > problem through to the a point in the Pyro code where it freezes. The code > fragment (my added print statements): > > print '[finalizeConfig_Server] before import random' > import random > print '[finalizeConfig_Server] after import random' > > is printing the first print line but not the second. Is there any way of > dynamically turning on in-depth tracing before the import statement? > [Py2.3.2, Win2K] Not sure about tracing per se, but if you can run the server program without detaching from the console, the following two lines of code can be exceptionally helpful: import pdb pdb.set_trace() This lets you manually single-step through the code to find the source of the trouble (and other features, probably including some real tracing). -Peter From news at u-schramme.de Thu Nov 13 01:26:29 2003 From: news at u-schramme.de (Ulrich Schramme) Date: Thu, 13 Nov 2003 07:26:29 +0100 Subject: Palindrome In-Reply-To: References: <20031112223135.29045.00000109@mb-m12.aol.com> Message-ID: Georgy Pruss wrote: > Knowing what your program should do, could also help. > G-: > As far as I know is a palindrome a word that you can read from both sides. Sorry, but English is not my native language. So I don?t have an English example handy. But the German name 'OTTO' is a palindrome. -- -- Ulli www.u-schramme.de From mlh at furu.idi.ntnu.no Mon Nov 24 11:10:18 2003 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Mon, 24 Nov 2003 16:10:18 +0000 (UTC) Subject: minidom nodes without a document? References: <8b5e42a6.0311231738.6376d486@posting.google.com> Message-ID: In article <8b5e42a6.0311231738.6376d486 at posting.google.com>, Levente Sandor wrote: >mlh at furu.idi.ntnu.no (Magnus Lie Hetland) wrote in message >news:... >> Is it possible to build a minidom tree bottom-up without access to a >> document node? It seems that simply instantiating the various node >> classes doesn't quite do the trick... > >I'm not sure what you mean exactly by "without access to...". You need >a Document instance to create the elements, but they aren't added >automatically to it. > [snip] Right. I understand this. Thanks to you and Martin for mentioning it, though :) My problem is that I'm building the DOM as part of a bottom-up parse, where the various subtrees are build independently from each other, through callbacks that are set as part of the parser. So... For all of these to have access to a document object (so they can use the createFoo methods) I'd have to either (1) hard-code a document into the parser (meaning, basically, that each parser instance can only be used once), or (2) refactor the parser to supply a context object to each callback (which could be, for example, the document object). I guess the latter is the way to go, but it does seem awkward that it should be necessary. In my case it's OK, as the parsing code is part of my project, but if I used an external parser, I'd have to create a separate AST and then translate that into a DOM tree afterward; a bit unnecessary... Oh, well. Can't argue with the DOM, I suppose :) -- Magnus Lie Hetland "In this house we obey the laws of http://hetland.org thermodynamics!" Homer Simpson From a.schmolck at gmx.net Sun Nov 23 17:07:28 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 23 Nov 2003 22:07:28 +0000 Subject: Use of GPLed Python extension modules References: <7xu14xdu8a.fsf@ruckus.brouhaha.com> <7xislcjh4k.fsf@ruckus.brouhaha.com> <7xwu9svyny.fsf@ruckus.brouhaha.com> <7xvfpcowjt.fsf@ruckus.brouhaha.com> <653b7547.0311222346.b4d9e98@posting.google.com> Message-ID: Ville Vainio writes: > pmaupin at speakeasy.net (Patrick Maupin) writes: > > > restrictive). So it would appear that the FSF has no real legal > > ability under the GPL to keep someone from writing and distributing > > a package which uses readline, as long as that person does not > > simultaneously distribute readline itself. > > In the light of this, does releasing a library under GPL (as opposed > to LGPL) make any sense at all? Well Stallman says the above wrong, have a look at how clisp became GPL. 'as From sorry_i_am_tired_of_spam at refuse.com Thu Nov 27 02:40:15 2003 From: sorry_i_am_tired_of_spam at refuse.com (David McNab) Date: Thu, 27 Nov 2003 20:40:15 +1300 Subject: Choosing the right framework References: Message-ID: On Wed, 16 Jul 2003 14:54:16 +0200, Carsten Gehling paused, took a deep breath, then came out with: > Oh how often this subject may come up... > > The thing is, I've come to the decision of abandoning PHP as much as > possible (old projects still remain...), and use Python for all purposes. > Reason: One language to fit it all (instead of having one language for > webprogramming, one for batches, etc...) > > I stand now at the point where I must choose a framework for my web > application development. I've skimmed a few: mod_python, pso and Zope. > However, I cannot decide on which to choose. I've been working on an HTML generation framework called 'pyWeb'. Just posted to this ng yesterday, calling for testers. You might like to visit http://www.freenet.org.nz/python/pyweb and have a look. Cheers David > I've read descriptions and comments on > http://www.python.org/cgi-bin/moinmoin/WebProgramming to get other's > opinions. The user comments are sparse though, so I've decided to ask here. > > I like the ideas behind Zope. For instance the "long running process" > feature that improve performance and retain scripts between requests, among > other things. I do not, however, like the design of the management > interface, it would not appeal to my customers. I'm not yet knowledgable > enough about Zope, to know if this can be changed. Anyone who can elaborate? > (MaxM don't answer "Plone"... ;-) > > mod_python seems the choice, if I want the feature of retaining scripts in > memory between requests and want to write my own managemen interface. I > don't know, if it allows for application variables (variables shared > globally between sessions). > > pso looks like the framework that is easiest to deploy. If run under > mod_python, it also retains scripts in memory, but does it allow for the > aforementioned application variables? And does the performance match up > compared to mod_python and Zope? > > It'll probably be run behind an Apache httpd server, so I guess Twisted is > out of the question. > > What is your preferred framework? And why? > > To those who would ask "What do you want to do with it", the answer is: > General purpose web application development. Porting (enhancing) of my > existing CMS (built in PHP - it's badly in need of a rewrite, so the time is > right for changing to Python). > > I am to start on a new web project in the beginning of next week, and I > would like to use this opportunity to make the switch from PHP to Python. > Which is why I ask and don't just spend 2+ more weeks to dig further into > the above mentioned frameworks before making the decision. > > - Carsten From francisgavila at yahoo.com Sun Nov 30 04:30:49 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 30 Nov 2003 04:30:49 -0500 Subject: Bug in glob.glob for files w/o extentions in Windows References: Message-ID: Georgy Pruss wrote in message ... >OK, you can call it not a bug, but different behavior. That's true. But calling dir's behavior "different" here is quite a euphemism! >It seems that in any case I'll have to extract 'nnn' by myself. >Something like: > > if mask.endswith('.'): # no extention implies actually no dots in name at all > list = glob.glob( mask[:-1] ) > list = filter( lambda x: '.' not in x, list ) # or [x for x in list if '.' not in x] > else: > list = glob.glob( mask ) > I don't understand where 'mask' is coming from. If you want files with no dots, just filter out those files: filelist = [file for file in glob.glob('*') if '.' not in file] Or you can use sets: symmetric difference of all files against the files with dots. If you're trying to recast glob in windows' image, you'll have to specialcase '*.*' too. And then what do you do if someone comes along who *really* wants *only* names with dots in them!? Trying to shoehorn windows-style semantics into glob is just braindead--the windows semantics are wrong because dots are not special anymore. For one thing, we can have more than one of them, and they can be anywhere in the filename. Both were not true for DOS, whence windows inherited the *.* nonsense. Behold the awesome visage of the One True Glob (TM): (Not that I'm starting a holy war or anything ;) *.* -> Filename has a dot in it, and that dot cannot be the first or last char. This is NOT the same as '*'!! .* -> Filename has a dot as the first character. *. -> Filename has a dot as the last character. * -> Gimme everything. -- Francis Avila From anabell at sh163.net Tue Nov 11 23:30:22 2003 From: anabell at sh163.net (achan) Date: Wed, 12 Nov 2003 12:30:22 +0800 Subject: Metaclass' __init__ Does not Initialize Message-ID: As I was trying to create a metaclass, I found out that __init__ defined in it does not initializes at all: class CMeta(type): def __new__(cls, ClassName, BaseClass, ClassDict): def __init__(self): for k in self.__slots__: k = 'something' NewDict = {'__slots__': [], '__init__': __init__} for k in ClassDict: if k.startswith('__') and k.endswith('__'): if k in NewDict: warnings.warn("Can't set attr %r in bunch-class %r" % (k, ClassName)) else: NewDict[k] = ClassDict[k] else: NewDict['__slots__'].append(k) return type.__new__(cls, ClassName, BaseClass, NewDict) class CNewType(object): __metaclass__ = CMeta a = 'nothing' b = 'nothing' c = 'nothing' >>> x = CNewType() something something something >>> x.a Traceback (most recent call last): File "", line 1, in ? AttributeError: a ------------->>> Non-existent! class CMeta(type): def __new__(klass, name, base, dict): def __init__(self): for s in seq: s = 123 print s newDict = {'__init__': __init__, seq = []} return type.__new__(klass, name, base, newDict) class Test(object): __metaclass__: CMeta >>> a = Test() >>> From mwilson at the-wire.com Tue Nov 11 09:58:54 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 11 Nov 2003 09:58:54 -0500 Subject: Pruss Manifesto - Long numbers References: <2259b0e2.0311101009.59a5ed2e@posting.google.com> Message-ID: In article <2259b0e2.0311101009.59a5ed2e at posting.google.com>, mis6 at pitt.edu (Michele Simionato) wrote: >> Georgy Pruss wrote: >> 1) Underscores in numbers. It will help to read long numbers. >> E.g. >> 12 345 678 >> 3.14159 26535 89793 23846 > >Typically, long numbers are not in the program code, but in an >external data file. Then, they can be read as strings and converted >to numbers with a one-liner: > >>>> def i(x): return int(x.replace(" ","")) >... >>>> i("1 234") >1234 > >So, this "feature" is not worth the effort, IMHO. Except in some cryptological code, e.g. DES, Blowfish. But the 'i' solution works just as well inside a program. def h (s): return int (s.replace ('_', ''), 16) def ks0tbl (): return map (h, ( 'd131_0ba6', '98df_b5ac', '2ffd_72db', 'd01a_dfb7', [page (printed, not screen) of hex constants] '53b0_2dfd', 'a99f_8fa1', '08ba_4799', '6e85_076a' )) ks0 = ks0tbl() del ks0tbl Regards. Mel. From vincent at visualtrans.de Wed Nov 26 14:07:01 2003 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 26 Nov 2003 20:07:01 +0100 Subject: Problem with PyRun_SimpleFile and MFC Application References: <188007e5.0311251232.6c4b6254@posting.google.com> <188007e5.0311260352.1389b5ad@posting.google.com> Message-ID: "Susanne" schrieb im Newsbeitrag news:188007e5.0311260352.1389b5ad at posting.google.com... | Hello together, | | after reading your comments, i looked, which configuration | im using in my console app. Its a release app. | Than i tried to run it as a debug app and now the | programm crashes like my mfc app. | | So the hint with the debug dll was good. | | But how can i get this dll? | I don't have the python source code and i also | can't find it in the internet. | So there is no way to create it by myself. | | Can anyone of you help me again?? | | Thanks | Susanne Download the Python source (e.g. http://www.python.org/ftp/python/2.3.2/Python-2.3.2.tgz or the version you want to use) and untar it to disk. You will end up with a directory "Python-2.3.2". In this directory you will find a directory called "PCBuild" with the relevant MSVC workspaces already nicely lined up. Look at the pythoncore and build it in debug mode (python23_d.dll). If you want to do extensions at some time, make sure you compile a python_d.exe for debugging purposes too. Regards Vincent Wehren (PS: ~snipped cross-post to comp.lang.c++ to avoid angry neighbors....) From jon+usenet at unequivocal.co.uk Mon Nov 24 12:45:12 2003 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 24 Nov 2003 17:45:12 GMT Subject: Question regarding thread atomicity Message-ID: If I have the following line of Python code: self.foo.bar += 1 where 'foo' is an instance of an object and 'bar' is an integer, is that thread-safe? i.e. will the GIL mean that it is reliable, or do I need to manually add locking around it? From tweedgeezer at hotmail.com Fri Nov 14 16:55:05 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 14 Nov 2003 13:55:05 -0800 Subject: asyncore/asynchat References: Message-ID: <698f09f8.0311141355.2430c07b@posting.google.com> "F.G.Testa" wrote in message news:... > How do I access the underlying list/map/array of AcmeChannel? > Thank you. There is none, but feel free to keep one yourself; I've done that, for instance, when I want to limit the number of connections to a server that should (barring malicious clients) have very fast sessions. Jeremy From djones at shcorp.com Fri Nov 7 16:55:17 2003 From: djones at shcorp.com (Dan Jones) Date: Fri, 07 Nov 2003 16:55:17 -0500 Subject: binary string question Message-ID: <1068242117.17201.143.camel@pc72.shcorp.com> Hello, I'm trying to figure out how to get bit operators to work on a binary string. This is what I'm trying to do: list(frame) #where frame is a binary string y = frame[x] << 8 It gives me a TypeError. Whats the best way to get around that? I think the struct module may be what I'm looking for, if so could someone give me an example? Also, is there a better way to be able to access individual bytes than converting the string to a list? Thanks, Dan Jones From r at msolutionsinc.com Wed Nov 19 16:53:51 2003 From: r at msolutionsinc.com (Rob McMonigal) Date: Wed, 19 Nov 2003 16:53:51 -0500 Subject: using autoit and ctypes Message-ID: Hi, I am using Autoit to do a little gui scripting. I am currently using the ActiveX version with the win32com package. I first tried to use the dll version with the ctypes library. The calls work with the dll version, but I always get the following error: Traceback (most recent call last): File "test.py", line 8, in ? autoit.AUTOIT_WinActivate("Inbox - Microsoft Outlook" , "") ValueError: Procedure called with not enough arguments (8 bytes missing) or wrong calling convention Code is as follows -------------------------- from ctypes import * autoit = cdll.LoadLibrary("c:\\autoit\\autoitdll.dll") autoit.AUTOIT_WinActivate("Inbox - Microsoft Outlook" , "") -------------------------- Can someone tell me why I'm getting that error? Thanks, Rob From max at alcyone.com Thu Nov 13 17:51:00 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 13 Nov 2003 14:51:00 -0800 Subject: How sum() should really be done References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <653b7547.0311121826.65b6b2d4@posting.google.com> Message-ID: <3FB40AD4.9428C78A@alcyone.com> Douglas Alan wrote: > Ah, that reminds me -- both sum() and reduce() can be removed from > Python by extending operator.add so that it will take any number of > arguments. reduce can't, since reduce doesn't require the function passed to be operator.add. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ The golden rule is that there are no golden rules. -- George Bernard Shaw From bdesth.nospam at removeme.free.fr Sat Nov 29 20:32:05 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Sun, 30 Nov 2003 02:32:05 +0100 Subject: Need some advice In-Reply-To: <2idisv45km5c64v2iqn7mj7pim3l1f4hpk@4ax.com> References: <2idisv45km5c64v2iqn7mj7pim3l1f4hpk@4ax.com> Message-ID: <3fc94499$0$28619$636a55ce@news.free.fr> Jeff Wagner wrote: > I am in the process of learning Python (obsessively so). I've been through a few tutorials and read > a Python book that was lent to me. I am now trying to put what I've learned to use by rewriting that > Numerology program I wrote years ago in VB. > > There are times I am totally stuck (for instance, I just had an idea to put the numerical values of > the alphabet and months of the year in a dictionary located in a function. Then, I can import the > dictionary I need from that function ... well, I'm getting import errors). "import the dictionnary from a function" ???? > So the question is this ... when I get stuck like this and seem to be banging into walls with > everything I try, is it better to continue trying different things Definitively, *no*, niet, nein, non, etc... If you don't know what you're doing, it's not programming, it's a story about monkeys, typewriters and Shakespeare. > or stop, take a break and go back > to reading a tutorial or a Python book? Should be one of the first thing to do. You won't do anything good if you don't know enough of the language. > Or is it better that after I've tried everything I can think > of, "trying everything [you] can think of" is not programming. See above... > I just post the question here, get the answer and move forward? First try to know what you're trying to do, and why you're trying to do it this way. Ask yourself if this is the best way (or at least the most obvious way) to do it with the language. Then look thru your tutorials, books, etc to see how this can be done. Don't forget that the Python shell is a great tool. If then you're still stuck, you're of course welcome to post your question here, with explanation about what you're trying to do and what you're stuck with !-) My 0.2 cents Bruno From aleax at aleax.it Wed Nov 12 06:25:07 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 12 Nov 2003 11:25:07 GMT Subject: Regular expression code implementation review between Tcl vs Python References: <394af34.0311110758.3b1781ea@posting.google.com> <3fdsb.10497$hV.431113@news2.tin.it> Message-ID: Rainer Deyke wrote: > Alex Martelli wrote: >> Using an OO language doesn't necessarily make implementing another >> OO language any easier, when the object models are mismatched (and >> they almost invariably are). > > Using RAII to automate reference count management would certainly help in > implementing Python, even if it is a feature that Python itself doesn't > have. Yes, C++ surely has plenty of features -- including RAII, templates, etc -- that might come in useful, quite apart from Python and/or C++ "being OO". You can see that in extensions written with "Boost Python" -- you end up using _FAR_ less boilerplate, both for reference counting and other housekeeping and interfacing tasks. However, for the size and speed of the resulting code you end up somewhat at the mercy of your C++ compiler, and I'm not sure they're anywhere near as optimized as C compilers, yet -- it IS a MUCH larger and more complicated language, after all. The problems that C++'s size and complication give to its compilers (and may, by now, be overcome in the very best compilers -- I do believe that after these many years there ARE compilers which do claim 100% compliance with the standard, for example, though I don't know about quality of optimization) pair up with those given to its users -- the price to pay for that wonderful plenty of features, of course, and the awesome _potential_ for speed (even though there may be yet some time to wait until the full extent of that potential is actualized by super optimizers). There's a long-standing debate on whether big languages can be effectively subsetted, identifying a set of features that can be counted on to be solidly and optimally implemented on all the relevant compilers and ensuring no features outside that set are ever used -- thus allowing programmers to only learn "half" the language, or some such fraction. I believe this doesn't work, except perhaps in a tightly knit group of Extreme Programmers who are really keen to enforce the group-mandated subsetting rules -- and even then, slight mistakes may end up in "correct" code that however strays from the blessed subset and produces symptoms which you need complete knowledge of the language to understand. So, my opinion is that if an open-source project adopted C++, it would basically require contributors to make the effort to learn the whole C++ language, not just half of it. _Some_ OS projects, such as Mozilla or KDE, appear to thrive on C++, I believe, and enforce SOME subsetting effectively. I'm not sure exactly what dynamics are at play there, since I'm not a part of those projects. Still, C still dominates the opensource scene -- C++ has a much smaller presence there. Alex From magnus at thinkware.se Sat Nov 22 12:38:12 2003 From: magnus at thinkware.se (Magnus Lyck?) Date: 22 Nov 2003 09:38:12 -0800 Subject: for what are for/while else clauses References: Message-ID: <258fd9b8.0311220938.3210484c@posting.google.com> "Fredrik Lundh" wrote in message news:... > the break statement has nothing to do with the else clause; the else > is executed when there's no more item in the sequence. if you break > or raise or return or yield-and-never-resume or call-and-never-return > your way out of the loop doesn't matter. On the other hand, I only think it's in the case of a break in block that... while condition: block else: print "Loop finished" ...will behave differently than... while condition: block print "Loop finished" So, unless you use a break in the block, the else statement is just noise: an extra line of code and additional whitespace for the following statement(s). It's only together with the python idiom of breaking out of loops with ifs (which is considered bad form in some (non python) circles that the else part of the for and while statements make sense. From jjl at pobox.com Mon Nov 3 08:06:48 2003 From: jjl at pobox.com (John J. Lee) Date: 03 Nov 2003 13:06:48 +0000 Subject: Selling Python Software References: Message-ID: <8765i1d2jb.fsf@pobox.com> Alex Martelli writes: [...] > "Can not be decompiled" is impossible whatever language you're using. > > "*extreme* difficulty" is in the eye of the beholder. You can e.g. > add layers of encryption/decription to the bytecode, etc, but whatever > you do somebody else can undo. Depending on the relative skills of > you and the "somebody else" the ratio (your effort to keep things > secret, to theirs to uncover them) can be any. [...] Whie this is all true, you seem to put undue emphasis on the fact that it's always *possible* to decompile stuff. Isn't the point you make in your last sentence actually crucial here? The game is to make your opponent (customer ;-) incur more expense in decompiling it than it would cost to just go ahead and pay you, is it not? And yeah, you also have to take into account how much it costs you to come up with the protection scheme, of course. So, is there a good practical solution of that form, for Python code of this sort of size (or any other size)? I suspect the answer for standard Python may be no, while the answer for optimising compilers may be yes -- but that's just a guess. John From juntu at operamail.com Wed Nov 26 10:35:40 2003 From: juntu at operamail.com (Juntu) Date: 26 Nov 2003 07:35:40 -0800 Subject: pymat and Matlab6.5 Message-ID: To who read this message: I am trying to use pymat with python2.3 and matlab6.5 but unfortunatlly it does not work because it is intended for python2.2. I tried to recompile the source code to make it work with matlab6.5 and python2.3 platform but it does not work for my at all. Is there any one in this plant who have already the compiled library and sned it to me by email or post it in the internet in the Python web site. Thank you all. Junnty From tdelaney at avaya.com Mon Nov 24 17:53:41 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 25 Nov 2003 09:53:41 +1100 Subject: Bug or Feature? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DEEEC330@au3010avexu1.global.avaya.com> > From: David Eppstein > > It is very useful that ImmutableSet is closed under set operations. > By making the set operations copy the types of their arguments, the > author of sets.py was able to achieve this without > duplicating each set > operation's implementation. If you don't like this behavior you can > always override it... So what happens when I make a set subclass that takes no parameters (other than self) to __init__? Tim Delaney From aleax at aleax.it Wed Nov 5 13:29:50 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 05 Nov 2003 18:29:50 GMT Subject: How to list the superclassesof an object References: Message-ID: Fernando Rodriguez wrote: > On Wed, 05 Nov 2003 16:17:11 GMT, Alex Martelli wrote: > > >>>>> x.__class__.__bases__ >>(, ) > > I didn't know the existence of the __bases__ attribute, and it doesn't > show > with dir(). How can I get a list of ALL the attributes of an object? try hasattr(x, somest) for all identifier strings somest (up to whatever length you're comfortable with). Nothing stops an object from 'inventing' attributes on the fly when queried about them, e.g: class allem(object): def __getattr__(self, name): return name x=allem() now x 'has' ANY attribute you can name, in the sense it will give a value for x.supercalifragilisticexpialidocious and so on. How else save by exhaustive search could you find this out...? > I thought that dir() listed every attribute.... O:-) No, it can't take days every time you call it;-) >>You may need a recursive walk up the (DA) graph if you also want >>bases of bases, etc, among 'superclasses'; alternatively, but >>ONLY for newstyle classes (recommended anyway for many reasons): > > I haven't used python in a while and all my classes are 'old style'. I'd > like to get up to date. Where can I find info about the differences / > advantages of > these new classes? Is it safe to convert all my previous classes to new > ones, and how can I do it? O:-) I suggest peeking at the OO chapter of Python in a Nutshell -- I think I cover the issues decently (do it for free by subscribing at safari.oreilly.com and canceling before 14 days, since the first 2 weeks are free). Alex From exarkun at intarweb.us Tue Nov 18 13:15:29 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 18 Nov 2003 13:15:29 -0500 Subject: good ways to convert string into time In-Reply-To: <731fc603.0311180958.32135957@posting.google.com> References: <731fc603.0311180958.32135957@posting.google.com> Message-ID: <20031118181529.GA15058@intarweb.us> On Tue, Nov 18, 2003 at 09:58:08AM -0800, Hank wrote: > hi, > > i have a string as follows > > 18Nov2003:18:23:43:405 > > Is there an easy way to convert that to absolute time? What i really > want to do is to parse these times from a log file and do time > comparisons, averages, stop minus start (elapsed). > > Probably create my own conversion table i guess? time.strptime http://www.python.org/doc/lib/module-time.html > > thanks > -- > http://mail.python.org/mailman/listinfo/python-list > From bkelley at wi.mit.edu Mon Nov 24 12:23:41 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Mon, 24 Nov 2003 12:23:41 -0500 Subject: small, fast and cross-platform flat-file database for python In-Reply-To: References: <425cc8d1.0311210915.33eb10e0@posting.google.com> Message-ID: <3fc23e5c$0$575$b45e6eb0@senator-bedfellow.mit.edu> Tom Wilkason wrote: > > Have you looked at metakit ( http://www.equi4.com/metakit/python.html ), it > meets requirements 1-4 on your list above. And best of all there is an sql binding: http://www.mcmillan-inc.com/mksqlintro.html There is a learning curve to using metakit at full strength, I have been trying to update the documentation, a preview is available here: http://jura.wi.mit.edu/people/kelley/tutorial/python.html I have successfully used metakit in a fairly large application and couldn't be happier with the results. The best thing about metakit is that you can view millions of records in a nice view with ease: See KitViewer here http://jura.wi.mit.edu/people/kelley/ You can try out the binary and load in a csv file to play around. > > Tom > > From simonb at webone.com.au Sun Nov 16 02:44:36 2003 From: simonb at webone.com.au (Simon Burton) Date: Sun, 16 Nov 2003 18:44:36 +1100 Subject: Playing a .wav file in MAC OSX with Python 2.2 without visuals. References: <857b782c.0311151600.47daf7b8@posting.google.com> Message-ID: On Sat, 15 Nov 2003 16:00:29 -0800, Christopher Mahan wrote: > Have a python XMl-RPC interface to a client's site. He wants an > audio-only reminder to play a wav file. On Mac. > > Any ideas? (3 hours of Googlin and still nothing) > > Thanks in advance > > Christopher Mahan pygame Simon. From reply.in.the.newsgroup at my.address.is.invalid Mon Nov 17 15:07:12 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 17 Nov 2003 21:07:12 +0100 Subject: socket object, connection refused ... References: Message-ID: <5fairvk5veee54g1ggq3mnc6is2ptcfcbp@4ax.com> Maxim Olivier-Adlhoch: >using 'localhost' or '127.0.0.1' always works, using my actual machine's ip or its hostname does not!! What is the server socket binding to? "Connection refused" normally means there is no server listening for connections on the specified IP/port-combination. -- Ren? Pijlman From tim.golden at viacom-outdoor.co.uk Thu Nov 13 03:42:06 2003 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 13 Nov 2003 00:42:06 -0800 Subject: STrange error importing win32gui References: <3fb27d5f.57321764@news.cybermesa.com> <87fzgtfm8c.fsf@pobox.com> Message-ID: <8360efcd.0311130042.60b25835@posting.google.com> jjl at pobox.com (John J. Lee) wrote in message news:<87fzgtfm8c.fsf at pobox.com>... > joconnor at cybermesa.com (Jay O'Connor) writes: > > > I'm using Python 2.3 on windows and trying to use the win32 libs. I > > keep getting the following error > > > > >>> import win32gui > > > > Traceback (most recent call last): > > File "", line 1, in -toplevel- > > import win32gui > > ImportError: DLL load failed: A device attached to the system is not > > functioning. > > > > I'm not sure what it means ot how to fix it. Any thoughts? > > Don't you just love those informative Windows error messages? > > I had that error message before (can't remember the circumstances), > and never found out what the problem was. Had to work around it > rather than fix it. > > > John When I've had these errors, it's usually indicated that -- at some point -- one of my network drives has gone down, especially but not limited to the one I'm hosting my python-site-packages directory on. Forcing a reconnection to the drive (ie net use /del followed by net use) seems to solve it, even if the drive is by now up and running again. YMMV TJG From kmneilso at REMOVEyahoo.com Sun Nov 9 15:22:36 2003 From: kmneilso at REMOVEyahoo.com (Kerry Neilson) Date: Sun, 09 Nov 2003 20:22:36 GMT Subject: sharing dictionaries amongst class instances Message-ID: Hi, Really hung up on this one. I'm trying to get all the fields of a dictionary to be unique for each class: class A { my_dict = [] dict_entry = { 'key1':0, 'key2':0 } __init__(self): for x in range(10): tmp = copy.deepcopy(self.dict_entry) tmp['key1'] = x self.my_dict.append(tmp) } in a driver, I have inst0, inst1 = A.A(), A.A() inst0.my_dict[1]['key2'] = "ted" inst1.my_dict[5]['key2'] = "steve" inst0.display() inst1.display() printing them out shows that both objects have ted and steve in their dictionaries. I have done this very thing outside of a class, and it works wonderfully. All other attributes in the class are able to remain unique. ie, inst0.data = 5 and inst1.data = 8 works fine. I believe I could set the dictionaries up beforehand, but they will be substatially different sizes, and it certainly wouldn't be proper. Any ideas? Thanks very much for any insight. From dave-au_member at newsguy.com Thu Nov 13 15:50:18 2003 From: dave-au_member at newsguy.com (dave-au) Date: 13 Nov 2003 12:50:18 -0800 Subject: newbie need help on python-2.3.2 installation Message-ID: Hi: I was trying to install python on solaris 9 and failed: root at system:~/Python-2.3.2:) make install ./install-sh -c python /usr/local/bin/python2.3 if test -f libpython2.3.so; then \ if test ".so" = .dll; then \ ./install-sh -c -m 555 libpython2.3.so /usr/local/bin; \ else \ ./install-sh -c -m 555 libpython2.3.so /usr/local/lib/libpython2.3.so; \ (cd /usr/local/lib; ln -sf libpython2.3.so libpython2.3.so); \ fi; \ else true; \ fi ln: cannot create libpython2.3.so: File exists make: *** [altbininstall] Error 2 thanks From jeder at earthlink.net Tue Nov 25 00:26:25 2003 From: jeder at earthlink.net (Ryan Spencer) Date: Tue, 25 Nov 2003 05:26:25 GMT Subject: sleep() function, perhaps. Message-ID: Hello Everyone, I want to have a row of periods, separated by small, say, .5 second intervals between each other. Thus, for example, making it have the appearance of a progress "bar". [code] import time sleep(.5) print "." sleep(.5) print "." [end code] But, it would (with those .5 second intervals) print out much like the following. . (pause) . (pause) I would rather those periods be on a single line, not printing on a new line each time. Any suggestions? Thank you in advance, ~Ryan From kirk at daycos.com Fri Nov 7 18:00:34 2003 From: kirk at daycos.com (Kirk Strauser) Date: Fri, 07 Nov 2003 23:00:34 GMT Subject: Problems with regexps References: <87fzgz98vh.fsf@internal.daycos.com> Message-ID: <874qxf946f.fsf@internal.daycos.com> OK, let me give a clearer demonstration. Given this program: #!/usr/bin/env python import re sample = 'FOO= BAR' if re.search(r'[^=]\s+BAR', sample): print 'Match 1.' if re.search(r'[^=]\s*BAR', sample): print 'Match 2.' When run, it produces "Match 2.". Why? I want to match: 1) Anything but '=', followed by 2) Zero or more spaces, followed by 3) 'BAR' The first pattern correct does *not* match. Why doesn't the '= ' get struck down by the '[^=]' pattern before a '\s+' but not before '\s*'? Thanks, -- Kirk Strauser The Day Companies From richard.philips at ua.ac.be Mon Nov 3 06:53:18 2003 From: richard.philips at ua.ac.be (Richard Philips) Date: Mon, 03 Nov 2003 12:53:18 +0100 Subject: Testing validity of for...in... Message-ID: <3FA641AE.7040607@ua.ac.be> Hi, From the "The Pragmatic Programmer / Dave Thomas, Andy Hunt", I acquired the habit to insert assertions in function declarations: def maxlength(mylist): assert isinstance(mylist, list), "A list with strings" max = -1 for item in list: if len(item)>max: max = len(item) return max But if you look at the code, maxlength is meaningful if mylist supports the "for ... in ...". Is there an easy way to test if "mylist" supports "for ... in ..." ? Thank you, Richard -- ================================================================ Dr. Richard PHILIPS University of Antwerp Systemmanager Anet Phone: +32 3 820.21.53 Fax: +32 3 820.21.59 GSM: 0478/36.76.28 Email: Richard.Philips at ua.ac.be ================================================================ From bokr at oz.net Thu Nov 20 13:08:50 2003 From: bokr at oz.net (Bengt Richter) Date: 20 Nov 2003 18:08:50 GMT Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <3FBB805D.40A8DA75@engcorp.com> Message-ID: On Wed, 19 Nov 2003 09:09:54 -0700, "Dave Brueck" wrote: [...] >> >> If it's really for obfuscation, wouldn't a simpler algorithm be >> sufficient, such as "XOR each byte with 0x5A" or something like that? >> >> If the answer is "no, that's too easy to break", then it's not really >> just for obfuscation, is it? > >I understand what you mean, but obfuscation _is_ a form of encryption, just one >that's understood to be on the weak side (so the above may be considered "too >weak"). Rather than being _either_ obfuscation _or_ encryption, they really are >just different points on a broad data protection spectrum. > IMO that ignores an important disctinction. I.e., obfuscation may be a lossy transformation (or conceivably noise-introducing for that matter) (e.g., like stripping comments, compiling to eliminate source info, etc.) whereas encryption ISTM must guarantee recoverability of all the bits. Regards, Bengt Richter From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Tue Nov 25 11:32:58 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Tue, 25 Nov 2003 19:32:58 +0300 Subject: static method feature In-Reply-To: References: Message-ID: rashkatsa wrote: > Hi all, > > do you know why python development team decided to forbid polymorphism > for static methods ? As you can do it in another languages (Java,...) it > could be very handy if you can create utility classes with static > methods that could be differentiate from the number of parameters. It's not polymorphism, but overloading > > with no static methods, it is already possible in python : > > class Assert: > def assertEquals(self,expected,actual): > ... > def assertEquals(self,msg,expected,actual): No, you just *redefine* assertEquals method Try Assert().assertEquals('expected', 'actual') and Python'd complain: TypeError: assertEquals() takes exactly 4 arguments (3 given) [skipped] Python doesn't support overloading (search the group for more info on it). It can be emulated to some extened with default values and *args, **args E.g.: def foo(*args): if len(args) == 3: return foo3(*args) else: return default_foo(*args) A nice example of dispatch on passed parameters is multimethod.py (you can google for it). regards, anton. From cgmckeever at yahoo.com Wed Nov 5 01:42:53 2003 From: cgmckeever at yahoo.com (Chris McKeever) Date: 4 Nov 2003 22:42:53 -0800 Subject: Modify Python Code - no idea at all Message-ID: <1a78c305.0311042242.66e4a7d0@posting.google.com> I am trying to modify the Mailman Python code to stop mapping MIME-types and use the extension of the attachment instead. I am pretty much clueless as to what I need to do here, but I think I have narrowed it down to the Scrubber.py file.. If this seems like a quick step me through, I would be very appreciative, could get you something on your Amazon wish-list (that is me on my knees begging).. >From just my basic understanding, it looks like it does a mimemapping, and then uses the 'best' extension for that type. We are sending .pdf files, but they are being classified as application/octet-stream from the mail program, and this then gets mapped to a .obj file extension when it is being archived. This causes problems when going through the archive. I am attaching the code below, if anyone could give me some guidance.. Thanks! Chris cgmckeever at prupref.com # Copyright (C) 2001-2003 by the Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """Cleanse a message for archiving. """ from __future__ import nested_scopes import os import re import sha import time import errno import binascii import tempfile from cStringIO import StringIO from types import IntType from email.Utils import parsedate from email.Parser import HeaderParser from email.Generator import Generator from Mailman import mm_cfg from Mailman import Utils from Mailman import LockFile from Mailman import Message from Mailman.Errors import DiscardMessage from Mailman.i18n import _ from Mailman.Logging.Syslog import syslog # Path characters for common platforms pre = re.compile(r'[/\\:]') # All other characters to strip out of Content-Disposition: filenames # (essentially anything that isn't an alphanum, dot, slash, or underscore. sre = re.compile(r'[^-\w.]') # Regexp to strip out leading dots dre = re.compile(r'^\.*') BR = '
\n' SPACE = ' ' try: from mimetypes import guess_all_extensions except ImportError: import mimetypes def guess_all_extensions(ctype, strict=1): # BAW: sigh, guess_all_extensions() is new in Python 2.3 all = [] def check(map): for e, t in map.items(): if t == ctype: all.append(e) check(mimetypes.types_map) # Python 2.1 doesn't have common_types. Sigh, sigh. if not strict and hasattr(mimetypes, 'common_types'): check(mimetypes.common_types) return all def guess_extension(ctype, ext): # mimetypes maps multiple extensions to the same type, e.g. .doc, .dot, # and .wiz are all mapped to application/msword. This sucks for finding # the best reverse mapping. If the extension is one of the giving # mappings, we'll trust that, otherwise we'll just guess. :/ all = guess_all_extensions(ctype, strict=0) if ext in all: return ext return all and all[0] # We're using a subclass of the standard Generator because we want to suppress # headers in the subparts of multiparts. We use a hack -- the ctor argument # skipheaders to accomplish this. It's set to true for the outer Message # object, but false for all internal objects. We recognize that # sub-Generators will get created passing only mangle_from_ and maxheaderlen # to the ctors. # # This isn't perfect because we still get stuff like the multipart boundaries, # but see below for how we corrupt that to our nefarious goals. class ScrubberGenerator(Generator): def __init__(self, outfp, mangle_from_=1, maxheaderlen=78, skipheaders=1): Generator.__init__(self, outfp, mangle_from_=0) self.__skipheaders = skipheaders def _write_headers(self, msg): if not self.__skipheaders: Generator._write_headers(self, msg) def safe_strftime(fmt, floatsecs): try: return time.strftime(fmt, floatsecs) except (TypeError, ValueError): return None def calculate_attachments_dir(mlist, msg, msgdata): # Calculate the directory that attachments for this message will go # under. To avoid inode limitations, the scheme will be: # archives/private//attachments/YYYYMMDD// # Start by calculating the date-based and msgid-hash components. fmt = '%Y%m%d' datestr = msg.get('Date') if datestr: now = parsedate(datestr) else: now = time.gmtime(msgdata.get('received_time', time.time())) datedir = safe_strftime(fmt, now) if not datedir: datestr = msgdata.get('X-List-Received-Date') if datestr: datedir = safe_strftime(fmt, datestr) if not datedir: # What next? Unixfrom, I guess. parts = msg.get_unixfrom().split() try: month = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12, }.get(parts[3], 0) day = int(parts[4]) year = int(parts[6]) except (IndexError, ValueError): # Best we can do I think month = day = year = 0 datedir = '%04d%02d%02d' % (year, month, day) assert datedir # As for the msgid hash, we'll base this part on the Message-ID: so that # all attachments for the same message end up in the same directory (we'll # uniquify the filenames in that directory as needed). We use the first 2 # and last 2 bytes of the SHA1 hash of the message id as the basis of the # directory name. Clashes here don't really matter too much, and that # still gives us a 32-bit space to work with. msgid = msg['message-id'] if msgid is None: msgid = msg['Message-ID'] = Utils.unique_message_id(mlist) # We assume that the message id actually /is/ unique! digest = sha.new(msgid).hexdigest() return os.path.join('attachments', datedir, digest[:4] + digest[-4:]) def process(mlist, msg, msgdata=None): sanitize = mm_cfg.ARCHIVE_HTML_SANITIZER outer = 1 if msgdata is None: msgdata = {} dir = calculate_attachments_dir(mlist, msg, msgdata) charset = None lcset = Utils.GetCharSet(mlist.preferred_language) # Now walk over all subparts of this message and scrub out various types for part in msg.walk(): ctype = part.get_type(part.get_default_type()) # If the part is text/plain, we leave it alone if ctype == 'text/plain': # We need to choose a charset for the scrubbed message, so we'll # arbitrarily pick the charset of the first text/plain part in the # message. if charset is None: charset = part.get_content_charset(lcset) elif ctype == 'text/html' and isinstance(sanitize, IntType): if sanitize == 0: if outer: raise DiscardMessage del part['content-type'] part.set_payload(_('HTML attachment scrubbed and removed'), # Adding charset arg and removing content-tpe # sets content-type to text/plain lcset) elif sanitize == 2: # By leaving it alone, Pipermail will automatically escape it pass elif sanitize == 3: # Pull it out as an attachment but leave it unescaped. This # is dangerous, but perhaps useful for heavily moderated # lists. omask = os.umask(002) try: url = save_attachment(mlist, part, dir, filter_html=0) finally: os.umask(omask) del part['content-type'] part.set_payload(_("""\ An HTML attachment was scrubbed... URL: %(url)s """), lcset) else: # HTML-escape it and store it as an attachment, but make it # look a /little/ bit prettier. :( payload = Utils.websafe(part.get_payload(decode=1)) # For whitespace in the margin, change spaces into # non-breaking spaces, and tabs into 8 of those. Then use a # mono-space font. Still looks hideous to me, but then I'd # just as soon discard them. def doreplace(s): return s.replace(' ', ' ').replace('\t', ' '*8) lines = [doreplace(s) for s in payload.split('\n')] payload = '\n' + BR.join(lines) + '\n\n' part.set_payload(payload) # We're replacing the payload with the decoded payload so this # will just get in the way. del part['content-transfer-encoding'] omask = os.umask(002) try: url = save_attachment(mlist, part, dir, filter_html=0) finally: os.umask(omask) del part['content-type'] part.set_payload(_("""\ An HTML attachment was scrubbed... URL: %(url)s """), lcset) elif ctype == 'message/rfc822': # This part contains a submessage, so it too needs scrubbing submsg = part.get_payload(0) omask = os.umask(002) try: url = save_attachment(mlist, part, dir) finally: os.umask(omask) subject = submsg.get('subject', _('no subject')) date = submsg.get('date', _('no date')) who = submsg.get('from', _('unknown sender')) size = len(str(submsg)) del part['content-type'] part.set_payload(_("""\ An embedded message was scrubbed... From: %(who)s Subject: %(subject)s Date: %(date)s Size: %(size)s Url: %(url)s """), lcset) # If the message isn't a multipart, then we'll strip it out as an # attachment that would have to be separately downloaded. Pipermail # will transform the url into a hyperlink. elif not part.is_multipart(): payload = part.get_payload(decode=1) ctype = part.get_type() size = len(payload) omask = os.umask(002) try: url = save_attachment(mlist, part, dir) finally: os.umask(omask) desc = part.get('content-description', _('not available')) filename = part.get_filename(_('not available')) del part['content-type'] del part['content-transfer-encoding'] part.set_payload(_("""\ A non-text attachment was scrubbed... Name: %(filename)s Type: %(ctype)s Size: %(size)d bytes Desc: %(desc)s Url : %(url)s """), lcset) outer = 0 # We still have to sanitize multipart messages to flat text because # Pipermail can't handle messages with list payloads. This is a kludge; # def (n) clever hack ;). if msg.is_multipart(): # By default we take the charset of the first text/plain part in the # message, but if there was none, we'll use the list's preferred # language's charset. if charset is None or charset == 'us-ascii': charset = lcset # We now want to concatenate all the parts which have been scrubbed to # text/plain, into a single text/plain payload. We need to make sure # all the characters in the concatenated string are in the same # encoding, so we'll use the 'replace' key in the coercion call. # BAW: Martin's original patch suggested we might want to try # generalizing to utf-8, and that's probably a good idea (eventually). text = [] for part in msg.get_payload(): # All parts should be scrubbed to text/plain by now. partctype = part.get_content_type() if partctype <> 'text/plain': text.append(_('Skipped content of type %(partctype)s')) continue try: t = part.get_payload(decode=1) except binascii.Error: t = part.get_payload() partcharset = part.get_content_charset() if partcharset and partcharset <> charset: try: t = unicode(t, partcharset, 'replace') except (UnicodeError, LookupError): # Replace funny characters t = unicode(t, 'ascii', 'replace').encode('ascii') try: # Should use HTML-Escape, or try generalizing to UTF-8 t = t.encode(charset, 'replace') except (UnicodeError, LookupError): t = t.encode(lcset, 'replace') # Separation is useful if not t.endswith('\n'): t += '\n' text.append(t) # Now join the text and set the payload sep = _('-------------- next part --------------\n') del msg['content-type'] msg.set_payload(sep.join(text), charset) del msg['content-transfer-encoding'] msg.add_header('Content-Transfer-Encoding', '8bit') return msg def makedirs(dir): # Create all the directories to store this attachment in try: os.makedirs(dir, 02775) # Unfortunately, FreeBSD seems to be broken in that it doesn't honor # the mode arg of mkdir(). def twiddle(arg, dirname, names): os.chmod(dirname, 02775) os.path.walk(dir, twiddle, None) except OSError, e: if e.errno <> errno.EEXIST: raise def save_attachment(mlist, msg, dir, filter_html=1): fsdir = os.path.join(mlist.archive_dir(), dir) makedirs(fsdir) # Figure out the attachment type and get the decoded data decodedpayload = msg.get_payload(decode=1) # BAW: mimetypes ought to handle non-standard, but commonly found types, # e.g. image/jpg (should be image/jpeg). For now we just store such # things as application/octet-streams since that seems the safest. ctype = msg.get_content_type() fnext = os.path.splitext(msg.get_filename(''))[1] ext = guess_extension(ctype, fnext) if not ext: # We don't know what it is, so assume it's just a shapeless # application/octet-stream, unless the Content-Type: is # message/rfc822, in which case we know we'll coerce the type to # text/plain below. if ctype == 'message/rfc822': ext = '.txt' else: ext = '.bin' path = None # We need a lock to calculate the next attachment number lockfile = os.path.join(fsdir, 'attachments.lock') lock = LockFile.LockFile(lockfile) lock.lock() try: # Now base the filename on what's in the attachment, uniquifying it if # necessary. filename = msg.get_filename() if not filename: filebase = 'attachment' else: # Sanitize the filename given in the message headers parts = pre.split(filename) filename = parts[-1] # Strip off leading dots filename = dre.sub('', filename) # Allow only alphanumerics, dash, underscore, and dot filename = sre.sub('', filename) # If the filename's extension doesn't match the type we guessed, # which one should we go with? For now, let's go with the one we # guessed so attachments can't lie about their type. Also, if the # filename /has/ no extension, then tack on the one we guessed. filebase, ignore = os.path.splitext(filename) # Now we're looking for a unique name for this file on the file # system. If msgdir/filebase.ext isn't unique, we'll add a counter # after filebase, e.g. msgdir/filebase-cnt.ext counter = 0 extra = '' while 1: path = os.path.join(fsdir, filebase + extra + ext) # Generally it is not a good idea to test for file existance # before just trying to create it, but the alternatives aren't # wonderful (i.e. os.open(..., O_CREAT | O_EXCL) isn't # NFS-safe). Besides, we have an exclusive lock now, so we're # guaranteed that no other process will be racing with us. if os.path.exists(path): counter += 1 extra = '-%04d' % counter else: break finally: lock.unlock() # `path' now contains the unique filename for the attachment. There's # just one more step we need to do. If the part is text/html and # ARCHIVE_HTML_SANITIZER is a string (which it must be or we wouldn't be # here), then send the attachment through the filter program for # sanitization if filter_html and ctype == 'text/html': base, ext = os.path.splitext(path) tmppath = base + '-tmp' + ext fp = open(tmppath, 'w') try: fp.write(decodedpayload) fp.close() cmd = mm_cfg.ARCHIVE_HTML_SANITIZER % {'filename' : tmppath} progfp = os.popen(cmd, 'r') decodedpayload = progfp.read() status = progfp.close() if status: syslog('error', 'HTML sanitizer exited with non-zero status: %s', status) finally: os.unlink(tmppath) # BAW: Since we've now sanitized the document, it should be plain # text. Blarg, we really want the sanitizer to tell us what the type # if the return data is. :( ext = '.txt' path = base + '.txt' # Is it a message/rfc822 attachment? elif ctype == 'message/rfc822': submsg = msg.get_payload() # BAW: I'm sure we can eventually do better than this. :( decodedpayload = Utils.websafe(str(submsg)) fp = open(path, 'w') fp.write(decodedpayload) fp.close() # Now calculate the url baseurl = mlist.GetBaseArchiveURL() # Private archives will likely have a trailing slash. Normalize. if baseurl[-1] <> '/': baseurl += '/' url = baseurl + '%s/%s%s%s' % (dir, filebase, extra, ext) return url From peter at engcorp.com Thu Nov 27 11:18:54 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 27 Nov 2003 11:18:54 -0500 Subject: List index - why ? References: Message-ID: <3FC623EE.2B1E033@engcorp.com> Kepes Krisztian wrote: > > The string object have a method named "index", and have a method named > "find". > Why don't exists same method in the list object ? It does: Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 >>> l = [1, 2, 3] >>> l = list('abcdefg') >>> l ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> l.index('d') 3 .find() doesn't exist on lists, perhaps because nobody has asked for it and presented a good use case. It seems to me quite rare that somebody needs to search for a sublist in a list, and you can already search for individual elements with "in". > Same thing is the deleting. > I think, this method is missing from strings, and lists. Strings are immutable, and you can already delete elements from lists. Or did I miss something... your request was a little confusing. -Peter From peter at engcorp.com Tue Nov 11 18:55:16 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Nov 2003 18:55:16 -0500 Subject: trouble with unittest and namespaces - can anyone help? References: Message-ID: <3FB176E4.B3F7D534@engcorp.com> Lol McBride wrote: > > I've hit a snag which I believe is to do with namespaces (specifically the > os.path). Probably more a problem with sys.path, but perhaps that's what you meant. > The programs in analysis do not import classes or modules from anywhere > else and the tests in the tests directory run fine.My problem is with the > tests done for prog3 and prog4, both of which import from the analysis > package e.g > from analysis import prog1 > > All tests fail to run and a 'no such module as analysis message' is > displayed. > Could anyone give me an idea as to how to resolve this problem? The simplest approach is to insert the following at the top of your tests: import sys sys.path.append('../..') Or something like that... basically if the directory containing the files to be imported (or the one containing the package folder, in the case of a Python package) is not in sys.path, you won't be able to import the module or package properly. Given that your tests are in a subfolder of the one where prog2.py is found, I'm not sure how you are invoking the tests right now such that they are working at all. How do they find "prog2" when they import it right now? -Peter From t-meyer at ihug.co.nz Sun Nov 16 19:19:10 2003 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 17 Nov 2003 13:19:10 +1300 Subject: [COM Newbie] How to find out the # of cells and rows in an excelsheet In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F130415CF47@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F130212B12B@its-xchg4.massey.ac.nz> > Having a reference to an excel workbook and worksheet, how > can I get the width and height of the area with data without > iterating through 65536 rows * 256 columns (which would take > a small eternity)? You're after the UsedRange property. It's a property of various things, including WorkSheets. The Excel object reference has more info on it. =Tony Meyer From rmunn at pobox.com Wed Nov 5 16:43:13 2003 From: rmunn at pobox.com (Robin Munn) Date: Wed, 05 Nov 2003 21:43:13 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Nov 3) References: <044sZWAyhsp$Ewo$@jessikat.fsnet.co.uk> <75J$JKA2ptp$Ew4f@jessikat.fsnet.co.uk> Message-ID: Robin Becker wrote: > In article <044sZWAyhsp$Ewo$@jessikat.fsnet.co.uk>, Robin Becker > writes >>In article , Emile van Sebille >> writes >> >>for some reason these supplied google links are failing for me. Is there >>some way to get the right urls? >> >>> Marc-Andre Lemburg offers what must be the definitive answer on >>> accessing a MS Access database from linux, and suggests switching to >>> MS Desktop Engine. >>> http://groups.google.com/groups?threadm=3Dmailman.253.1067539482.702.py >>t >>>hon-list at python.org >>> >>> Jerome Alet releases PyPlet adding speech to IRC. >>> http://groups.google.com/groups?selm=3Dpan.2003.10.29.15.29.19.383092 at l >>i >>>brelogiciel.com >>...... > I guess it's the 3D that's causing me pain although the fold doesn't > help. Replace the '=3D' string with a bare '=' (equals sign) and the URL should work for you. -- Robin Munn rmunn at pobox.com From seberino at spawar.navy.mil Wed Nov 26 00:45:35 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 25 Nov 2003 21:45:35 -0800 Subject: Problems sending list/tuple to a C extension. References: Message-ID: Martin Thanks for your email. I understand now. I got it to work. All is well. Chris martin at v.loewis.de (Martin v. L?wis) wrote in message news:... > seberino at spawar.navy.mil (Christian Seberino) writes: > > > I think you misunderstood my question. My invocation of PyArg_ParseTuple > > was flawless EXCEPT for checking return value. > > > > ALL I did was check return value and then code worked fine!!! > > > > *This* is what was exceedingly strange. > > When you say "It worked fine", you mean "It raises an exception", right? > Because you did not, actually, pass a tuple to the call. > > If you had passed a tuple to the call, instead of passing an integer, > it would have worked even without the check for an error return. It > was only because you made an error *in Python* that the failure to > check for errors in C made any difference. > > Or are you asking "Why do I need to check for errors in Python code if > the Python code does have errors?" I couldn't quite imagine why you > would ask this question: How else could Python possibly communicate > the error to the Python code, except by returning an error???? > > Regards, > Martin From mal at egenix.com Tue Nov 25 05:43:06 2003 From: mal at egenix.com (M.-A. Lemburg) Date: Tue, 25 Nov 2003 11:43:06 +0100 Subject: Database connect / PDO In-Reply-To: <030d01c3b2d9$4220a970$7401a8c0@voidmk9> References: <3FC248D1.3090603@ghaering.de> <030d01c3b2d9$4220a970$7401a8c0@voidmk9> Message-ID: <3FC3323A.3050209@egenix.com> Jon Franz wrote: > Yes, an underlying DBAPI driver is required, and mxODBC works... > mostly (see below). > I might recommend the adodbapi driver for use on the windows platform, > but that still leaves mxODBC for linux. > > I may be wrong, but I think mxODBC module still doesn't provide all > the values for the DBAPI .description fields - I know the field name > is provided, but I don't know if the size info will be correct, or if a > non-None value will be available for the other attributes. mxODBC provides all .description values except display_size and internal_size (and this is allowed by the DB API standard). These two values are rarely of importance and if you absolutely need them they can also be queried using the catalog methods the mxODBC exposes. You should note however, that some ODBC database drivers try to be smart and "optimize" the return values that you see in .description (the MyODBC driver is a prominent example). While this is allowed by the ODBC standard, it is certainly not good practice. As a result, the only true source of the schema information are the catalog methods, e.g. .columns() available in mxODBC. These also provide much more information than is available in .description. > Thus, some of the Field object's member variables may be meaningless > when used with mxODBC on your project. > > Does anyone know offhand when mxODBC will add this info? I think > its the last (or one of the few) things holding it back from true DBAPI > 2.0 compliance. mxODBC 2.0.x is 100% DB API 2.0 compliant. The only omissions are .nextset() and .callproc() which will be available in mxODBC 2.1.0. Both are optional in the DB API 2.0 specification. > ~Jon Franz > NeuroKode Labs, LLC > > > ----- Original Message ----- > From: "SectorUnknown" > To: > Sent: Monday, November 24, 2003 3:47 PM > Subject: Re: Database connect / PDO > > > >>I've been looking through the documentation for PDO, but it sounds like >>you still need mxODBC. Is this correct? >> >>See: http://sourceforge.net/docman/display_doc.php?docid=20024&group_id= >>86244#supported >> >>In article , >>jfranz at neurokode.com says... >> >>>>Another possibility is to see if an OR-thingie like PDO/SQLObject/... >>>>actually helps for database abstraction. I suppose they'll get really >>>>"fun" to use once you need advanced queries, though. Does anybody have >>>>any real-life experience with any of these Python OR mappers? >>> >>>I have lots of experience with PDO - but it is not an OR mapper. >>>It's an abstraction layer on top of the DB-API that adds functionality >>>and attempts to make it easier to write your application to a single >>>API. I guess you could say its the n-1th abstraction layer. >>> >>>PDO might be useful for SectorUnknown's needs. >>> >>>~Jon Franz >>>NeuroKode Labs, LLC >>> >>> >>> >> >> > > -- Marc-Andre Lemburg eGenix.com Professional Python Software directly from the Source (#1, Nov 24 2003) >>> Python/Zope Products & Consulting ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From bogus at invalid.tld Sun Nov 30 00:54:04 2003 From: bogus at invalid.tld (Jules Dubois) Date: Sat, 29 Nov 2003 22:54:04 -0700 Subject: Bug in glob.glob for files w/o extentions in Windows References: Message-ID: On Sun, 30 Nov 2003 03:47:38 GMT, in article , Georgy Pruss wrote: > On Windows XP glob.glob doesn't work properly for files without extensions. > E.g. C:\Temp contains 4 files: 2 with extensions, 2 without. > [...] > C:\Temp>dir /b *. > ccccc > ddddd This is standard Windows behavior. It's compatible with CP/M and therefore MS-DOS, and Microsoft has preserved this behavior in all versions of Windows. Did you ever poke around in the directory system in a FAT partition (without VFAT)? You'll find that every file name is exactly 11 characters long and "." is not found in any part of any file name in any directory entry. It's bizarre but that's the way it works. If you try dir /b * does cmd.exe list only files without extensions? >>>> glob.glob( '*.' ) > [] > glob provides "Unix style pathname pattern expansion" as documented in the _Python Library Reference_: If there's a period (".") in the pattern, it must match a period in the filename. > It looks like a bug. No, it's proper behavior. It's Windows that's (still) screwy. From keflimarcusx at aol.comNOSPAM Mon Nov 17 07:29:28 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 17 Nov 2003 12:29:28 GMT Subject: True inconsistency in Python References: <3FB8847F.6CB1BECA@alcyone.com> Message-ID: <20031117072928.12288.00000313@mb-m25.aol.com> >Explicit comparison with the true constant (or false constant) >necessarily degenerates into complete uselessness. (For those just joining us, this statement was made about all languages, not just Python.) I'm not so sure about that. In most languages (including Python), 'false' is guaranteed to be only one value (usually zero), therefore comparing against it poses no problem. I assume you're saying that doing so isn't problematic in any way, it's just pointless. Well, actually, some coding standards suggest you always compare against false. This is so the code is slightly more clear, and "!= false" avoids the pitfall that "== true" has. The problem of course is that some unwitting maintenance programmer may decide that "== true" os more clear than "!= false", not realizing it is wrong...which is why all maintenance programmers should read programming standards. :) We can't program in baby C just for them, after all, but we shouldn't make things unnecessarily difficult for them either, but I think we have bigger things to worry about if a maintenance programmer fails to understand such a simple concept after being told about it. Now of course any idiot C (or C++, or Java) programmer knows that these two are equivalent: if(blah != false) do_blah(); if(blah) do_blah(); But if whatever goes in "blah" is really long (and often it is), you very quickly see what is being compared: it's a straight boolean comparison, whereas with the second you have to look at the whole thing, find no comparison operator, and go, "oh, there's no explicit comparison so it's obviously an implicit straight boolean comparison". This is especially valuable in really long 'if' statements, such as one might want for an inverse parser (don't worry if you don't know what one is). The idea is if you compare against 'false' all the time, you won't forget it when it would actually give the code more clarity. One standard which suggests this is the one Steve Maguire proposes in the book Writing Solid Code. This is probably the best book on C coding guidelines that I've ever read, despite it being written by a Microsoft programmer. ;) Although much of it is specific to C, a lot of the concepts apply to other languages, including Python. However, comparing against a boolean is discouraged in Python (but your argument wasn't about Python specifically), so I wouldn't do it in Python: when in Rome, do as the Romans do. Although, as a last thought, it should be relatively easy to make it so that True returns '1' in any comparison except against 0. A class would be able to do this easily by overriding __cmp__: def true_class(bool): def __cmp__(self, other): if other: return 1 else: return 0 True = true_class() (of course this class definition would be tweaked to make it a singleton) I'm assuming there's a good reason for not doing it this way (or in an equivalent fashion), though...what else might we add to this discussion? - Kef From bokr at oz.net Wed Nov 19 01:05:31 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Nov 2003 06:05:31 GMT Subject: maximum value for long? References: Message-ID: On Tue, 18 Nov 2003 21:45:45 -0500, "Terry Reedy" wrote: > >"S.Susnjar" wrote in message >news:baab8c40.0311180906.a4ab9f7 at posting.google.com... >> Hello all, > >Hi. > >> I have been programming in Python only for a month or so and have >stumbled >> over a "problem" that I could not solve through rtfm. > >Ref Man 3.2 The standard type hierarchy >" >There are two types of integers: > >Plain integers >These represent numbers in the range -2147483648 through 2147483647. >(The range may be larger on machines with a larger natural word size, >but not smaller.) When the result of an operation would fall outside >this range, the exception OverflowError is raised. For the purpose of Seems out of date re version 2.3.2: >>> x = 2**30 >>> x 1073741824 >>> type(x) >>> x+x 2147483648L >>> type(x+x) >shift and mask operations, integers are assumed to have a binary, 2's >complement notation using 32 or more bits, and hiding no bits from the >user (i.e., all 4294967296 different bit patterns correspond to >different values). > >Long integers >These represent numbers in an unlimited range, subject to available >(virtual) memory only. For the purpose of shift and mask operations, a >binary representation is assumed, and negative numbers are represented >in a variant of 2's complement which gives the illusion of an infinite >string of sign bits extending to the left. >" Though hex of negative numbers is slated for ugliness (IMO) in version 2.4 in the form of '-' prefixing the hex of the absolute value -- making it useless for the normal bit pattern visualization that one would like when looking at bitwise operations. Ugh! Barf!. >In short, Python ints are C longs, while Python longs are extended or >arbitrary precision, and hence truly long. Your confusion over the >two meanings of 'long' is not unique among people with a C background >;-). > Regards, Bengt Richter From ajs at optonline.net Sat Nov 15 04:18:16 2003 From: ajs at optonline.net (Arthur) Date: Sat, 15 Nov 2003 04:18:16 -0500 Subject: Python's simplicity philosophy Message-ID: <00d801c3ab59$676e0b50$1c02a8c0@BasementDell> Rainer writes - >In one line: >x = sum(seq) >And that is why 'sum' is a worthwhile part of the Python >standard library The issue that concerns me is the analysis, decision-making on this kind of issue on what is essentially an "as if" basis - as if Numeric and its line of descent were not defacto standard library for numeric processing in Python. I don't know that any conclusions would change with current Numeric functionality, and the effect of such changes on Numeric, taken under consideration. But I do wonder why it doesn't seem to be condered essential to consider these kinds of issues in this light. Art From jzgoda at gazeta.usun.pl Wed Nov 12 14:53:41 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 12 Nov 2003 19:53:41 +0000 (UTC) Subject: GUI - Qt Designer References: Message-ID: John Bradbury pisze: > Is there any way to take the output produced by Qt designer (or any other > GUI designer) and use it in Python to create a screen? You are not limited to PyQt, wxPython has few nice GUI designers, of which wxGLADE seems to be the easiest to use. Or -- at you will -- you can use xrc resources, wchich are native to wxWindows and can be shared between wxPython and wxWindows applications. The window designs (frames, forms) created with Qt Designer can be translated to Python code using pyuic tool. BlackAdder IDE has this support built-in, although I never tried this approach. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From lyle at users.sourceforge.net Wed Nov 26 12:22:51 2003 From: lyle at users.sourceforge.net (Lyle Johnson) Date: Wed, 26 Nov 2003 11:22:51 -0600 Subject: Swig - problem with visual c++ extension exercise In-Reply-To: References: Message-ID: <3FC4E16B.7020901@users.sourceforge.net> S Green wrote: > I keep getting an error unresolved external symbol initexample when > running python setup.py build, This problem is not unique to Visual C++. Please see this section of the SWIG documentation (19.2.3, "Compiling a dynamic module"): http://www.swig.org/Doc1.3/Python.html#n6 and pay special attention to the last two paragraphs in that section (beginning with "When linking the module, ..."). Hope this helps, Lyle From rmunn at pobox.com Sat Nov 22 10:57:47 2003 From: rmunn at pobox.com (Robin Munn) Date: Sat, 22 Nov 2003 15:57:47 GMT Subject: os.walk help References: <3FBEAF80.5020802@hotmail.com> Message-ID: hokiegal99 wrote: > Joe Francia wrote: >> Your code is trying to recurse into the list of directories in 'dirs', >> but you are renaming these directories before it can get to them. For >> example, if dirs = ['baddir?*', 'gooddir', 'okdir'], you rename >> 'baddir?*' to 'baddir--' and then os.walk tries to enter 'baddir?*' and >> cannot find it. You're better off building a list of paths to rename, >> and then renaming them outside of the os.walk scope, or doing something >> like... >> >> dirs.remove(dname) >> dirs.append(newdname) >> >> ...in your 'if' block. >> >> Peace, >> Joe > > So, which is better... rename in the os.walk scope or not? The below > code works sometimes at others it produces this error: > > ValueError: list.remove(x): x is not in list That's strange. It shouldn't be happening. Stick some print statements in there and see what's going on: > setpath = raw_input("Path to the Directory: ") > def clean_names(setpath): > bad = re.compile(r'%2f|%25|%20|[*?<>/\|\\]') > for root, dirs, files in os.walk(setpath): > for dname in dirs: > badchars = bad.findall(dname) > for badchar in badchars: > newdname = dname.replace(badchar,'-') > if newdname != dname: try: > dirs.remove(dname) except ValueError: print "%s not in %s" % (dname, dirs) else: > dirs.append(newdname) > newpath = os.path.join(root, newdname) > oldpath = os.path.join(root, dname) > os.renames(oldpath, newpath) Note that I'm assuming it's the dirs.remove(dname) call that's triggering the ValueError, since there aren't any invocations of list.remove() anywhere else in your sample code. But I could be wrong; you should look at the complete exception trace, which will include the line number at which the exception was thrown. -- Robin Munn rmunn at pobox.com From Python at essene.com Mon Nov 3 15:33:15 2003 From: Python at essene.com (Python) Date: Mon, 03 Nov 2003 13:33:15 -0700 Subject: TypeError: can't multiply sequence to non-int Message-ID: <20031103133306.BC11.PYTHON@essene.com> Hello, I am just learning Python and am going through some examples. I found one very simple example I can't figure out. Here is the script: # Enter a number to be squared x = raw_input("Enter a number: ") int(x) sq = x*x print sq I am getting the following error: Enter a number: 5 Traceback (most recent call last): File "db.py", line 6, in ? sq = x*x TypeError: can't multiply sequence to non-int Why is the function "int(x)" not changing the input to an integer? Thanks for the help, Jim From michele.simionato at poste.it Wed Nov 26 01:24:34 2003 From: michele.simionato at poste.it (Michele Simionato) Date: 25 Nov 2003 22:24:34 -0800 Subject: HOWTO: Python 2.3 on Fedora Core 1 Linux References: Message-ID: <95aa1afa.0311252224.216248b2@posting.google.com> Logan wrote in message news:... > Several people asked me for the following HOWTO, so I decided to > post it here (though it is still very 'alpha' and might contain > many (?) mistakes; didn't test what I wrote, but wrote it - more > or less - during my own installation of Python 2.3 on Fedora Core 1 > Linux for a friend of mine). > Thank you very much for this! (I've ordered Fedora CDs just yesterday ...) Michele From dpharris76 at msn.com Sat Nov 1 21:36:49 2003 From: dpharris76 at msn.com (Dave Harris) Date: Sat, 1 Nov 2003 20:36:49 -0600 Subject: IDLE traceback on sys.exit() Message-ID: Something to think about...I'm not sure if this is a problem for anyone. IDLE currently issues a traceback when running a program which contains sys.exit(). For example, the program: if __name__ == "__main__": sys.exit(False) shows the following in the IDLE shell window: Traceback (most recent call last): File "C:\rascal\dev\pylearn\odbchelpertest.py", line 8, in -toplevel- sys.exit(False) SystemExit: False If that's the way it's supposed to work, fine. But unittest wraps up the runTests() function with the line: sys.exit(not result.wasSuccessful()) So, I always get a traceback whenever I run a test program in IDLE. (The command-line invocation works silently, which I would expect.) My resolution is simple: I won't use IDLE to exercise my unit tests. Python 2.3b2 (#43, Jun 29 2003, 16:43:04) [MSC v.1200 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. IDLE 1.0b2 -------------- next part -------------- An HTML attachment was scrubbed... URL: From camelo at esss.com.br Tue Nov 4 07:50:19 2003 From: camelo at esss.com.br (Marcelo A. Camelo) Date: Tue, 4 Nov 2003 09:50:19 -0300 Subject: Extendin/Embedding architecture diagram In-Reply-To: Message-ID: <000001c3a2d2$33cd4bb0$0d00000a@esss.com.br> Hi! I remember running into a nice diagram of the layered architecture of Python embedding/extending that I'd like to use in a presentation. It was probably on some embedding or extending tutorial, but I can't remember where. I couldn't find it on google, neither. Does anyone on the list knows about it? Or was I dreaming? Cheers, Marcelo A. Camelo From balex at sympatico.ca Tue Nov 4 11:32:19 2003 From: balex at sympatico.ca (Brian) Date: Tue, 04 Nov 2003 11:32:19 -0500 Subject: breaking iteration of generator method Message-ID: Hello; What happens when a program breaks (think keyword 'break') its iteration of a generator? Is the old state in the generator preserved? Ex: # .gen() is generator method. for i in myObject.gen(): if i == specialValue: break Do subsequent calls to .gen() start off with new locals? Or, would the iteration begin after the yielded 'i' that caused the for-statement to exit? Many thanks, Brian. From bokr at oz.net Sat Nov 29 16:04:25 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Nov 2003 21:04:25 GMT Subject: Importing from a file to use contained variables References: Message-ID: On Sat, 29 Nov 2003 03:39:34 GMT, Jeff Wagner wrote: >I am importing a file which contains a persons name (firstName, middleName, etc). If I define a >function to do this, how can I use the variables outside of that function? Does the file only contain ONE person's info, or does the pattern of 5 lines repeat for more? If it's only one person, as you have it here, you can just split on line endings, like def getName(): return map(str.lower, file('enterName.txt').read().splitlines()) to return a list of the lower case strings you want, which you can then do an unpacking assignment with, e.g., fName, mName, lName, nName, pName = getName() But that's sure a special-purpose routine, being locked into just using the first five lines of a particular file with a fixed file name. If you have other possible files of the same format, and possibly with more than one person's info (i.e., repeating groups of 5 lines), I'd suggest a generator that you can pass a file name to, and which will return the info in successive lists of 5. E.g., the following looks like a function, but the 'yield' makes it a generator-maker ====< JeffWagner.py >==================================== def mkgen_GetName(fileOrPath): if isinstance(fileOrPath, str): fileOrPath = file(fileOrPath) # use open file or open by name lineCount = 0 for line in fileOrPath: if lineCount%5==0: nameList = [] nameList.append(line.strip().lower()) # strips white space incl newline if any lineCount += 1 if lineCount%5==0: yield nameList def test(): from StringIO import StringIO siofile = StringIO("""\ John Q Public JQ Johnny Alice B Choklas Allie Chok """) for fName, mName, lName, nName, pName in mkgen_GetName(siofile): # do whatever with each successive person-info set ... print ('%10s'*5)%(fName, mName, lName, nName, pName) if __name__ == '__main__': test() ========================================================= if you run this, you get: [13:00] C:\pywk\clp>jeffwagner.py john q public jq johnny alice b choklas allie chok It also has the advantage that it doesn't put the whole file in memory, just what it needs as it goes. > >Here is the code: > >import string Are you still using 1.5.2? You really ought to upgrade to 2.3.2 ;-) > >def getName(): > > data = open("enterName.txt") ^^^^ ^^^^^^^^^^^^^-- do you really want this as a fixed name in your function? | +-- deprecated in favor of 'file' > allNames = data.readlines() ^^^^^^^^^^^-- reads the whole file into memory. Not so good for big files. > data.close() ^^^^^^^^^^^^ good practice, but not necessary if you are using cPython. > > fName = string.lower(allNames[0]) fName = allNames[0].lower() # current way to spell previous line # (hence importing string is not necessary) > mName = string.lower(allNames[1]) > lName = string.lower(allNames[2]) > nName = string.lower(allNames[3]) > pName = string.lower(allNames[4]) > >I need to use these variables in another function (routine) to calculate the associated numbers. >Since these are local to the function, how is this done? Can I make them global or something? 'or something' is preferred ;-) BTW, if you don't want to use a loop to sequence through the data, you can get it one set at a time from the generator's .next method, e.g., >>> from JeffWagner import mkgen_GetName >>> if 1: # so I can copy/paste from the source file ... from StringIO import StringIO ... siofile = StringIO("""\ ... John ... Q ... Public ... JQ ... Johnny ... Alice ... B ... Choklas ... Allie ... Chok ... """) ... >>> gen = mkgen_GetName(siofile) >>> gen.next() ['john', 'q', 'public', 'jq', 'johnny'] >>> a,b,c,d,e = gen.next() >>> a,b,c ('alice', 'b', 'choklas') >>> d,e ('allie', 'chok') >>> gen.next() # expecting the StopIteration exception here Traceback (most recent call last): File "", line 1, in ? StopIteration >>> # so you will have to catch that to use .next() cleanly BTW, what does pName stand for? Regards, Bengt Richter From bignose-hates-spam at and-benfinney-does-too.id.au Thu Nov 20 17:00:14 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 21 Nov 2003 08:50:14 +1050 Subject: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com> <3FBC2025.B2A33B6F@alcyone.com> <87d6bncbaj.fsf@einstein.electron.net> Message-ID: On 20 Nov 2003 16:25:08 +0100, Curt wrote: > Erik Max Francis writes: >> [Unix command] uniq doesn't care whether the input is sorted or not. >> All it does is collapse multiple consecutive duplicate lines into a >> single line. Using uniq in conjunction with sort is certainly a >> common mode, but it's hardly required. > > curty at einstein:~$ less uniq.txt > flirty > curty > flirty > curty > > curty at einstein:~$ uniq uniq.txt > flirty > curty > flirty > curty > > curty at einstein:~$ sort uniq.txt | uniq > curty > flirty > > Maybe my uniq is unique. > > curty at einstein:~$ man uniq > > NAME > uniq - remove duplicate lines from a sorted file I suspect your uniq is not unique; merely poorly documented. Pass it a file consisting of unsorted input, but multiple consecutive identical lines; you should see them collapsed to one. Your OS needs a better 'man uniq', since that description doesn't say what the expected behaviour is with unsorted input. The GNU 'man uniq' doesn't mention sorted input, but applies to any input. -- \ "Theology is the effort to explain the unknowable in terms of | `\ the not worth knowing." -- Henry L. Mencken | _o__) | Ben Finney From c.sette_NOSPAM_ at reddevils.it Fri Nov 7 08:17:54 2003 From: c.sette_NOSPAM_ at reddevils.it (Carlo Sette) Date: Fri, 07 Nov 2003 14:17:54 +0100 Subject: XML DOM Message-ID: Hi all, when I try to Parse a sample XML ducument Python display the follow error message: --------------------------------------------------------------------------- Traceback (most recent call last): File "./mysql.py", line 57, in ? DOM=xml.dom.minidom.parseString(XML) File "/usr/local/lib/python2.3/xml/dom/minidom.py", line 1925, in parseString return expatbuilder.parseString(string) File "/usr/local/lib/python2.3/xml/dom/expatbuilder.py", line 940, in parseString return builder.parseString(string) File "/usr/local/lib/python2.3/xml/dom/expatbuilder.py", line 223, in parseString parser.Parse(string, True) xml.parsers.expat.ExpatError: mismatched tag: line 1, column 112 ---------------------------------------------------------------------------- I used xml.dom.minodom module and the source code is: #!/usr/local/bin/python import xml.dom.minidom XML="""55> CarloSette""" DOM=xml.dom.minidom.parseString(XML) ---------------------------------------------------------------------------- Do you have any suggestions?? Thanks in advance Carlo From frank-westermann at freenet.de Mon Nov 24 16:45:15 2003 From: frank-westermann at freenet.de (news.freenet.de) Date: Mon, 24 Nov 2003 21:45:15 -0000 Subject: =?iso-8859-1?q?Treffen/Stammtische_f=FCr_Hacker=2C_PC-Freaks=2C_?= =?iso-8859-1?q?Informatiker=2C_Programmierer?= Message-ID: <3fc26d95$1$26688$9b622d9e@news.freenet.de> Hallo miteinander, auf der Website http://de.msnusers.com/Recherche/dokumente.msnw sowie der Unterseite http://de.msnusers.com/Recherche/Dokumente/Informatik25%2D3.htm werden aktuelle Trefftermine zu Stammtischen von Informatikern, PC-Freaks, Programmierern, Hackern, Lan-Partie-Besessenen. MS-Access Zope Notes SAP/ABAP PHP Java Linux Palm Perl Im Regelfall werden Termine f?r die n?chsten 7 Kalendertage aufgef?hrt. Aktuell werden schwerpunktm??ig Termine f?r den Gro?raum Frankfurt/M publiziert. Wer seine eigenen Termine auf den oben genannten Website aufgef?hrt sehen will, muss sich an den Gruppenbetreiber wenden, oder in der Gruppe anmelden. Aktuell werden folgende Termine genannt: 1.. 25.11.2003 K+P Consulting GmbH (Kluge+Partner) Wirtschaftsrat Darmstadt Ahastra?e 5 Darmstadt http://www.kluge-partner.de 2.. 26.11.2003 Deutsche Zope User Group, Termine 20 Uhr, N?he Westbahnhof, Arche Nova (im ?kohaus) Kasseler Stra?e 1a Frankfurt/M. http://www.dzug.org 3.. 27.11.2003 Deutsche Notes User Group - Frankfurt, Termine Arbeitskreis Methoden und Strategien, InterCityHotel, 13 Uhr Frankfurt/M. http://www.dnug.de 4.. 28.11.2003 Access Stammtisch Rhein-Main, Raunheim, Termine 19 Uhr, Gasts?tte Zum Bembelsche, Mainzer Stra?e 53 Raunheim http://www.me-asal.de/access/stammtisch.htm 5.. 29.11.2003 adminX.de - Internetverein e.V., Termine 14:00 Uhr in Frankfurt/Nordend, Grafikformate im WorldWideWeb, Schulungstermin Hufnagelstrasse 22 Frankfurt/M. http://www.adminx.de 6.. 2.12.2003 adminX.de - Internetverein e.V., Termine 19 Uhr, Palacios' Criollo in Bornheim, Mitgliederstammtisch Hufnagelstrasse 22 Frankfurt/M. http://www.adminx.de 7.. 2.12.2003 EUROFORUM Deutschland GmbH Rechtsfallen f?r IT-Sicherheitsbeauftragte Semi, Berlin Prinzenallee 3 D?sseldorf http://www.euroforum.com 8.. 2.12.2003 K+P Consulting GmbH (Kluge+Partner) Wirtschaftsclub Frankfurt Ahastra?e 5 Darmstadt http://www.kluge-partner.de 9.. 3.12.2003 EUROFORUM Deutschland GmbH Rechtsfallen f?r IT-Sicherheitsbeauftragte Semi, Berlin Prinzenallee 3 D?sseldorf http://www.euroforum.com 10.. 3.12.2003 Frankfurt Perl Mongers - Frankfurt.pm, Termine 19 Uhr Caf? Activ, Basaltstra?e 13a Frankfurt/M. Bockenheim http://frankfurt.perlmongers.de 11.. 3.12.2003 PHP + Linux User Group Frankfurt/M, Termine 19 Uhr, Restaurant Dionysos, R?delheimer Stra?e 34 B Frankfurt/M. Bockenheim http://www.lugfrankfurt.de From abriggs at westnet.com.au Mon Nov 3 05:15:02 2003 From: abriggs at westnet.com.au (Anthony Briggs) Date: Mon, 3 Nov 2003 18:15:02 +0800 Subject: pickle: maximum recursion depth exceeded In-Reply-To: References: Message-ID: At 11:29 AM +1100 3/11/03, Simon Burton wrote: >Hi, > >I am pickling big graphs of data and running into this problem: > >[...] > File "/usr/lib/python2.2/pickle.py", line 225, in save > f(self, object) > File "/usr/lib/python2.2/pickle.py", line 414, in save_list > save(element) ... > File "/usr/lib/python2.2/pickle.py", line 225, in save > f(self, object) > File "/usr/lib/python2.2/pickle.py", line 405, in save_list > write(self.put(memo_len)) >RuntimeError: maximum recursion depth exceeded > >However, it works when i try the smallest examples and use >sys.setrecursionlimit(4000) > >This seems like a limitation in the pickling code. Yes? I would suspect that you have a loop in your definitions, eg. A imports B, and B imports A, particularly since you're trying small examples, and they're still exceeding the recursion depth. Hope that helps, Anthony -- ---------------------------------------------------- HyPEraCtiVE? HeY, WhO aRE YoU cALliNg HypERaCtIve?! aBRiGgS at wEStNeT.cOm.aU ---------------------------------------------------- From adalke at mindspring.com Sun Nov 16 14:16:22 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 16 Nov 2003 19:16:22 GMT Subject: Python's simplicity philosophy References: <3FAC19F0.284DCB03@alcyone.com> <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> Message-ID: Alex: > I have already suggested, in a post on this thread's direct ancestor 9 days > ago, the 100%-equivalent substitution in pure, simple, faster Python: I've only been skimming this thread. Now upon reread I see you also looked at the standard library. No fair -- I'm supposed to be the only one who does that! :) > Nope -- itertools is not about CONSUMERS of iterators, which this one would > be. All itertools entries RETURN iterators. Yup. There's no good, existing, natural place for such a function, that I can tell. > Given that the sort method of lists now has an optional key= argument, I > think the obvious approach would be to add the same optional argument to min > and max with exactly the same semantics. I.e., just as today: That follows Moshe's comment that a "Decorate Max Undecorate", in parallel to Decorate Sort Undecorate. Nice. > we'd also have > > x = max(somelist, key=whatever) > somelist.sort(key=whatever) > assert x == somelist[-1] Is 'key' also an iterable? ... > That would be max(seq, key=len) in my proposal. Ahh, it's the function used to get the keys. What about 'getkey' as a name? I looked through the back thread but didn't see your function definition. Is it backwards compatible to the existing max function?... You know, I never realized how strange max was in the first place, so that max(1, 2) and max( (1, 2) ) are both valid. It must assume that if there's only one argument then the latter form is appropriate. Then your form must say that if there's only one non-keyword argument then it's of the form max(seq, **args) But max(a, b, key=len) seems reasonable as well. Then again, so does max(seq, len) > a perfectly natural extension, it seems to me. I've found such total and > extreme opposition to this perfectly natural extension in private > correspondence about it with another Python committer that I've so far > delayed proposing it on python-dev -- for reasons that escape me it would > appear to be highly controversial rather than perfectly obvious. My guess is that reaction is based on the need to have both forms max(a, b) and max(seq) and allow a key function to be passed in, and make it feel natural without running into problems when the two might be mixed up. > even though > the tasks handled by the standard library are heavily slanted > to string and text processing, networking &c, and (of course) > "pure infrastructure", rather than typical application tasks. Yeah, I worry about that bias error when I do my analysis. I really should also scan some of the other (proprietary) code bases I have access to, but then it leads to claims of being irreproducible. Besides, despite being a scientific programmer, I mostly do "string and text processing, networking &c." Andrew dalke at dalkescientific.com From susi2000 at web.de Tue Nov 25 15:32:46 2003 From: susi2000 at web.de (Susanne) Date: 25 Nov 2003 12:32:46 -0800 Subject: Problem with PyRun_SimpleFile and MFC Application Message-ID: <188007e5.0311251232.6c4b6254@posting.google.com> Hello! In have embedded python into my MFC application. It works fine using the PyRun_SimpleString method, giving it a string with some simple commands. When i am using PyRun_SimpleFile instead, my application crashes. I have also created a console application. There i also call PyRun_SimpleFile. The console application executes the given script. My code looks like the following: ********************************** MFC-Application: ********************************** >Py_SetProgramName("testclient"); >/* Initialize the Python interpreter. Required. */ >Py_Initialize(); >initCORBA(); >curMode = DEBUG_MODE; >//**** is running!!!!***** >//CString command = "import CORBA; CORBA.SetTPData();"; >//PyRun_SimpleString(command); >//CORBA is my python module, SetTPData a method of this modul >//in SetTPData i open an AfxMessageBox, so thats why i know that >//it works >//path of my file >char * filename2 = "C:\\cvsroot\\OCI-TestClient\\projects\\main\\tao\\test.py"; >FILE *fp =fopen(filename2,"r"); int result; >if(fp !=NULL) >{ > //does not work :-( > result = PyRun_SimpleFile(fp,filename2); > fclose(fp); >} >Py_Finalize(); **************************************** Now the code of the console application: **************************************** >/* Pass argv[0] to the Python interpreter */ >Py_SetProgramName(argv[0]); >/* Initialize the Python interpreter. Required. */ >Py_Initialize(); >//create instance of my class >PythonExtension * pythi = new PythonExtension(); >//init my module (not the same module like in MFC app) >pythi->initspam(); >char * filename2 = "C:\\cvsroot\\OCI-TestClient\\projects\\main\\tao\\test.py"; >FILE *fp =fopen(filename2,"r"); >int result; >//works fine, only says, that there is no modul called CORBA >//see below >result = PyRun_SimpleFile(fp,filename2); >printf("Result: %d",result); ********************** My python script file: ********************** >import CORBA; >CORBA.SetTPData(); >//... ************************ So, does anyone of you have an idea, what i am doing wrong in my mfc app? Susanne From knight at baldmt.com Fri Nov 7 11:56:34 2003 From: knight at baldmt.com (Steven Knight) Date: Fri, 7 Nov 2003 10:56:34 -0600 (CST) Subject: ANNOUNCE: SCons 0.94 adds command-line argument features, fixes key bugs Message-ID: SCons is a software construction tool (build tool, or make tool) written in Python. It is based on the design which won the Software Carpentry build tool competition in August 2000. Version 0.94 of SCons has been released and is available for download from the SCons web site: http://www.scons.org/ Or through the download link at the SCons project page at SourceForge: http://sourceforge.net/projects/scons/ RPM and Debian packages and a Win32 installer are all available, in addition to the traditional .tar.gz and .zip files. WHAT'S NEW IN THIS RELEASE? This release adds the following features: - A new AddOptions() method makes it easier to add multiple command-line option specifications in a single call. - New BoolOption(), EnumOption(), ListOption(), PackageOption() and PathOption() functions provide canned initialization for several useful types of common option behavior. - New BUILD_TARGETS, COMMAND_LINE_TARGETS and DEFAULT_TARGETS variables provide access to the lists of targets specified on the command line or through calls to the Default() function or method. The following fixes have been added: - The use of CPPDEFINES with C++ source files has been fixed. - The env.Append() method now works properly when the operand is an object with a __cmp__() method (like a Scanner instance). - Subclassing the Environment and Scanner classes has been fixed. - C++ compilation with the SGI compiler has been fixed. - C and C++ compilation with AIX compiler has been fixed. The documentation has been improved: - The man page un-indented correctly after examples in some browsers; this has been fixed. - Use of the Options() object to control command-line options has been documented in the User's Guide. - New features have been documented in the man page and User's Guide. ABOUT SCONS Distinctive features of SCons include: - a global view of all dependencies; no multiple passes to get everything built properly - configuration files are Python scripts, allowing the full use of a real scripting language to solve difficult build problems - a modular architecture allows the SCons Build Engine to be embedded in other Python software - The ability to scan files for implicit dependencies (#include files); - improved parallel build (-j) support that provides consistent build speedup regardless of source tree layout - use of MD5 signatures to decide if a file has really changed; no need to "touch" files to fool make that something is up-to-date - easily extensible through user-defined Builder and Scanner objects - build actions can be Python code, as well as external commands An scons-users mailing list is available for those interested in getting started using SCons. You can subscribe at: http://lists.sourceforge.net/lists/listinfo/scons-users Alternatively, we invite you to subscribe to the low-volume scons-announce mailing list to receive notification when new versions of SCons become available: http://lists.sourceforge.net/lists/listinfo/scons-announce ACKNOWLEDGEMENTS Special thanks to Hartmut Goebel, Steve Leblanc, Gary Oberbrunner and Vincent Risi for their contributions to this release. On behalf of the SCons team, --SK From not.available at na.no Sat Nov 1 19:59:58 2003 From: not.available at na.no (Noen) Date: Sun, 02 Nov 2003 00:59:58 GMT Subject: Everybody likes python In-Reply-To: <20031101105027.12380.00000091@mb-m11.aol.com> References: <20031101105027.12380.00000091@mb-m11.aol.com> Message-ID: KefX wrote: >>I thought Guido wanted Python associated with Monty Python? > > > Yup, though the snake remain popular nonetheless. I think it may come down to a > match between the remaining Pythons and a python. We could throw in a computer > running a Python app while we're at it. Python vs. Python vs. python! > > - Kef > Stop discussing, just hug the snakes! From tweedgeezer at hotmail.com Mon Nov 10 17:55:18 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 10 Nov 2003 14:55:18 -0800 Subject: A vote for re scanner References: <5b4785ee.0311100714.1445cdfb@posting.google.com> Message-ID: <698f09f8.0311101455.41f8706a@posting.google.com> wade at lightlink.com (Wade Leftwich) wrote in message news:<5b4785ee.0311100714.1445cdfb at posting.google.com>... > Every couple of months I have a use for the experimental 'scanner' > object in the re module, and when I do, as I did this morning, it's > really handy. So if anyone is counting votes for making it a standard > part of the module, here's my vote: While I don't think they're still accepting votes :), you've pointed me to something I didn't know about until now. What kinds of things have you been using re.Scanner for? Jeremy From hanzspam at yahoo.com.au Fri Nov 21 08:04:54 2003 From: hanzspam at yahoo.com.au (Hannu Kankaanp??) Date: 21 Nov 2003 05:04:54 -0800 Subject: Python's simplicity philosophy References: <2259b0e2.0311112248.3be2d304@posting.google.com><17lsb.109042$fl1.4548960@twister.southeast.rr.com> Message-ID: <840592e1.0311210504.2258911c@posting.google.com> "Terry Reedy" wrote in message news:... > The above was a minimal 'concept' proposal to test the aesthetics of > something structurally different from current 'lambda's. I think I > would make all identifiers params by default, since I believe this to > be more common, and 'tag' non-locals, perhaps with one of the > reserved, as yet unused symbols. Example: lambda x: x + y == `x + @y` > or `x+y@`. Since expressions cannot assign, no global declaration is > needed. A pretty simplistic way to do something similar would be this alias: @ <=> lambda X=None, Y=None, Z=None: Thusly: seq.sort(lambda x, y: cmp(y, x)) => seq.sort(@cmp(Y, X)) map(lambda x: x[::-1], seq) => map(@X[::-1], seq) It could replace lambda for most cases. Half of the function definition wouldn't be "useless trash" anymore, and redundancy in describing the parameter names would go away (lambdas don't usually need describing parameter names). But @ isn't exactly describing symbol (though "lambda" or "def" don't scream out "Here's a function definition!" either) and the 3 implicit arguments don't really fit with Python's explicity philosophy.... And from what I've gathered, Guido would rather remove lambda than introduce syntax that encourages small anonymous functions (in a weird way to boot). Oh well. From not.available at na.no Tue Nov 4 14:31:26 2003 From: not.available at na.no (Noen) Date: Tue, 04 Nov 2003 19:31:26 GMT Subject: XORing long strings opimization? In-Reply-To: References: <3ISpb.24447$BD3.4566933@juliett.dax.net> Message-ID: Peter Otten wrote: > Noen wrote: > > >>def XOR(s1,s2): >>""" XOR string s1 with s2 """ >>output = "" >># Argument check >>if (type(s1) and type(s2)) != type(""): >>raise TypeError, "Arguments are not strings" >>if len(s1) != len(s2): >>raise ValueError, "Size differs in strings" >># Xoring >>for c1 in s1: >>for c2 in s2: >>output += chr(ord(c1) ^ ord(c2)) >>return output >> >>This way is very slow for large strings. >>Anyone know of a better and faster way to do it? > > > Before we start optimizing: > > len(XOR(s1, s2)) == len(s1) * len(s2) > > Bug or feature? > > Peter Oh, didnt notice that as I wrote it. Thanks... Anyway, this is how it should be. def XOR(s1,s2): """ XOR string s1 with s2 """ output = "" # Argument check if (type(s1) and type(s2)) != type(""): raise TypeError, "Arguments are not strings" if len(s1) != len(s2): raise ValueError, "Size differs in strings" # Xoring for i in range(len(s1)): output += chr(ord(s1[i]) ^ ord(s2[i])) return output From rainerd at eldwood.com Mon Nov 17 22:01:35 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Tue, 18 Nov 2003 03:01:35 GMT Subject: Origin of the term "first-class object" References: <8ef9bea6.0311171335.356a7af6@posting.google.com> Message-ID: John Roth wrote: > I think I'd disagree with that. In fact, except for the optimization > within function bodies, I can't think of anything I can't do > with a name that I might want to. I can think of several things. One would be passing a name as an argument to a function. Given the immutability of certain Python objects, it is often necessary to write statements in the form of "x = f(x)". This is a violation of the Once And Only Once principles, since it mentions the same variable twice. I'm not saying that the way Python deals with objects and variables is wrong. Language design is a series of trade-offs, and the simplicity and clarity of Python may very well make up for its limitations. However, that doesn't mean that the limitations are not real. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From __peter__ at web.de Sat Nov 22 06:23:25 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Nov 2003 12:23:25 +0100 Subject: Newbie here... getting a count of repeated instances in a list. References: Message-ID: Amy G wrote: > I started trying to learn python today. The program I am trying to write Welcome to the worst programming language ... except all others :-) > will open a text file containing email addresses and store them in a list. > Then it will go through them saving only the domain portion of the email. > After that it will count the number of times the domain occurs, and if > above a certain threshhold, it will add that domain to a list or text > file, or > whatever. For now I just have it printing to the screen. > > This is my code, and it works and does what I want. But I want to do > something with hash object to make this go a whole lot faster. Any > suggestions are appreciated a great deal. I think your code looks alright, just not very idiomatic, as one might expect. I have tinkered with it a bit and came up with the version given below. I hope the result is readable enough, so I have abused the comments to give some hints regarding the language/library that you might find useful. get_domains() creates a dictionary with domains as keys and the number of occurences as values, e. g. {"nowhere.com": 10, "elswhere.edu": 5} The code for extracting the domain from a line is factored out in its own function extract_domain(). Precautions have been taken to make the file usable both as a library module and a stand-alone script. import sys def get_domains(lines): "Generate a domain->frequency dict from lines" domains = {} # enumerate() is the pythonic equivalent for # index = 0 # while index < len(alist): # alist[index] # index += 1 for lineno, line in enumerate(lines): try: domain = extract_domain(line) except ValueError: print >> sys.stderr, "IGNORING line %d: %r" % (lineno+1, line.strip()) else: # else in a try ... except ... else statement # may look a bit strange at first, but ist # really useful domains[domain] = domains.get(domain, 0) + 1 return domains def extract_domain(line): "Remove the name part of an emal address" try: return line.split("@", 1)[1].strip() except IndexError: # in this short example, you could just catch # the index error in get_domains; however, in the long run # it pays for client code to always see the "right" exception raise ValueError("Invalid email address format: %r" % line.strip()) def filter_domains(domains, threshold=10): "The most frequent domains in alphabetical order" # below is a demo of a very popular construct # called "list comprehension" result = [domain for domain, freq in domains.iteritems() if freq >= threshold] # the list.sort() method returns None, so # sorting may look a bit clumsy when # you first encounter it result.sort() return result # The __name__ == "__main__" test is a common idiom in Python. # The code below is only executed if you run the script from the # command line, but not if you import it into another module, # thus allowing to use the above functions in other contexts. if __name__ == "__main__": # for proper handling of command line args, have a look at # the optparse module threshold = int(sys.argv[2]) # the file object is iterable, so in many # cases you can avoid an intermediate list # of the lines in a file source = file(sys.argv[1]) try: domain_histogram = get_domains(source) finally: # clean up behind you if something goes wrong in the # try block source.close() print "domains with %d or more messages" % threshold print "\n".join(filter_domains(domain_histogram, threshold)) Peter From adolfo at linuxmail.org Fri Nov 21 19:10:11 2003 From: adolfo at linuxmail.org (Adolfo) Date: 21 Nov 2003 16:10:11 -0800 Subject: Help Pliz ! stuck on page 4 of tutorial Message-ID: <91de052a.0311211610.48fdd0ea@posting.google.com> Hello everyone, I am a newbie starting Fredrik Lundh .pdf tutorial. Running W2000. I am stuck in page four "Hello Again" program: When I try running it, it shows the root Python window very fast and dissapears. The intended Tk window with buttons: either does not show, or dissapears fast before I can tell it is there. The first program on the tutorial did run fine. Here's the program as shown on the tutorial: ==================================================== from Tkinter import * class App: def_init-(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="QUIT", fg="red", comand=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print "Hi there, everyone !" root = Tk() app = App(root) root.mainloop() =================================================== Any help will be much appreciated, Adofo Aguirre Santa Barbara, CA From jzsmith at optonline.net Wed Nov 26 10:47:03 2003 From: jzsmith at optonline.net (John Z. Smith) Date: Wed, 26 Nov 2003 10:47:03 -0500 Subject: How to call functions with list and keyword arguments? Message-ID: Hi, I want to subclass a class (more precisely, optparse.Option). that looks like class Option: def __init__(self, *opts, **attrs): do_something() I want to do something in my __init__ and and also call Option.__init__. Then I don't know how to pass the arguments. For example, class MyOption: def __init__(self, *opts, **attrs): do_my_own_thing() Option.__init__(self, opts, attrs) does not work (and you know why). I figured out some very ugly ways to do this but I believe there should be an elegant way to pass the argments to superclass. From calfdog at yahoo.com Fri Nov 7 11:16:18 2003 From: calfdog at yahoo.com (calfdog at yahoo.com) Date: 7 Nov 2003 08:16:18 -0800 Subject: Python, Unicode, Excel and Web Tesing References: Message-ID: Peter Otten <__peter__ at web.de> wrote in message news:... > calfdog at yahoo.com wrote: > > [problems with excel automation, reportedly due to unicode] > > (u'Test1',) > > is a tuple, you are doing > > (u'Test1',)[-1] > > to extract the last item in that tuple, which is, by the way, the same as > the first item (u'Test1',)[0] in this case. > > So you may still run into trouble when you inadvertently try to convert your > unicode string into a str *and* it contains characters with ord(c) >= 128. > > However, rest assured that Python will spit out a helpful traceback :-) > > Peter Thanks Peter for the feedback!! From newsgroups at jhrothjr.com Mon Nov 3 19:10:17 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 3 Nov 2003 19:10:17 -0500 Subject: strptime performance References: Message-ID: "George Trojan" wrote in message news:bo6oaf$vfq$1 at news.nems.noaa.gov... > Is time.strptime() intrinsically slow and should be avoided whenever > possible? I have the following code in my application: According to the "what's new in Python" for 2.3, the strptime implementation was switched from a lightweight wrapper around the frequently buggy and incompatible C library to a portable pure Python implementation. Yes, it's going to be a lot slower. John Roth From http Wed Nov 19 17:31:28 2003 From: http (Paul Rubin) Date: 19 Nov 2003 14:31:28 -0800 Subject: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <7xoevcf1u2.fsf@ruckus.brouhaha.com> <7x7k1zc0si.fsf@ruckus.brouhaha.com> <61Ztb.3481$sb4.1708@newsread2.news.pas.earthlink.net> <7xk75ysycx.fsf@ruckus.brouhaha.com> Message-ID: <7x4qx0ng73.fsf@ruckus.brouhaha.com> "Andrew Dalke" writes: > The 'against' side says, as you do, that having list.sort required > to be stable now places an extra barrier to anyone else who > implements a list-alike sort, because that sort should now also > be stable. It's also a barrier to anyone who implements list sort, not just listalike sort. Of course that doesn't affect CPython or Jython users, who already have a built-in stable list sort. But what about PyPy or maybe someone trying to reimplement Python from scratch in C? > What mollifies the latter view is that some user-defined sorts > won't have ties, so there will never be a problem. I'm not a sorting whiz but my feeling is that if an application needs sort to be stable, that's already a sign that something isn't really right about it. Sorting is supposed to mean turning an unordered permutation into an ordered one. So if list.sort gives you a useable answer (i.e. one that satisfies your application's needs), then randomizing the list and then sorting it should also give you a useable answer. The way to do that is make your comparison function look at every part of the record that you care about, not just select some single field and count on stability to take care of the rest. If at all possible, design the comparison function so that there are never any ties. To do otherwise has in my experience been a source of bugs that don't become evident til much later. From aleaxit at yahoo.com Fri Nov 7 18:22:32 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 07 Nov 2003 23:22:32 GMT Subject: Precise calculations References: <0e547e2582633f8ea23d0b5e5d337128@news.meganetnews.com> Message-ID: Ben Finney wrote: ... >> Could anybody help me on how to do precise calculations with Python >> the way hand-held calculators do? > > Use rounding, e.g. as implemented by the str() function. From the above Use str if you really want to do like hand-held calculators, i.e., hide some digits. If you want really high precision in binary floating point, the gmpy extension module may be useful; if in decimal floating point, there is a class Decimal that's being worked on to eventually provide that, too. Alex From martin at v.loewis.de Sat Nov 1 03:53:35 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 01 Nov 2003 09:53:35 +0100 Subject: gcc compile / link questions References: Message-ID: "Edward C. Jones" writes: > I compile and link Python extension modules using the script > > gcc -fPIC -g -I/usr/local/include/python2.3 \ > -Wall -Wstrict-prototypes -c mymodule.c > g++ -shared mymodule.o -L/usr/local/lib -o mymodule.so > > It works for me but it isn't pretty. Is there a better way to write it? Yes, you should write a setup.py using distutils. > Gcc finds all the libraries that need to be linked in. For example, > "/usr/local/lib/python2.3/site-packages/numarray/libnumarray.so". How > does gcc do this? I doubt this statement. gcc does not find things in /usr/local/lib/python2.3. Why do you think it does? > I created a .so file "utilities.so" that contains some C functions > that are called in mymodule.c but are not visible from Python. Both > "utilities.c" and "mymodule.c" use numarray. What changes do I make in > the script above? Must I use the nasty "libnumarray_UNIQUE_SYMBOL" > trick? You cannot access symbols from different extension modules; each module has its own, separate, space of symbols. If you want to invoke functions in a different module, you must do so through the Python API. Some extension modules provide a CObject containing the API; if numarray offers such a thing, you should use it. Regards, Martin From aleax at aleax.it Sun Nov 2 06:25:05 2003 From: aleax at aleax.it (Alex Martelli) Date: Sun, 02 Nov 2003 11:25:05 GMT Subject: suggestion for Python References: Message-ID: Fran?ois Miville-Dech?ne wrote: > I find your language very nice, it is actually more than three quarters > of what I had been dreaming for years a programming language should be. > But I mourn the passing of APL, another interpreted language. I like Having worked a LOT with both APL and APL2 around 1977-1986, I don't really mourn them at all (except when I'm in my cups, sometimes, but then I'm mostly mourning the fact that 20 years ago I was younger:-). > One suggestion I would propose would be to make common operators > distributive by enclosing them in square brackets. For instance: > [1, 3, 5, 7] [*] [1, 2, 1, 3] would be equivalent to > [[1, 3, 5, 7][i] * [1, 2, 1, 3][i] for i in range(3)] > In APL the common operators were implicitly distributive over vectors, > but it is not possible for Python due to the more evident concatenation > meaning of + and *. The map function does the job for a user > defined-function, as would do in this instance something like > map(multiply, [1, 3, 5, 7], [1, 2, 1, 3]), but it is cumbersome to > redefine simple operations. import operator map(operator.mul, [1,3,5,7], [1,2,1,3]) and you're done. Or, to taste, [ a*b for a, b in zip([1,3,5,7], [1,2,1,3]) ] > One problem with Python is the necessity to define very short functions > to enable operators to be the object of function of functions such as Yes, we do lack a _good_ syntax for "codeblock literals" -- about a month ago we were discussing possibilities quite actively here. > map. Another problem is that common operators cannot be easily > redifined onto larger mathematical objects one might conceive and could > be defined by the means of classes. This could be solved by setting > that such functions named as add, mult, div, defined as two-parameter > functions, would automatically correspond to the dyadic +, *, /, etc. Standard library module operator has those. But I'm not sure what you mean by "redefined onto larger mathematical objects" -- you can get operator overloading on any type by defining __add__ __mul__ etc. > And conversely, any name of a two-parameter function, let it be > hypothenuse, would signify when enclosed in parentheses the > corresponding dyadic operators. > > so that 3(hypothenuse)4 would be 5 Yep, Haskell has something like that, except that instead of yet another overloading for parentheses (which have too many already!-) it uses `...` which in Python are an unfortunate and useless duplciate for repr(...). However to make sense you need to be able to define priority and associativity and that gets hairy. > This would give Python all the advantages of late APL and much more, for > APL could process only regular data structures such as matrices whereas APL2 could have arrays with each row a different length, which helped. > Python is so good with data more to be encountered in real life such as > ill-formatted texts to be divided in chapters, sections and subsections > in order to fit in a certain software, just to name one intance, by the > means of the use of reg exps and tree-processing. > > Thanks for your attention. The sole objection to the development I > propose for Python would be a certain loss of readability for persons > not acquainted with the language, but reg exps are not that readable > neither and yet what would we do without them? They're in a separate standard library module -- the criteria are laxer. Getting into core Python demands passing MUCH stricter tests on all scores. Alex From amk at amk.ca Thu Nov 13 11:52:57 2003 From: amk at amk.ca (A.M. Kuchling) Date: Thu, 13 Nov 2003 10:52:57 -0600 Subject: Validate XML with RELAX NG References: <3FB38959.CE275465@mortauxspams.bz> Message-ID: On Thu, 13 Nov 2003 14:38:33 +0100, Olivier Hoarau wrote: > To transform RelaxNG compact to RelaxNG "full", I use rnc2rng written in > Python. I have some difficulties, the file I obtain from a RELAXNG > compact file is not conform. Use Trang instead; rnc2rng doesn't seem to be complete as it fails on the RNC schema for RNG full, for example. See http://www.amk.ca/notes/rng.html for a little two-line wrapper script for Trang. If you must have a pure Python solution, you're going to have to roll up your sleeves and fix rnc2rng. --amk From bignose-hates-spam at and-benfinney-does-too.id.au Thu Nov 6 23:29:33 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 7 Nov 2003 15:19:33 +1050 Subject: Why does changing 1 list affect the other? References: <8ufjqvc24b7o1v0c32p2cpv7us32gtsdic@4ax.com> Message-ID: On Fri, 07 Nov 2003 04:03:27 GMT, Cy Edmunds wrote: > Scalars do NOT automatically make a copy. True, they can't be modified at all, so the only assignment operation that makes sense is to assign a new value entirely. This was obscured in my summary of the issue. So, yes, "mutable objects can be modified" is the better starting point. -- \ "Faith may be defined briefly as an illogical belief in the | `\ occurrence of the improbable." -- Henry L. Mencken | _o__) | Ben Finney From peter at engcorp.com Sat Nov 29 17:40:24 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 29 Nov 2003 17:40:24 -0500 Subject: sockets, select or: twisted and other file-descriptors References: Message-ID: <3FC92058.C3B53580@engcorp.com> "Diez B. Roggisch" wrote: > > I now want to rewrite it using select and no more threads. If it was only a > network-application, I'd try to make my first steps using twisted. However, > I'm not sure if its possible to have twisteds select also take my > filedescriptors for the serial connection. Twisted has some (or full?) support for serial ports, so you should investigate it more closely to see just what it does and whether that would work for your own application. A download is free, and you can browse the source pretty easily to get the gist of it. I suspect you'll see right away that it is or is not suitable. (Of course, someone else might be able to say "yeah, it works" or something already, but there's no real substitute for just checking for yourself.) -Peter From chenyu468 at hotmail.com Fri Nov 7 02:21:48 2003 From: chenyu468 at hotmail.com (chenyu) Date: 6 Nov 2003 23:21:48 -0800 Subject: newbie question, what's the difference between built-in functions "__new__" and "__init__" Message-ID: <6143ac23.0311062321.757bc0fc@posting.google.com> Hi, I have studied other's program and found __new__ and __init__ are used. My question is what's the difference between built-in functions "__new__" and "__init__". Could anyone help me? Thank you in advance. kind regards/chenyu From robin at jessikat.fsnet.co.uk Tue Nov 18 08:44:42 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 18 Nov 2003 13:44:42 +0000 Subject: rotor alternative? Message-ID: It seems that the rotor module is being deprecated in 2.3, but there doesn't seem to be an obvious alternative. I'm using it just for obfuscation. It seems we have ssl available in 2.3 for sockets, but there seems no obvious way to use that from python code. Is an alternative to rotor planned? -- Robin Becker From keflimarcusx at aol.comNOSPAM Mon Nov 17 20:11:13 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 18 Nov 2003 01:11:13 GMT Subject: True inconsistency in Python References: <3FB91F07.9F275BB4@alcyone.com> Message-ID: <20031117201113.28795.00000484@mb-m17.aol.com> >Yes. The same cascade into insanity developes. If you're testing for >falsity, why not write x == false? But what about _that_ test, >shouldn't that be (x == false) != false? And _that_ test ... > Of course the point that those tests aren't any less redundant from the language perspective is valid. But they're a heck of a lot more redundant to a human reader than a single "== false". >My point is that any such coding standard is dumb. In my experience, every coding standard has things one would call "dumb". But not everybody calls the same thing dumb. (I remember some people objecting to my assertion that "assert" should be used as often to check parameters in C code when defining functions...I still don't get how that's dumb. Some even claimed that assert was a C++ thing!) >> But if whatever goes in "blah" is really long (and often it is), you >> very >> quickly see what is being compared: it's a straight boolean >> comparison, whereas >> with the second you have to look at the whole thing, find no >> comparison >> operator, and go, "oh, there's no explicit comparison so it's >> obviously an >> implicit straight boolean comparison". > >I don't see the value in this. The expression in an if statement is >treated as a Boolean expression. In languages where there isn't a >distinct Boolean type without implicit conversions (like your example, >C89), it doesn't matter whether you put the explicit comparison there or >not. However long the expression is, I don't see how adding `== true' >at the end makes it more clear. What if the expression is 37 lines long? (Can't happen? I'm LOOKING at such an example!) Fishing out the main comparison in such a monster isn't always the easiest thing to do. Of course I'm exaggerating here, since we usually don't write 37-line expressions, but still. >It's a Boolean test, what's to make >explicit? Yes, all tests are boolean tests in the sense that they evaluate to a bool and the if statement then compares the result, but not all comparisons are boolean comparisons in the sense that we don't always compare to a boolean value. In other words, "a == 0" isn't comparing against true or false, it's comparing against an integer. It's worth noting here that omitting the "== 0" here is considered bad style by many (though this is by no means universal). The camp that would have you write "== false" invariably falls in the same camp that would have you write "== 0", because that way the two would be consistent in that you always specify what's being compared to what. Of course, this doesn't mean everybody would have you write "== 0" would also have you write "== false". The idea is consistency (I don't know how that slipped my mind in my original posting.) >All including the explicit test there does is make other programmers >wonder if you've lost your mind Not all programmers would think that, again. :) >Trying to correct that error, you end up with monstrosities such >as bool(x) == True or operator.truth(x) == True (or the equivalent in >other languages), and after some point it should dawn on the programmer >that the explicit True test is pointless. I don't see how that would logically follow just from making an explicit bool test. We know that such code is broken when we consider it, and then we reject it, and we just do it the way we always did it, whether that's omitting the explicit comparison altogether or comparing against false, or whatever other possibility. - Kef From tjreedy at udel.edu Wed Nov 26 11:55:43 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Nov 2003 11:55:43 -0500 Subject: Extract double in binary file References: Message-ID: <3sydnZ0FHKKNRlmi4p2dnA@comcast.com> "Gandalf" wrote in message news:mailman.1105.1069859877.702.python-list at python.org... > > > > > >I've a binary file with data in it. > >This file come from an old ms dos application (multilog ~ 1980). > >In this application, a field is declared as a 'decimal' (999 999 > >999.99). > >I put 0.00 in the field and save the record to the file. > >When I look in the binary file (with python or an hex editor), the > >field is stored on 8 bytes: 00-00-00-00-00-00-7F-00. > >I try unpack from struct module but the result isn't good. > > > >Can someone help me? > > > > > Most likely it is a BCD field. I believe hex OP gave is for double 0.0e0 (exponents are biased). OTOH, BCD for 11 digits would be 6 bytes, all 0, which also has. Putting -1.0 and 1.0 in field and storing would clarify storage format if really not known. tjr From duane at franz.com Sun Nov 2 10:29:05 2003 From: duane at franz.com (Duane Rettig) Date: 02 Nov 2003 07:29:05 -0800 Subject: Paging Mr. Rettig [ws Re: Explanation of macros; Haskell macros] References: <87brs2tjut.fsf@memetrics.com> <4wuaj84x5.fsf@franz.com> Message-ID: <4vfq23i2m.fsf@franz.com> Marcin 'Qrczak' Kowalczyk writes: > On Sun, 02 Nov 2003 02:01:58 -0800, Duane Rettig wrote: > > > With this much openness, it doesn't seem unreasonable > > to expect a debugger to be able to use such information to make macros > > and the forms they expand into completely debuggable and steppable at > > any desired level. > > Does any debugger do this? Most Lisp debuggers will do this with compiled code. I know of nne which do this to compiled code without recompilation. I apologize for the lack of context in my reply - it was late last night and I have no time this morning as well; Lisp, and in particular CL, does very well in debugging interpreted code. However, just as I detest the need for a -g option in gcc, I always strive to avoid requiring the user to recompile in order to get debugging info. In CL, the debug quality interacts with but is separate from the speed, safety, compilation-speed, and space qualities. -- Duane Rettig duane at franz.com Franz Inc. http://www.franz.com/ 555 12th St., Suite 1450 http://www.555citycenter.com/ Oakland, Ca. 94607 Phone: (510) 452-2000; Fax: (510) 452-0182 From bucodi at wanadoo.fr Tue Nov 25 06:27:36 2003 From: bucodi at wanadoo.fr (Rony Steelandt) Date: Tue, 25 Nov 2003 12:27:36 +0100 Subject: win32com (VBScript to Python) problem References: Message-ID: Not knowing exactly what you want to do, just a question. Why use COM, shutdown is an exe so why not just execute it? Rony "Tim Howarth" a ?crit dans le message de news: d715dc564c.tim at worthy.demon.co.uk... > > > I'm (very non expert) trying to use a snippet of VBScript (to shut down > Windows workstations) converted to Python but have hit a problem. > > > The VBScript below work fine; > > > pc="MyPC" > > Set oWMI=GetObject("winmgmts:{impersonationLevel=impersonate,(Shutdown)}!\\"_ > & pc & "\root\cimv2") > > Set colOperatingSystems = oWMI.ExecQuery("Select * from Win32_OperatingSystem") > > For Each obj in colOperatingSystems > obj.Win32shutdown 12 > Next > > > > but my translation results in "'int' object is not callable" with the > attempted call to Win32Shutdown. > > This is with Python 2.3.2 win32all 1.57 or Active Python 2.3.2 > > print type(obj.Win32ShutDown) > gives int > > print obj.Win32ShutDown > gives 87 - the ASCII code of "W" - coincidentally ? > > > > > import win32com.client, sys > > > pc='MyPC' > > oWMI = > win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate,\ > (Shutdown)}!\\" + pc + r"\root\cimv2") > > colOperatingSystems = oWMI.ExecQuery(r"Select * from Win32_OperatingSystem") > > for obj in colOperatingSystems: > obj.Win32ShutDown(12) > > > > > -- > ___ > |im ---- ARM Powered ---- From reply.in.the.newsgroup at my.address.is.invalid Fri Nov 21 06:04:25 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 21 Nov 2003 12:04:25 +0100 Subject: plataform dependent code References: Message-ID: Zunbeltz Izaola: >I am using wxPython and i want to have some code plataform dependent. >Is it possible? import sys if sys.platform == 'win32': pass elif sys.platform == 'linux2': pass >I can't find any information about this in the net. You've got to be kidding. -- Ren? Pijlman From max at alcyone.com Fri Nov 14 06:34:39 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 14 Nov 2003 03:34:39 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <2259b0e2.0311140033.4e3ca8ea@posting.google.com> Message-ID: <3FB4BDCF.19876B55@alcyone.com> "Brandon J. Van Every" wrote: > Fair warning: you are going to hear a lot of people talking in > circles. You > are only going to get things done if you are the kind of person who > will > take a bull by the horns and actually get things done, even / > especially > when others are yapping mindlessly and endlessly. So what have you done? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ Then conquer we must, for our cause is just ... -- Francis Scott Key From shuvit at 127.0.0.1 Tue Nov 4 16:12:57 2003 From: shuvit at 127.0.0.1 (Dave) Date: Tue, 4 Nov 2003 14:12:57 -0700 Subject: PyQt leaves C-code in python modules References: Message-ID: "Phil Thompson" wrote in message news:mailman.439.1067973360.702.python-list at python.org... > On Tuesday 04 November 2003 6:45 pm, Dave wrote: > > I'm having a strange problem with the pyqt-tools in the latest Debian > > packages. When I run > > $ pyuic colortool.ui > colortool.py > > Extracting init() > > Extracting loadSettings() > > Extracting saveSettings() > > ... > > it produces 'colortool.py' with python function headers, but the body of > > the functions are still in C. There are no error messages, just the normal > > log of "extracting" functions. > > [...] > That's because the form includes embedded C++ code. There is nothing to stop > you embedding Python code (just ignore the C++ style function definition) and > it will be properly extracted. > > What pyuic doesn't do is look at the embedded code and try to work out if it > is Python or something else. OK, I can ignore the C++ embedded code, but it seems that Python can't. Python 2.3.2 (#2, Oct 6 2003, 08:02:06) [GCC 3.3.2 20030908 (Debian prerelease)] on linux2 >>> from colortool import MainForm Traceback (most recent call last): File "", line 1, in ? File "colortool.py", line 225 QSettings settings; ^ SyntaxError: invalid syntax I must be missing a switch or something. -- Dave From cbrown at metservice.com Wed Nov 26 15:35:32 2003 From: cbrown at metservice.com (Colin Brown) Date: Thu, 27 Nov 2003 09:35:32 +1300 Subject: try finally doesn't Message-ID: <3fc50d57@news.iconz.co.nz> When I run this code and then immediately do a Control-C, I do not get the 'thread' printed? Colin Brown PyNZ ----------------------------------------------------------- import thread, time def x(): try: time.sleep(60) finally: print 'thread' thread.start_new_thread(x,()) time.sleep(60) From alanmk at hotmail.com Thu Nov 13 12:32:06 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 13 Nov 2003 17:32:06 +0000 Subject: Palindrome References: <20031112223135.29045.00000109@mb-m12.aol.com> Message-ID: <3FB3C016.56BCA546@hotmail.com> [Ulrich Schramme] > there might be a million ways to solve the palindrome problem. I think > that another good way would be the use of regular expressions. The same occurred to me, so I had a go. This is as well as I was able to do in my lunchtime. #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= import re ignore = """ ",.'`!?-""" def isPalindrome(s): testphrase = re.sub("[%s]" % ignore, '', s) numtomatch = len(testphrase)/2 regx = "(\S)?" for x in range(numtomatch): regx = "(\S)%s(\%d)" % (regx, numtomatch-x) rxc = re.compile(regx, re.I) result = rxc.match(testphrase) return result is not None phrases = [ "Able was I, `ere I saw Elba", "A man, a plan, a canal, Panama", "Go Hang a Salami! I'm a Lasagna Hog!", "Sit on a Potato Pan, Otis", "Too Hot to Hoot", "If I Had a Hi-Fi", "So Many Dynamos", "Madam I'm Alan", "Santa, Oscillate My Metallic Sonatas", "Knob, testes set? Set. Bonk!", ] if __name__ == "__main__": print "Palindromes:" for phrase in phrases: if isPalindrome(phrase): print "Yes: '%s'" % phrase else: print "No : '%s'" % phrase #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= I'm not too happy with it though. There must be some way to have a single fixed regular expression that can be used to test every palindrome. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From 3seasA at Tthreeseas.DOT.not Mon Nov 10 17:10:23 2003 From: 3seasA at Tthreeseas.DOT.not (3seas) Date: Mon, 10 Nov 2003 22:10:23 GMT Subject: Matrix - Metaphors, Analogies and the REAL References: <3FAFF339.E499F960@engcorp.com> Message-ID: Scott Chapman wrote: > On Monday 10 November 2003 12:30, 3seas wrote: >> Its in python code >> >> http://threeseas.net/vic/vic/ >> >> -- >> 3 S.E.A.S -- Virtual Interaction Configuration (VIC) >> Changing how we preceive and use computers >> email @ translate not to net, remove capitol letters, one . >> web @ http://threeseas.net > > If it's a Python-related announcement, it should go on Python Announce. > > If it's a python issue, it should go here. > > If it's a Matrix issue, it should not go here. > > Your email was not a Python-related announcement. The blog entry it > points to was not Python-related. There was no Python-related content > in your email. I think that adds up to off-topic. This would have > probably gone mostly unnoticed except for your attitude. > > If everyone posted their latest advertisement for some pet web site that > happened to be written in python, we'd be flooded with CLEARLY > OFF-TOPIC posts regarding CLEARLY OFF-TOPIC subject matter. > > Post your pet web site posts where they are on-topic. > > Finally, if you _are_ going to post off-topic and you've gotten > "bitched" at in the past, please don't respond with a bad attitude post > like the one that started this thread. Do you really think such > attitudes will be of any value in furthering your ends in any way? Why > not learn from your mistakes? > > Post your pet web site posts in an appropriate manner. > > You don't owe the list any further details about the nature of the web > site. I think you owe the list an apology and a different pattern of > behavior in the future. > > You joined this list as an adult understanding that it exists with > certain criteria which you, being a member of the list, are supposed to > honor. Police yourself so that the list doesn't have to. We have work > to do. > > ' Hoping you get smarter as you get older, not just older. > > Scott and all of that is supposed to justify acts of spaming not just one but two of my email boxes.... in essence causing more unnecessary traffic to go thru the net.....? hmmmm How many mesages go thur this newsgroup and of that many, how many do you read, how many do you ignore? -- 3 S.E.A.S -- Virtual Interaction Configuration (VIC) Changing how we preceive and use computers email @ translate not to net, remove capitol letters, one . web @ http://threeseas.net From __peter__ at web.de Thu Nov 13 08:05:12 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Nov 2003 14:05:12 +0100 Subject: Try, except...retry? References: <7iptfxlywi.fsf@enark.csis.hku.hk> Message-ID: Isaac To wrote: > Hmmm... I agree only with reservation. The primary advantage of > exceptions, rather than other error reporting mechanisms like a return > value, is that you can group a lot of statements and have a single block > of > code handling all of those. This way you can separate the error handling > code and the normal code, to make the whole logic clearer. So if the > exception doesn't happen often enough to warrant the effort, I consider > the one at the begining, i.e., > > try: > x1 = could_raise_an_exception(1) > x2 = could_raise_an_exception(2) > x3 = could_raise_an_exception(3) > x4 = could_raise_an_exception(4) > process(x1) > process(x2) > process(x3) > process(x4) > except Exception, err: > deal_with_exception(err) > proceed_here() > > to be a better alternative than the corresponding code when all the > excepts are written out in else parts, just because it is easier to > understand. I would prefer: x1 = x2 = x3 = x4 = None try: x1 = acquireRessource(1) x2 = acquireRessource(2) x3 = acquireRessource(3) x4 = acquireRessource(4) process(x1, x2, x3, x4) finally: if x1: releaseRessource(x1) if x2: releaseRessource(x2) if x3: releaseRessource(x3) if x4: releaseRessource(x4) where acquireRessource() should try hard to deal with potential exceptions and only pass the fatal ones to the caller. Exceptions occuring when processing the ressource should be dealt with in process() if possible. As for process() working orthoganally on xi, that does not make any sense to me. In such cases, be generous and provide a try ... finally and/or except for every ressource. Now back to else: try: x = canRaise() cannotRaise(x) except Exception, e: dealWithException(e) You must be very confident in your code to assume that cannotRaise() will never raise an exception that dealWithException() will then accidentally handle. So after a short phase of accommodation, try: x = canRaise() except Exception, e: dealWithException(e) else: cannotRaise(x) # may still be lying is both more readable and better code (neglecting for the moment the redundancy that many python coders will find in these attributes :-) Peter From pythonguy at Hotpop.com Fri Nov 21 03:00:21 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 21 Nov 2003 00:00:21 -0800 Subject: file bug??? References: <3FBD8C08.9010002@hotmail.com> Message-ID: <84fc4588.0311210000.5b925947@posting.google.com> There are many problems with your code. First of all answer to your main question. In Line 15, you are using a local variable named 'file' which is being used to walk a list of files. When you are using a keyword as a variable, python gets confused and thinks that you are trying to use a variable before it is being defined. If you replace the 'file' in L15 with say 'f', you can use 'file' instead of 'open' in L4. Some other things. o 'os' module does not have a function 'walk'. Change it to os.path.walk . o os.path.walk takes 3 arguments, not one. You need to correct this. -Anand hokiegal99 wrote in message news:<3FBD8C08.9010002 at hotmail.com>... > When I use 'file' instead of 'open' on the 4th line of this script (the > line that begins with "outputFile") I get this error: > "UnboundLocalError: local variable 'file' referenced before assignment" > 'open' works w/o problem and 'file' works in some other scripts that are > almost identical to this one... any ideas? I can post a script where > 'file' works if anyone is interested. > > import os, string > setpath = raw_input("Enter the path to the Mac files and folders: ") > def clean_spaces(setpath): > outputFile = open('fix-spaces.txt', 'w') > for root, dirs, files in os.walk(setpath): > for dir in dirs: > old_dname = dir > new_dname = old_dname.strip() > if new_dname != old_dname: > newpath = os.path.join(root,new_dname) > oldpath = os.path.join(root,old_dname) > print >> outputFile, "Replaced ", old_dname, "\nWith > ", new_dname > os.rename(oldpath,newpath) > for file in files: > old_fname = file > new_fname = old_fname.strip() > if new_fname != old_fname: > newpath = os.path.join(root,new_fname) > oldpath = os.path.join(root,old_fname) > print >> outputFile, "Replaced ", old_fname, "\nWith > ", new_fname > os.rename(oldpath,newpath) > outputFile.close() > clean_spaces(setpath) From jkrepsBEAR at FISHneb.rr.com Sat Nov 1 14:09:42 2003 From: jkrepsBEAR at FISHneb.rr.com (GrayGeek) Date: Sat, 01 Nov 2003 19:09:42 GMT Subject: My first Python program.. Calculating pi geometrically. References: <3fa39a91$0$58703$e4fe514c@news.xs4all.nl> Message-ID: Ron Adam wrote: > On Sat, 01 Nov 2003 12:35:45 +0100, Irmen de Jong > wrote: > >>Ron Adam wrote: >> >>> Doing it geometrically was strictly a learning exercise. And I did >>> learn quite a bit by doing it. >> >>And you only scratched the surface of what Python offers you :-) >>While it's nice to hear that you learned a lot by making this >>arithmetic python program, it certainly is not the most >>inspiring thing that Python is capable of... >> >>I even think you learned more about calculating Pi than you >>did about programming in Python ;-) >> >>--Irmen > > The challenging parts were, figuring out how to do the calculation > without using sin or cos, (nice geometry refresher), getting the gmpy > module to work and how to set the precision, and working out by trial > and error the precision calculation. If there is a formula to > convert digits of precision to bits of precision, I'd like to know. > And the last was to figure out how to use the clock and timedelta > functions. > > Other interesting things I learned was how to convert to and from > stings, use slices, and for-in loops are very fast for small lists, > but can eat up a lot of memory, hit the swap file and be extremely > slow for large lists. For-in loops aren't suited for everything. > > And yes, before I started, I did not know how to calculate pi. So you > are right about that. ;-) That was an interesting subject in it > self. > > Overall, it was a very good learning project. > > _Ron As I recall, Ron, your method is the same one used by Archimedes when he computed PI. http://itech.fgcu.edu/faculty/clindsey/mhf4404/archimedes/archimedes.html The method of diminishing triangles is SO similar to Gauss & Newton's method of diminishing rectangles one wonders how much faster the scientific advances of Man would have occurred if Archimedes had gone on to develop Calculus. -- - GrayGeek From amk at amk.ca Tue Nov 18 09:35:40 2003 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 18 Nov 2003 08:35:40 -0600 Subject: ok... References: Message-ID: On Tue, 18 Nov 2003 16:02:28 +0200, user at domain.invalid wrote: > to users as part of a self test. What I am looking for is to specify a > date and time to run the self tests without interfering with anything > else i.e. the rest of the logic is not affected. Is this possible? > > P.S. Cron can probably do the job, but I am trying to stick to python. Why impose that last constraint? It seems much more difficult to write and debug Python code for cron-like features than to just use cron. Would your Python code run as a daemon and wait around until it's time to do something? Then what if it crashes? You'd better implement logging of errors so that you find out about any problems. What if the system gets rebooted? You'd better write an /etc/init.d script to start your daemon. It seems much easier to run 'crontab -e' and type in the following: # Run the test every morning at 1AM 0 1 * * * /home/amk/test.py --amk From johnk at aurema.commercial Tue Nov 25 21:28:10 2003 From: johnk at aurema.commercial (John Ky) Date: Wed, 26 Nov 2003 13:28:10 +1100 Subject: Compiling 64 bit python - using wrong stdlibc++ References: <1069813229.180239@cousin.sw.oz.au> Message-ID: <1069813707.78669@cousin.sw.oz.au> > And it compiles, but fails to link with /usr/local/lib/stdlibc++.so.5 > because it is the 32-bit version. The exact error message is: ld.so.1: ./python: fatal: /usr/local/lib//libstdc++.so.5: wrong ELF class: ELFCLASS32 Thanks -John From martin at v.loewis.de Mon Nov 17 05:12:28 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 17 Nov 2003 11:12:28 +0100 Subject: IDLE and non-ascii encoding workaround? References: Message-ID: klappnase at web.de (klappnase) writes: > Any hints on this would be very appreciated. I recommend to use the IDLE that comes with Python 2.3. Regards, Martin From python473 at yahoo.com Wed Nov 19 20:57:13 2003 From: python473 at yahoo.com (John Howard) Date: 19 Nov 2003 17:57:13 -0800 Subject: python a bust? References: <9eabe547.0311131610.4dd7819c@posting.google.com> <38ec68a6.0311132310.630e10e2@posting.google.com> <84fc4588.0311140319.3778de15@posting.google.com> Message-ID: <9eabe547.0311191757.2cc51af3@posting.google.com> Let's say some one walked into a book store and glanced at the books in computers. He might think, "gee look at all the books on java and perl and hardly any books on python. What is python? And it's not even in the languages section. No sense in looking at that!" It's a matter of perception. "Lots of perl and java - that's the way to go." I also agree that maybe a lot of books on python are not necessary to learn the langage. Heck, I learned almost all I know (which I admit is not much) from web tutorials and samples. But I do have questions I cannot find the answers to when I browse the book store. Eg, how do I do admin stuff with python? How do I do cgi stuff with python? There are books on how to do these in perl. Dozens. pythonguy at Hotpop.com (Anand Pillai) wrote in message news:<84fc4588.0311140319.3778de15 at posting.google.com>... > In the ideal "techie makes decisions" world this would have > been a good thing. But not in the real world where the Suits > make decisions in corporates. > > There might have been thousands of books published in C/C++ > language and they have all helped to popularize it in one > or the other way. Contrast, in the python world we have one > Alex Martelli, one Wesley Chun, one David Mertz, really > countable by hand. > > There is a limit to how much a single person can evangelize > a language. Questions similar to what the O.P posted arise > from the listeners. > > I would prefer to see more books on Python though they all might > be useless from a pure techie point of view. Let us have > a book on Software Projects in python for example. It might not > have the technical superiority of a Martelli book, but more > attempts like that will save the language and help the > eyeball factor, which is so important in practical marketing. > > -Anand > > afriere at yahoo.co.uk (Asun Friere) wrote in message news:<38ec68a6.0311132310.630e10e2 at posting.google.com>... > > python473 at yahoo.com (John Howard) wrote in message news:<9eabe547.0311131610.4dd7819c at posting.google.com>... > > > I've sent several messages over the last year asking about python - > > > Who teaches python? Is python losing steam? etc. I have noticed, eg, > > > the declinng number of books at my local borders. The last time I > > > visited a borders (last week), there was 1 (sic) book about python on > > > the shelve compared to dozens on perl & java! > > > > > > If you were developing in Java or Perl maybe you would need dozens of > > books. But Python is so elegant and intuitive a single one will do. > > ;) From email9898989 at yahoo.com Thu Nov 20 11:01:50 2003 From: email9898989 at yahoo.com (email9898989 at yahoo.com) Date: 20 Nov 2003 08:01:50 -0800 Subject: PyQt, Qt, Windows and Linux References: Message-ID: Jarek Zgoda wrote in message news:... > Don't spread FUD. You don't have to pay for Qt if you distribute it > under GNU Public License. Even commercially. You can earn money for your > software and you have nothing to pay to Trolltech if this is GPL-ed > software. They can say anything, but it's GPL, they just can not impose > such restriction. That is incorrect. You DO have to play them if you want your app to run _on any platform_ (i.e., Linux AND Windows), regardless if it is GPL licensed, free, commercial, or whatever. From aleax at aleax.it Mon Nov 3 07:57:15 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 03 Nov 2003 12:57:15 GMT Subject: Testing validity of for...in... References: Message-ID: Richard Philips wrote: > From the "The Pragmatic Programmer / Dave Thomas, Andy Hunt", > I acquired the habit to insert assertions in function declarations: Actually, I doubt Thomas & Hunt do "type assertions" when they program in their favourite language, Ruby (whose dynamic but strong typing is quite similar to Python's). > def maxlength(mylist): > assert isinstance(mylist, list), "A list with strings" But as you notice, this will refuse arguments that would work perfectly well, e.g. a _tuple_ of strings, and not trigger for arguments whose type is not ok, e.g. a list one of whose item is for example an int. So what use is it...?! > max = -1 > for item in list: Hopefully you mean "in mylist". > if len(item)>max: > max = len(item) > return max ...and the whole function is best coded as: return max([ len(item) for item in mylist ]) > But if you look at the code, maxlength is meaningful if mylist supports > the "for ... in ...". ...AND each item supports len(). Yep, very different from what the assertion expresses. > Is there an easy way to test if "mylist" supports "for ... in ..." ? Sure: just omit the assertion and get to the "for item in mylist:" statement -- IT will raise (a more precise TypeError rather than a vaguer AssertionError) if mylist is not iterable. Similarly, when you try doing len(item) on each item, it will raise a TypeError if the item does not support having len() called on it. Generally, in languages with strong but dynamic typing, assertions on types aren't a great way to proceed. Most of the time you can just go ahead and rely on the language raising exceptions for you as appropriate if the types are not compatible with your code. In some rare cases you may want to do earlier checks/diagnostics, in which case the idioms I suggest in a Cookbook recipe may help -- see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52291 for more (it's better developed in the printed version of the Cookbook published by O'Reilly). Alex From logan at phreaker.nospam Mon Nov 24 19:09:09 2003 From: logan at phreaker.nospam (Logan) Date: Tue, 25 Nov 2003 01:09:09 +0100 Subject: 'from __future__ import ...' overview Message-ID: Is there a list with all 'from __future__ import ...' statements (which lists all the statements, in which version of Python the feature was introduced and in which version of Python it will become the default behavior)? I guess, normally such a list is not necessary because a new feature needs its 'from __future__ import ...' statement only in the present version of Python and will become default in the next version. But e.g. 'from __future__ import division' is said to not become default before Python 3.0. Usually, I use A.M. Kuchling's "What's new in Python 2.x" articles for that kind of stuff; but I thought, such a might exist somewhere as a short reference. Any links? -- mailto: logan at phreaker(NoSpam).net From radam2 at tampabay.rr.com Mon Nov 3 19:03:31 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Tue, 04 Nov 2003 00:03:31 GMT Subject: nearest neighbor in 2D References: Message-ID: On Sun, 02 Nov 2003 22:12:47 -0600, John Hunter wrote: > >I have a list of two tuples containing x and y coord > > (x0, y0) > (x1, y1) > ... > (xn, yn) > >Given a new point x,y, I would like to find the point in the list >closest to x,y. I have to do this a lot, in an inner loop, and then I >add each new point x,y to the list. I know the range of x and y in >advance. > >One solution that comes to mind is to partition to space into >quadrants and store the elements by quadrant. When a new element >comes in, identify it's quadrant and only search the appropriate >quadrant for nearest neighbor. This could be done recursively, a 2D >binary search of sorts.... > >Can anyone point me to some code or module that provides the >appropriate data structures and algorithms to handle this task >efficiently? The size of the list will likely be in the range of >10-1000 elements. > >Thanks, >John Hunter > This is how I would do it. Maybe it's how you are already doing it? import math import random n_points = 1000 max_x = 1000 max_y = 1000 closest_distance = 10000 closest_point = (max_x,max_y) p = [] for i in xrange(n_points): x = round(max_x*random.random()) y = round(max_y*random.random()) p.append((x, y)) new_point = (round(max_x*random.random()), \ round(max_y*random.random())) for point in p: distance = math.sqrt((new_point[0]-point[0])**2 \ +(new_point[1]-point[1])**2) if distance < closest_distance: closest_distance = distance closest_point = point print 'new_point:', new_point print 'closest_point:', closest_point,' \ out of',n_points,'points.' I really don't know how you can make this faster. There might be a library that has a distance between two points function that could speed it up. Ronald R. Adam radam2 at tampabay.rr.com From radam2 at tampabay.rr.com Sat Nov 1 16:09:26 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Sat, 01 Nov 2003 21:09:26 GMT Subject: My first Python program.. Calculating pi geometrically. References: <3fa39a91$0$58703$e4fe514c@news.xs4all.nl> Message-ID: <4f58qvcf685f8ldrjs9lo4hti47pgfesl6@4ax.com> On Sat, 01 Nov 2003 19:09:42 GMT, GrayGeek wrote: >Ron Adam wrote: > >> On Sat, 01 Nov 2003 12:35:45 +0100, Irmen de Jong >> wrote: >> >>>Ron Adam wrote: >>> >>>> Doing it geometrically was strictly a learning exercise. And I did >>>> learn quite a bit by doing it. >>> >>>And you only scratched the surface of what Python offers you :-) >>>While it's nice to hear that you learned a lot by making this >>>arithmetic python program, it certainly is not the most >>>inspiring thing that Python is capable of... >>> >>>I even think you learned more about calculating Pi than you >>>did about programming in Python ;-) >>> >>>--Irmen >> >> The challenging parts were, figuring out how to do the calculation >> without using sin or cos, (nice geometry refresher), getting the gmpy >> module to work and how to set the precision, and working out by trial >> and error the precision calculation. If there is a formula to >> convert digits of precision to bits of precision, I'd like to know. >> And the last was to figure out how to use the clock and timedelta >> functions. >> >> Other interesting things I learned was how to convert to and from >> stings, use slices, and for-in loops are very fast for small lists, >> but can eat up a lot of memory, hit the swap file and be extremely >> slow for large lists. For-in loops aren't suited for everything. >> >> And yes, before I started, I did not know how to calculate pi. So you >> are right about that. ;-) That was an interesting subject in it >> self. >> >> Overall, it was a very good learning project. >> >> _Ron > >As I recall, Ron, your method is the same one used by Archimedes when he >computed PI. >http://itech.fgcu.edu/faculty/clindsey/mhf4404/archimedes/archimedes.html > The method of diminishing triangles is SO similar to Gauss & Newton's >method of diminishing rectangles one wonders how much faster the scientific >advances of Man would have occurred if Archimedes had gone on to develop >Calculus. Yes, the concept is the same, but slightly different method. All the examples I found used trig functions to do it with or used ratios related to trig functions. I used vectors to get around that. How much did calculus contributed to advances in mankind after it was developed? I think other developments in production methods and economics had a bigger impact and didn't require calculus. Correction, a quick search found this.... http://www-gap.dcs.st-and.ac.uk/~history/HistTopics/The_rise_of_calculus.html This shows calculus was developed over quite a long time in conjunction with, and driven by developments in production, which in turn were related to economics. But 2,500 years is a long time ago and who knows what would have happened? What would have happened if the telescope was invented sooner? :-) Something interesting about gmpy accuracy is after calculating pi to 10,000 digits and displaying the entire floating point number, only the last 4 digits are off due to rounding errors. I think that is exceptional and only occasionally are the last 5 digits not correct. I get around that by calculating at least 5 extra digits and then truncating. _Ron From jdhunter at ace.bsd.uchicago.edu Sun Nov 2 23:12:47 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 02 Nov 2003 22:12:47 -0600 Subject: nearest neighbor in 2D Message-ID: I have a list of two tuples containing x and y coord (x0, y0) (x1, y1) ... (xn, yn) Given a new point x,y, I would like to find the point in the list closest to x,y. I have to do this a lot, in an inner loop, and then I add each new point x,y to the list. I know the range of x and y in advance. One solution that comes to mind is to partition to space into quadrants and store the elements by quadrant. When a new element comes in, identify it's quadrant and only search the appropriate quadrant for nearest neighbor. This could be done recursively, a 2D binary search of sorts.... Can anyone point me to some code or module that provides the appropriate data structures and algorithms to handle this task efficiently? The size of the list will likely be in the range of 10-1000 elements. Thanks, John Hunter From fpetermaas at netscape.net Wed Nov 5 04:44:00 2003 From: fpetermaas at netscape.net (Peter Maas) Date: Wed, 05 Nov 2003 10:44:00 +0100 Subject: Python slow for filter scripts In-Reply-To: <9769adc8.0310281233.5fc5d252@posting.google.com> References: <9769adc8.0310281233.5fc5d252@posting.google.com> Message-ID: Peter Mutsaers schrieb: > I found that on my (linux) PC, the Python version was 4 times slower. > > Is that normal, does it disqualify Python for simple filter scripts? Have a look at the win32 language shootout (http://dada.perl.it/shootout/) with lots of benchmarks for lots of languages, among them python, cygperl (perl with cygwin calls, I assume) and perl (perl with native win32 calls). cygwin is usually faster than python, perl slower. You can also look at Doug Bagley's Linux based shootout but it's older (Perl 5.6, Python 2.1) and currently not maintained. My impression is that on an average perl is faster than python but not by an order of magnitude but by ~ 20%. Your test is probably closest to the "reverse file" benchmark where cygperl : python : perl = 0.68 : 1.68 : 12.72 on win32 and perl : python = 1.06 : 1.17 on Linux. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From aahz at pythoncraft.com Sun Nov 23 14:18:05 2003 From: aahz at pythoncraft.com (Aahz) Date: 23 Nov 2003 14:18:05 -0500 Subject: Help with script with performance problems References: Message-ID: In article , Dennis Roberts wrote: > >I have a script to parse a dns querylog and generate some statistics. >For a 750MB file a perl script using the same methods (splits) can >parse the file in 3 minutes. My python script takes 25 minutes. It >is enough of a difference that unless I can figure out what I did >wrong or a better way of doing it I might not be able to use python >(since most of what I do is parsing various logs). The main reason to >try python is I had to look at some early scripts I wrote in perl and >had no idea what the hell I was thinking or what the script even did! >After some googling and reading Eric Raymonds essay on python I jumped >in:) Here is my script. I am looking for constructive comments - >please don't bash my newbie code. If you haven't yet, make sure you upgrade to Python 2.3; there are a lot of speed enhancements. Also, it allows you to switch to idioms that work more like Perl's: for line in f: fields = line.split() ... Generally speaking, contrary to what another poster suggested, string methods will almost always be faster than regexes (assuming that a string method does what you want directly, of course; using multiple string methods may or may not be faster than regexes). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From jjl at pobox.com Sat Nov 8 07:11:37 2003 From: jjl at pobox.com (John J. Lee) Date: 08 Nov 2003 12:11:37 +0000 Subject: ANN: PyKDE now does KDE plugins References: <87sml01hgc.fsf@pobox.com> Message-ID: <87llqrgiva.fsf@pobox.com> Jim Bublitz writes: [...] > The same scheme will work for almost any plugin - the major > difference is that in some cases the plugin loader doesn't > provide enough info to allow a proxy for the .so file (for > example, to load "somePlugin" the loader might expect > libsomePlugin with an init_somePlugin factory function in C++). [...] Sounds like some gentle persuasion could be beneficial here! [from end of Jim's post] > On the other hand, there's really no reason why a proxy wouldn't > *always* work if C++ developers allowed for it - always call a > factory function with the same name ("init", "create". whatever) > and pass in an identifying string for locating the plugin. > Probably makes C++ plugins a little harder to write though. Not if a (C++) interface is *added*, not replaced. The KDE plugin loader could check for init_blah first, and if that's not there, check for plain old init. > I had a similar KSpread (KOffice spreadsheet) plugin working > using a cruder version of the same basic idea. Apps require a > Python wrapper for their API to be useful, but that's also > pretty simple to write using sip (for a well-written app > anyway). [...] Well, it might be if there were any sip documentation :-) I had some success using sip before, but it was hard work. I noticed that Phil promised docs for PyQt/sip 4, though! John From Google_Post at slink-software.com Wed Nov 12 00:29:54 2003 From: Google_Post at slink-software.com (K_Lee) Date: 11 Nov 2003 21:29:54 -0800 Subject: Regular expression code implementation review between Tcl vs Python References: <394af34.0311110758.3b1781ea@posting.google.com> <3fdsb.10497$hV.431113@news2.tin.it> Message-ID: <394af34.0311112129.6b773d56@posting.google.com> Alex Martelli wrote in message news:<3fdsb.10497$hV.431113 at news2.tin.it>... > K_Lee wrote: > ... > > One aspect I don't understanding about python is that the Python > > language itself is object oriented and all the internal is implement > > as C object. Why not C++ object? > > Using an OO language doesn't necessarily make implementing another > OO language any easier, when the object models are mismatched (and > they almost invariably are). Look at other opensource OO languages, > such as Ruby, and you'll see they also use C, not C++. > > Actually, a small and carefully selected subset of C++ might surely help, > _if_ there was consensus on what that subset should be and net of > the work of hashing that consensus out. But C++ just isn't very much > in the opensource culture -- C is just much more popular. Eric Raymond's > book "The Art of Unix Programming" doesn't address the issue directly but > much of what it says about "Unix culture" extends directly to opensource > (as he notes, too). There are such values as an admiration for simplicity > (cfr. C's principle, as per the Rationale of the C Standard, "provide only > one way to perform an operation", and Python's corresponding "there ought > to be one, and preferably only one, obvious way to do it") which militate in > favour of C (which may not have reached simplicity everywhere but surely > did and does always strive for it) and against C++ (which never gave > language-simplicity a high priority level among its many design goals); even > in subcultures that overtly reject such principles (e.g., Perl's) they may > still have some subconscious-level effect. > > I used to bemoan this back when I was a C++ not-quite-but-close-guru. > 3 years later, with little use of C++ in the meantime, I have forgotten more > about C++ than most of it practitioners will ever learn... but C is just > never forgotten, like how to swim or how to ride a bicycle. So, I am not > any longer so sure if my "bemoaning" was warranted. > > > Alex Alex, It is sad but true. One c++ project (was commercial, now open source) I found that is very interesting to read/browse is the chorus. It is micro-kernel os where everything is a class/object including threads, pagetable, scheduler. Very interesting. Unfortunately, it seems to be dying when compare to BSD, Linux. http://www.slink-software.com/W/SrcDoc_Top/chorus_c5/chorus_c5.sdoc/N_59 What's nice about python's internal is that it is very clean and well structure with object orient mind set. K Lee From FrogRemailer at bigfoot.com Tue Nov 18 15:35:03 2003 From: FrogRemailer at bigfoot.com (Frog) Date: 18 Nov 2003 21:35:03 +0100 Subject: using Python to run other programs Message-ID: <7T02VNBM37943.8988541667@Gilgamesh-frog.org> Hi, i'm not a programmer so I have a very stupid question. I'm trying to make a practical script. I need to run an executable program in it but i can't get it to work. Maybe someone here can figure it out easily: ----- #! /python a = (recipient's e-mail address) pgp -feat a (sendmail to address after encryption) ------ How do I get python to open the pgp program? Should I use an environment other than python? thanks! From zhoney at wildmail.com Mon Nov 3 16:18:11 2003 From: zhoney at wildmail.com (Zora Honey) Date: Mon, 03 Nov 2003 15:18:11 -0600 Subject: setup.py for c++ Message-ID: <3FA6C613.5010302@wildmail.com> I'm taking baby steps toward extending python with c++. I got the demo from "Extending and Embedding the Python Interpreter" running. My next step was to modify the demo to output stuff using . This fails, and this seems to be because my setup.py file is using a c compiler (gcc) instead of a c++ compiler. I've searched the web and found several solutions, none of which I've been able to implement correctly. I seem to be only inches away but always missing a critical piece of information, and I was wondering if the gurus here could help. My attempts: 1.) From Pythonmac-SIG: "The problem is that the link step is done with "gcc", not "g++", so you have to add the C++ library by hand. The easiest is to add an extra_link_libraries (iirc) flag to the setup.py file." Where in the setup.py file? Is this simply a flag or does it need arguments? 2.) From "Extending and Embedding the Python Interpreter": "For example, if you need to link against libraries known to be in the standard library search path on target systems Extension(..., libraries=["gdbm", "readline"])" This does seem to work, but I don't know if it's the same as 1) or which libraries I need to include. 3.) From "Installing Python Modules": "Arbitrary switches intended for the compiler or the linker can be supplied with the -Xcompiler arg and -Xlinker arg options: foo foomodule.c -Xcompiler" I'm using the syntax: odule1 = Extension(modulename , sources = sourcecode, ) in my setup.py file, and don't know where to put this compiler option. 4.) From ?: Use compiler option: python setup.py build --compiler=g++ I get an error message that ends in: distutils.errors.DistutilsPlatformError: don't know how to compile C/C++ code on platform 'posix' with 'g++' compiler Which sounds like distutils doesn't like my compiler (or somehow I need to set the platform--I'm on RedHat 7.1). Thanks for any ideas, Zora From a.rottmann at gmx.at Wed Nov 12 18:00:03 2003 From: a.rottmann at gmx.at (Andreas Rottmann) Date: Wed, 12 Nov 2003 23:00:03 GMT Subject: LAID (was: python libs v lisp coolness? References: Message-ID: <87he19uruh.fsf@alice.rotty.yi.org> mike420 at ziplip.com writes: [ sorry for cross-posting, but I really think this is relevant on all newsgroups posted ] > Joe Marshall wrote > in : > >> Kenny Tilton writes: >> >>> I don't know. Maybe I'm wrong. If Lisp is such a great language and >>> people love it so much, how come they don't write any code? >> [...] > Lispers need to cooperate with others on libraries. Maybe a Consortium of > Underdog Dynamically-Typed Languages needs to be started. Underdog > languages are more interested in libraries and cooperation. > > For each library, a language-agnostic interface description (in > LAID language, of course) should be generated by porters, so that > later FFIs could be produced for each language automatically. This > is the opposite (and complementary to) SWIG: SWIG auto-generates dumb > interface information and needs a lot of human post-work for each > specific language. > > "Are you guys having trouble with that GTK lib? - No, we got LAID!" > *g* Actually, h2def.py does something like produce LAID (called defs there). You basically scan the headers and adapt the resulting defs (which are, bu coinicence, lisp/scheme data). It's used by the guile-gobject GTK+2 bindings and the puthon GTK+2 bindings. We just need some infrastructure/framework for cooperating on improving this stuff and documenting the defs data format. Regards, Andy -- Andreas Rottmann | Rotty at ICQ | 118634484 at ICQ | a.rottmann at gmx.at http://www.8ung.at/rotty | GnuPG Key: http://www.8ung.at/rotty/gpg.asc Fingerprint | DFB4 4EB4 78A4 5EEE 6219 F228 F92F CFC5 01FD 5B62 From radam2 at tampabay.rr.com Sat Nov 1 14:32:39 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Sat, 01 Nov 2003 19:32:39 GMT Subject: prePEP: Decimal data type References: Message-ID: On Fri, 31 Oct 2003 15:36:38 -0300, "Batista, Facundo" wrote: [clip] > >The Decimal data type should support the Python standard functions and >operations and must comply the decimal arithmetic ANSI standard X3.274-1996. Is this the correct ANSI number? I ended up at the following websight. http://www.rexxla.org/Standards/standards.html _Ronald R. Adam From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Nov 24 07:27:19 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 24 Nov 2003 13:27:19 +0100 Subject: Dyna grid In-Reply-To: References: <17910121023.20031124112023@peto.hu> Message-ID: <3fc1f927$0$1493$e4fe514c@news.xs4all.nl> Peter Otten wrote: > cjOr proWe vbCould vbSettle prpFor noEnglish prpIn adjHungarian noNotation > :-) > > noPeter ROFL! Thanks, Peter, for the laugh of the day :-) noIrmen From anthony at interlink.com.au Thu Nov 13 00:07:18 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Thu, 13 Nov 2003 16:07:18 +1100 Subject: looking for a name for a python SIP phone In-Reply-To: References: Message-ID: <200311130507.hAD57IWV031624@localhost.localdomain> >>> Aahz wrote > All right, did anyone else translate "SIP" as "Strangers in Paradise"? Nope. Is Strangers in Paradise a Proposed Standard RFC? Anthony From jeder at earthlink.net Tue Nov 25 18:54:02 2003 From: jeder at earthlink.net (Ryan Spencer) Date: Tue, 25 Nov 2003 23:54:02 GMT Subject: sleep() function, perhaps. References: <7illq4zw89.fsf@enark.csis.hku.hk> Message-ID: On Tue, 25 Nov 2003 16:30:14 +0800, Isaac To wrote: > > Without a newline character, the normal sys.stdout writes to a buffer > and won't try to flush it out. Try this: > >>>> for i in range(10): > ... sys.stdout.write('.') > ... sys.stdout.flush() > ... time.sleep(.5) > ... > ..........>>> > > Regards, > Isaac. Hey! Wow! Thanks for all the advice guys. To admit, I'm rather new to python, but I am understanding thus far and working through all the great advice you've all given. The spinner is actually very cool, I must say. Also, I thank you Skip for your progress module, I'll play around with that in a bit for actually working in coherence with the programs actual progress. But flushing stdout's buffer does the trick, Which I'm really jazzed to see. I'm still am heading back through all the other stuff that everyone else has mentioned though, just to improve my knowledge of course. I must say though, I previously posted this question on an on line message board and received no feedback in a matter of weeks, and two days on this newsgroup and BAM! Haha Well, Thanks again guys, I'm sure I'll be back with other questions later ;) ~Ryan From http Fri Nov 21 12:13:37 2003 From: http (Paul Rubin) Date: 21 Nov 2003 09:13:37 -0800 Subject: Using an interable in place of *args? References: Message-ID: <7xn0apzltq.fsf@ruckus.brouhaha.com> Can you give an example of what you're trying to do? Your description and code are way too confusing. But it sounds to me like your best bet may be to use the array module and build up your string a field at a time. From ip at itk.ntnu.no Wed Nov 12 05:01:01 2003 From: ip at itk.ntnu.no (Idar) Date: Wed, 12 Nov 2003 11:01:01 +0100 Subject: Conversion of 24bit binary to int References: Message-ID: On Tue, 11 Nov 2003 10:21:29 -0500, Mike C. Fletcher wrote: > If I'm understanding correctly, hex has nothing to do with this and the > data is really binary, so what you're looking for is probably: Thanks for the hint!! and sorry - i ment binary! > > >>> data = '\000\001\002' > >>> temp = struct.unpack( '>I', '\000'+data ) # pad to 4-byte unsigned > big-endian integer format > >>> print temp # is now a regular python integer (in a tuple) > (258L,) > >>> print repr(struct.pack( ' little-endian integer format > '\x02\x01\x00\x00' > > There are faster ways if you have a lot of such data (e.g. PIL would > likely have something to manipulate RGB to RGBA images), similarly, you > could use Numpy to add large numbers of rows simultaneously (all 512 if I > understand your description of the data correctly). Without knowing what > type of data is being loaded it's hard to give a better recommendation. It is binary with no formating characters to indicate start/end of each block (fixed size). A file is about 6MB (and about 300 of them again...), Ch1: 1536B (512*3B) - the 3B are big endian (int) .. Ch6: 1536B (512*3B) And then it is repeated till the end: Ch1: 1536B (512*3B) .. Ch6: 1536B (512*3B) ciao, idar > > HTH, > Mike > > > Idar wrote: > >> Is there an effecient/fast way in python to convert binary data from >> file (24bit hex(int) big endian) to 32bit int (little endian)? Have seen >> struct.unpack, but I am unsure how and what Python has to offer. Idar > > ... _______________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://members.rogers.com/mcfletch/ > > > > > -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From cliechti at gmx.net Sun Nov 2 05:03:10 2003 From: cliechti at gmx.net (Chris Liechti) Date: 2 Nov 2003 12:03:10 +0200 Subject: py2exe question References: <3FA36D0A.45BCA44B@easystreet.com> <6FKob.391474$R32.12987108@news2.tin.it> <3FA3EE35.F382B493@easystreet.com> <3FA46952.60B2836D@easystreet.com> Message-ID: achrist at easystreet.com wrote in news:3FA46952.60B2836D at easystreet.com: > Thomas Heller wrote: >> >> py2exe up to version 0.4.2 has not be adapted to this change, but the >> 0.5.0 alpha version (available in the files section of >> http://sf.net/projects/py2exe) is able to handle this. >> > Looks like 0.5.0a is not picking up any of my command line arguments > or producing any executable when I run it through the same batch > file that worked for 0.4.2. > > Any docs on how to make if work? there is an example in the lib/site-packages/py2exe/samples dir the syntax of the setup call is different chris -- Chris From bignose-hates-spam at and-benfinney-does-too.id.au Tue Nov 11 22:04:29 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 12 Nov 2003 13:54:29 +1050 Subject: Text looking weird References: Message-ID: On Wed, 12 Nov 2003 02:56:43 GMT, Jakle wrote: > WOW, that came out weird, but if you copy/paste it into idle it looks > fine. It looks fine in any newsreader and editor that uses a fixed-pitch font. This is highly recommended, since you know that the spacing of the text you type will be the same for any other fixed-pitch font (as used by other people). This can't be said of any proportional font. -- \ "Marriage is a wonderful institution, but who would want to | `\ live in an institution." -- Henry L. Mencken | _o__) | Ben Finney From newsgroups at jhrothjr.com Fri Nov 7 07:42:50 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 7 Nov 2003 07:42:50 -0500 Subject: How to use a .pyd References: Message-ID: "Liu Kun, SLC ICM (BJ)" wrote in message news:mailman.519.1068205668.702.python-list at python.org... > Hello, > > I want to use a method from _xxx_yyy.pyd, but I can not use import to load this file, how to use .pyd in python interpreter? What happens when you try to use import? Please tell us the exact statement you used, and the error traceback. John Roth > > Best Regards > Liu Kun > From ConfuseYourSpamBot-parzp at ConfuseYourSpamBot.shaw.ca Mon Nov 10 03:22:07 2003 From: ConfuseYourSpamBot-parzp at ConfuseYourSpamBot.shaw.ca (Parzival) Date: Mon, 10 Nov 2003 08:22:07 GMT Subject: What does "#!/usr/bin/env python" do? References: <_eGrb.358699$9l5.109956@pd7tw2no> Message-ID: nospam wrote: > Since env is (almost?) always in /usr/bin, while python can be installed > God-knows-where, that is more portable than writing #!/local/bin/python > or #!/usr/bin/python or whatever. That clarifies that! Thanks. Followup question: I am using Mandrake 9.1, and it installs Python 2.2. I have installed Python 2.3. Somewhere I read that Mandrake NEEDS Python 2.2 to work, I cannot just remove it, nor can I replace it with 2.3, as this might be incomptible with some Mandrake Python script requirements. It further tuns out that I have no control over the placement of entries in PATH, so that my .bash_profile login script which adds /usr/local/bin to the PATH, wherein are "python", "python2.3" and "idle", does not have precedence over the Mandrake installed /usr/bin, wherein are "python" and "idle". The result is that I must type "python2.3 myscript.py" or "/usr/local/bin/idle myscript.py", and the just explained "#!/usr/bin/env python" at the start of scripts always resolves in favour of the Mandrake installed Python, not my own current version. I would like my personal installation of Python to be the default and convenient version, i.e. "./Myscript.py" "python MyScript.py" and "idle" should resolve that instead of the system version. Is there a good way to accomplish this? -- (-: Stop, smile, and enjoy your breathing :-) -- Parzival -- Reply-to is confuggled: parzp (@) shaw (.) ca From cbrown at metservice.com Thu Nov 13 15:04:38 2003 From: cbrown at metservice.com (Colin Brown) Date: Fri, 14 Nov 2003 09:04:38 +1300 Subject: socket's strange behavior with subprocesses References: <3fb28c56$1@news.iconz.co.nz> Message-ID: <3fb3e2cf$1@news.iconz.co.nz> "Jane Austine" wrote in message news:ba1e306f.0311121646.70779793 at posting.google.com... > "Colin Brown" wrote in message news:<3fb28c56$1 at news.iconz.co.nz>... > > "Jane Austine" wrote in message > > news:ba1e306f.0311120837.6e6eddf2 at posting.google.com... ... > I tried win32 API primitives for creating subprocesses: win32all's > CreateProcess. I used the Process class in winprocess.py in the > "demos" directory. However, it didn't work with sockets perfectly. > > Say, a socket server python script is launched via CreateProcess. It > then launches sub-processes. And I kill(via TerminateProcess) the > socket server process. The subprocesses remain alive(as expected). I > try to connect to the 'dead server port'. I expect almost immediate > "connect refused" error, but it doesn't come up until the subprocesses > are all gone and client hangs forever. > > Jane If I am interpreting what you are saying here correctly you have: Main_process => [create_process] => Sub_process1 socket_server_connection subprocess2 (of subprocess1) started Sub_process1 terminated, but socket connection held until subprocess2 terminated. This is what I would expect based on my findings. Subprocess2 has inherited the socket handle when it was created (assuming you used os.system, os.spawn* or os.popen*). You would have to use the correct incantation of create_process to launch subprocess2. I have attached the code I used in place of os.system. Colin --[Win32.py]--------------------------------------------------------------- # perform equivalent of os.system without open file handles import win32process,win32event def system(cmd): handles = win32process.CreateProcess \ (None,cmd,None,None,0,0,None,None,win32process.STARTUPINFO()) status = win32event.WaitForSingleObject(handles[0],win32event.INFINITE) if status == win32event.WAIT_ABANDONED: raise 'win32.system WAIT_ABANDONED' elif status == win32event.WAIT_FAILED: raise 'win32.system WAIT_FAILED' elif status == win32event.WAIT_IO_COMPLETION: raise 'win32.system WAIT_IO_COMPLETION' elif status == win32event.WAIT_OBJECT_0: pass elif status == win32event.WAIT_TIMEOUT: raise 'win32.system WAIT_TIMEOUT' else: raise 'win32.system - unknown event status = '+str(status) From nomail at hursley.ibm.com Fri Nov 21 03:19:18 2003 From: nomail at hursley.ibm.com (Derek Fountain) Date: Fri, 21 Nov 2003 16:19:18 +0800 Subject: Exceptions, assigning a tuple References: <3fbdb857$0$1727$5a62ac22@freenews.iinet.net.au> <3FBDBA3E.23D54A7C@alcyone.com> <3fbdbbdf$0$1739$5a62ac22@freenews.iinet.net.au> <3FBDBDED.D37C503F@alcyone.com> <3fbdc12f$0$1734$5a62ac22@freenews.iinet.net.au> <3FBDC541.63DA3821@alcyone.com> Message-ID: <3fbdca0c$0$1729$5a62ac22@freenews.iinet.net.au> > The tuple function can work with instances which support an iterating > interface. And that's the final piece of the puzzle! I can now claim to understand it. Many thanks. From see_signature__ at hotmail.com Tue Nov 18 02:11:56 2003 From: see_signature__ at hotmail.com (Georgy Pruss) Date: Tue, 18 Nov 2003 07:11:56 GMT Subject: Can this be written more concisely in a functional style References: <92c59a2c.0311171648.6360213d@posting.google.com> Message-ID: <0Djub.6998$tP4.802823@twister.southeast.rr.com> Something like return any( test, xs ) or return xs.any( test ) ? -- Georgy Pruss E^mail: 'ZDAwMTEyMHQwMzMwQGhvdG1haWwuY29t\n'.decode('base64') "MetalOne" wrote in message news:92c59a2c.0311171648.6360213d at posting.google.com... | 1) | def f(xs): | for x in xs: | if test(x): return True | return False | | I know that I can do (2), but it operates on the whole list and the original | may break out early. I want the efficiency of (1), but the conciseness of (2). | | 2) | return True in map(test,xs) From reply.in.the.newsgroup at my.address.is.invalid Wed Nov 12 08:59:12 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 12 Nov 2003 14:59:12 +0100 Subject: Automating FTP file transfers References: Message-ID: <3te4rv8mfft9km412n2gnfs3bue49afkee@4ax.com> Limey Drink: >is there any where I can search through archived newsgroup posts http://groups.google.com >I would like to know if the following could be made more robust using python >and its FTP libraries rather than executing native OS commands in a shell >script. > >Basically I need to... [upload a file] Sure. Use ftplib. See http://www.python.org/doc/2.3.2/lib/module-ftplib.html Here's a code snippet from one of my scripts. import os, ftplib ftp = ftplib.FTP(Hostname,Username,Password) ftp.cwd(WorkingDirectory) ftp.storbinary("STOR " + RemoteZipFile, file(LocalZipFile, "rb")) ftp.quit() os.remove(LocalZipFile) -- Ren? Pijlman From gh at ghaering.de Wed Nov 19 07:54:52 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 19 Nov 2003 13:54:52 +0100 Subject: smtp server In-Reply-To: <29jmrvc4s9blgmpusb3t70b9g2c8q3q3gf@4ax.com> References: <29jmrvc4s9blgmpusb3t70b9g2c8q3q3gf@4ax.com> Message-ID: <3FBB681C.1090303@ghaering.de> Fernando Rodriguez wrote: > Hi, > > Is there any python smtp server available with source? Try this: import smtpd -- Gerhard From newsgroups at jhrothjr.com Wed Nov 26 21:30:16 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 26 Nov 2003 21:30:16 -0500 Subject: if - else References: Message-ID: "Jeff Wagner" wrote in message news:oanasvs703tipmup24qgc5toggte8uh67n at 4ax.com... > I am trying to rewrite an old program written in VB. I can't figure out how to do the following: > > if SumOfNumbers == 11 or SumOfNumbers == 22 or SumOfNumbers == 33: > return > else: > I2 = int(SumOfNumbers / 10) > F2 = SumOfNumbers - (I2 * 10) > SumOfNumbers = I2 + F2 > > What I want this thing to do is if the SumOfNumbers is equivalent to any of the above, I want it to > stop and return from whence it came. In VB, I had used a GOTO statement which doesn't exist in > Python. I can not, for the life of me, figure out how to replace the GOTO function I was using. I > have tried many options, i.e., continue, break, return, return SumOfNumbers, return(), and none of > them work. Throw an exception. That will give the calling routine the opportunity to then do something different. I'm not sure what the surrounding code is so I'm going to assume that it's inline. try: if SumOfNumbers == 11 or SumOfNumbers == 22 or SumOfNumbers == 33: raise SomeException else: I2 = int(SumOfNumbers / 10) F2 = SumOfNumbers - (I2 * 10) SumOfNumbers = I2 + F2 except: #whatever you need to do here Also, please use spaces when indenting. Some newsreaders don't indent at all when you use tabs. I've reindented your example above for clarity. By the way, there are probably easier ways to deal with numerology... Try something like this: (untested) if SumOfNumbers not in (11, 22, 33): tens, units = divmod(SumOfNumbers, 10) SumOfNumbers = tens + units John Roth From joconnor at cybermesa.com Tue Nov 18 11:21:25 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Tue, 18 Nov 2003 09:21:25 -0700 Subject: Detecting Browsers in Python In-Reply-To: <77dd287a.0311180813.5405af98@posting.google.com> References: <77dd287a.0311180813.5405af98@posting.google.com> Message-ID: Daniel Orner wrote: >Does anyone know of a simple way to have a Python script find out what >browser is accessing it? After a web search the only thing I found to >do this is Zope, but the system I'm programming doesn't use Zope and >I'm not really interested in installing it just for this minor detail. >Is there another way? > >Thanks! > >--Daniel Orner > > Going purely from memory, "USER-AGENT" or something similar entry in the os.environ dictionary will have a string identifying the browser. It's only partially reliable because some browsers will pretend to be another browser and some, I think, will allow the user to specify what they want to pretend to be. Anyway, play around with it and see if will give you what you need Take care, Jay From edreamleo at charter.net Sat Nov 8 11:17:21 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Sat, 8 Nov 2003 10:17:21 -0600 Subject: Leo + Python: the ultimate scripting tool #2 References: Message-ID: Reasons why Leo and Python work so well together: 2. Leo's outlines are the perfect tool for organizing scripts. This is an immediate result of the organizational power of Leo's outline. However, it continues to surprise me how powerful this really is. For example, at present, Leo has a "Scripts" menu that also organizes scripts. It may well be that Leo's outlines alone, combined with features that I shall shortly discuss, will make the scripts menu redundant. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From tchur at optushome.com.au Sat Nov 8 19:59:13 2003 From: tchur at optushome.com.au (Tim Churches) Date: 09 Nov 2003 11:59:13 +1100 Subject: ANN: Leo 4.1 beta 1 An outlining editor In-Reply-To: References: Message-ID: <1068339552.9764.5.camel@emilio> On Sun, 2003-11-09 at 10:45, Edward K. Ream wrote: > My reader didn't give me the text of your message or the attachment. There > are definite problems with 4.1 beta 1 on Linux. Please send me your bug > reports at the email address below. Thanks, and my apologies for these > problems. > > Edward > -------------------------------------------------------------------- > Edward K. Ream email: edreamleo at charter.net > Leo: Literate Editor with Outlines > Leo: http://webpages.charter.net/edreamleo/front.html > -------------------------------------------------------------------- I think this may relate to my reply, which is reproduced below. I did send it to your address but received an automated reply asking me to visit a Web page, register there and then give three good reasons why my message should be forwarded to you. You have to be joking if you expect anyone to bother doing that! > A small request: please don't use spaces in directory or filenames > in your Leo distribution - use dashes or underscores if you need a > separator. Spaces annoy the hell out of anyone using a command line > interface. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From cbrown at metservice.com Wed Nov 26 14:18:36 2003 From: cbrown at metservice.com (Colin Brown) Date: Thu, 27 Nov 2003 08:18:36 +1300 Subject: Is there a .tolower() for a string?? References: <7b1fa3cb.0311261057.ecb7325@posting.google.com> Message-ID: <3fc4fb50@news.iconz.co.nz> "Amy" wrote in message news:7b1fa3cb.0311261057.ecb7325 at posting.google.com... > I have a string say > > a = "Hello how are YOU" > > I want to end up with > > a = "hello how are you' > > Isn't there a built in method for changing a string to lowercase? > > Thanks. a.lower() From theller at python.net Thu Nov 20 14:54:23 2003 From: theller at python.net (Thomas Heller) Date: Thu, 20 Nov 2003 20:54:23 +0100 Subject: "python exe" and "py plugins" References: Message-ID: <7k1uhl3k.fsf@python.net> Ahmad Baitalmal writes: > Thomas Heller wrote: >>>That works fine in linux or uncompiled on windows, but with py2exe, it >>>can't find the "services" folder. >> You should be a bit more specific here - what do you mean by "it >> can't >> find the services folder" ? >> > I figured out that's what is happening. py2exe used to package my > "services" package because it was imported normally. But now I do a > folder lookup to find all subfolders in my sys.executable + > '/services' folder and > exec("import %s" % foldername ) > each subfolder. That's why py2exe can't package those packages when > its building. > > And I'm doing it that way because the set of plugins are not known > ofcourse, that's why I do this dynamic discovery at runtime. > > > This will work, but it feels a bit patchy to me, is there a way in > python to say "here is the path to folder x, recursevily import all > packages you find in there"? py, pyc, pyd also? No, but it's easy to do that yourself. Thomas From newsgroups at jhrothjr.com Sat Nov 1 11:25:23 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 1 Nov 2003 11:25:23 -0500 Subject: prePEP: Decimal data type References: Message-ID: "Alex Martelli" wrote in message news:KCQob.78275$e5.2907092 at news1.tin.it... > John Roth wrote: > > > Lots of comments in line. See especially the comment > > about *NOT* wanting limited precision, as envisioned > > in the referenced decimal *floating point* standards. > ... > > Since we've got infinite precision integer arithmetic, going to > > limited precision decimal arithmetic is, IMNSHO, a step backwards. > > There may be a niche for a Rational data type, but in MHO it cannot take the > place of a limited-precision-decimal (fixed or float). I suggest you think > of a separate PEP to propose Rational (check the existing and rejected ones > first, there may be some that are relevant) rather than attacking this one. Alex, where did I suggest that I wanted a rational data type? Please tell me one place in my response where I said that. Please? For the record. I'm not suggesting a rational data type. I'm quite well aware of the arguements pro and con, and Guido's position. Please read what I said without your preconceptions. The only place where you can get into trouble is with division and equivalent operations. That's the one place where you actually need to specify the result number of decimal places and the rounding policy. Every other operation has a well defined result that won't ever lead to repeating decimal representations, etc. My basic suggestion for that is to replace the division operators with a div() function that lets you specify the number of places and the rounding policy. John Roth > > > Alex > From aahz at pythoncraft.com Sat Nov 1 10:34:38 2003 From: aahz at pythoncraft.com (Aahz) Date: 1 Nov 2003 10:34:38 -0500 Subject: On PEP 322 (ireverse) References: <4xQnb.373812$R32.12367046@news2.tin.it> Message-ID: In article , Alex Martelli wrote: >Aahz wrote: >> In article <4xQnb.373812$R32.12367046 at news2.tin.it>, >> Alex Martelli wrote: >>> >>>I still prefer Werner Schiendl's idea of iter.reversed, IF we find a >>>way to have builtin function iter grow a 'staticmethod' of sorts...! >> >> Raymond has vetoed this, but I don't understand why iter() needs to grow >> a staticmethod. After all, it's just a function that can be decorated >> with attributes.... > >built-in functions normally can't, and in that way they differ from >C-coded functions. So, iter would have to be changed into a different >type that _does_ support some attributes. Did you mean "Python-coded"? Anyway, I doubt that adding an attribute to iter() would cause problems the way changing it to a type constructor would. I'm not suggesting this, mind, just curious why nobody else mentioned the possibility. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From bhicking at bhicking.plus.com Wed Nov 12 16:09:20 2003 From: bhicking at bhicking.plus.com (Limey Drink) Date: Wed, 12 Nov 2003 21:09:20 -0000 Subject: Automating FTP file transfers References: Message-ID: <5lxsb.7552$lm1.52566@wards.force9.net> OK then, case closed, Python it is :-) Its just nice to have your gut feeling backed up by other peoples experience. Thanks for all the help guys. "Rene Pijlman" wrote in message news:m435rv429an7b68feg6slv9ihgjmahopam at 4ax.com... > Limey Drink: > >Just wondering about the bigger picture with regards to sys admin scripts, > >in your opinion, is creating these type of system administration scripts > >preferable/easier than using say bash scripts, or DOS .bat scripts ? > > Yes! You get real data structures, classes, exception handling, powerful > libraries and such. > > For example, you can write system administration scripts in Python that > use a relational database, parse XML config files, send e-mail, > up/download with FTP ... > > >Just wondering if you think I should be trying to execute the in built OS > >programs such as FTP etc. calling them from python > > No. Why would you want to do that? Only as a last resort. > > >or should I be using the libraries that come with Python such as FTPlib and > >say if I wanted to send email should I be using the SMTP lib > > Yes. Otherwise you'll loose the exception handling, classes, data > structures etc. :-) > > -- > Ren? Pijlman From kristian.ovaska at helsinki.fi Sun Nov 30 09:09:00 2003 From: kristian.ovaska at helsinki.fi (Kristian Ovaska) Date: Sun, 30 Nov 2003 14:09:00 GMT Subject: sorting dictionary keys? References: Message-ID: "John Smith" : >Hi, what's the fastest way (least amount of typing) to sort dictionary >objects by the key? You could use a custom dictionary that does what you want. class Mydict(dict): def sortedkeys(self): k = self.keys() k.sort() return k -- Kristian Ovaska - http://www.cs.helsinki.fi/u/hkovaska/ From mcicogni at siosistemi.it Mon Nov 10 12:56:17 2003 From: mcicogni at siosistemi.it (Mauro Cicognini) Date: Mon, 10 Nov 2003 18:56:17 +0100 Subject: try...finally is more powerful than I thought. In-Reply-To: <3FABEDA0.82E01FD9@engcorp.com> References: <3faab4e8$0$559$b45e6eb0@senator-bedfellow.mit.edu> <3FABB15C.6BB2C44A@hotmail.com> <3FABEDA0.82E01FD9@engcorp.com> Message-ID: <3FAFD141.2070502@siosistemi.it> Peter Hansen wrote: > Mauro Cicognini wrote: > >>Does anyone else think Python could have a nicer syntax for this one? > > Perhaps, but it's such an incredibly insignificant thing as far as > I'm concerned that after hearing of the existence of lengthy past > discussions about this, and the near certainty it will not be changed, > I stopped wasting my time worrying about it and went back to writing > code that worked, and some that didn't :-). > > (Basically, check the archives for the reasons this is the way it is.) Thanx for the nice explanation. I might check the archives... and yes, I agree it is a rather insignificant thing, in fact I was just curious and the mention of past wars does check out. I for no reason will ever wish to stir them up again. BR, Mauro From FBatista at uniFON.com.ar Wed Nov 5 12:46:35 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 5 Nov 2003 14:46:35 -0300 Subject: prePEP: Decimal data type Message-ID: John Roth wrote: #- literal. As currently defined, Decimal(1.1) and Decimal("1.1") #- go through the same process: 1.1 first gets converted to a float, #- and then converted a second time to a Decimal. I'd rather not #- have even the potential for confusion. Where's that defined? Decimal(1.1) != Decimal("1.1") unless you choose an "being discused" option (j). #- Part of the reason for wanting a type (rather than a class) #- is that it's much easier to justify a specific literal for a #- built in type. And it would not be that hard to do either, #- 1.1D is quite natural, and not all that easy to mistake for #- a float (the D isn't part of the float syntax in Python, #- although it is in other languages.) I think that this first must get into the standard library. Then we all can discuss if goes builtin. #- My personal opinion in the matter is that setting the precision high #- enough so that you won't get into trouble is a hack, and #- it's a dangerous #- hack because the amount of precision needed isn't directly #- related to the #- data you're processing; it's something that came out of an analysis, #- probably by someone else under some other circumstances. Given #- a software implementation, there's a performance advantage #- to setting it as #- low #- as possible, which immediately puts things at risk if your data #- changes. This is why I'm still unsure of using Decimal as a superclass for Money. . 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 cbeck at mercury.bc.ca Wed Nov 5 18:49:22 2003 From: cbeck at mercury.bc.ca (Coby Beck) Date: Thu, 6 Nov 2003 10:49:22 +1100 Subject: Explanation of macros; Haskell macros References: <87brs2tjut.fsf@memetrics.com> Message-ID: "Stephen J. Bevan" wrote in message news:m3sml3cjtf.fsf at dino.dnsalias.com... > "Coby Beck" writes: > > Here's a nice example from some production code I wrote that is easy to > > grok. > > I follow it to a certain extent but the problem now is that we are > given a solution with together with an explanation of what it does, > but we don't know all the details of the problem that shaped the > solution. Therefore while it is possible to agree that the macro > version obviously hides a lot of detail, it isn't entirely clear if > that is the best way to hide it or even if that detail is required. The problem was a fairly ordinary one and is easy to describe at a high level. The server existed to control a complicated configuration process and later process data according to the result. It was a simple socket server and I got to dictate the form of the commands and arguments. Ultimately, it boiled down to (funcall command client-session args). So I needed (wanted) a way to, in one stroke, - define the method, properly specialized on the session object - ensure it became an allowed function to call - define a way to gather the arguments needed from the client according to number of args and the type of each. - provide a facility for arbitrarily complex validation of any of the arguments or combinations thereof. - ensure that any changes, enhancements or additions to argument passing would require a single point of change in my code. Additional benefits: - automatically provided information to a kind of "help" facility. - allowed for very informative error messages, both in the debug environment and as returned data for clients. - simplified the main server loop while remaining completely flexible > I'm not asking you to give the full requirements for your program, > only explaining why if it isn't clear what the problem is then nobody > can easily tell if the macro-based solution is an improvement over > anything else. Hopefully the above is enough of a spec. I would be very happy to learn other approaches, there are always many ways to skin a cat. (how un-PC is that saying these days ;) > For example, if the commands have any kind of grammar > then solution is to define the grammar and let a parser generator take > care of parsing and building an AST. I was fortunate to be the one defining the API so I came up with a very clever way of having named and optional arguments that could be atoms or lists defined by ( and ) characters. (I should patent that ;) I did have to define a set of safe-read functions for lists and integers and strings etc for a combination of security and timing-out reasons. But the grammar was just s-expressions. (It was culture shock for the Java client coders, and I think they still would say SOAP was better though it is beyond me why). > Whether the parser generator is > an extension of the language (as is possible in Lisp and Forth) or a > separate language (most other languages) is to a certain extent an > implementation detail. At the other extreme is a simple flat file > that is processed by an AWK program to generate source in the target > language. To someone used to using macros, the AWK approach looks > like a really poor substitute for a subset of what macros can do and > it is from that perspective. If the target language is Lisp, then not "looks like", but "is". I think you know that, though. I actually have macros I use now that generate strings of SQL code, some of it as format strings that will be used at a later stage of processing (a "format string" would be something like "SELECT NEW.~A FROM ~A WHERE ~A > 3" where the ~A's get filled with variables later) > However, the AWK route is also an > approach that can solve a lot of simple problems, probably even the > one you solved using macros. Note I'm not going to argue that it any > solution using AWK is *better* than using a macro based solution, only > that to sell macros to someone using the AWK approach the pitch has to > convince them that the macro approach is significantly better in > order to be worth investing the time and effort to learn. What > constitues "significant" obviously varies. This trade-off is not unique to macros, it is what we all face all the time with new and maybe better tools or approaches. The start-up cost makes the first uses too expensive. I don't know AWK at all, I'm sure if I did I would not just open that file in emacs and use a few keyboard macros as often... "By the time I walk to the shed and get the socket wrench, I'll have already got this nut off with the vice-grips..." And it's true! The problem being that then at nut number five I'm thinking "if I had just gone to get that socket wrench in the beginning, this next nut would already be off" I have to confess I am guilty of that all the time....But I try not to kid myself that vice-grips are generally the best tool for removing nuts and bolts. But back to macros, and really any language feature, they are all just tools and it is always a judgment call as to what the best tool for a job is and judgements are always subjective. It is very hard to convince anyone that a tool they are completely unfamiliar with is the best one for some problem they never thought they had. -- Coby Beck (remove #\Space "coby 101 @ big pond . com") From joconnor at cybermesa.com Thu Nov 27 12:04:45 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Thu, 27 Nov 2003 10:04:45 -0700 Subject: polymorphism in python In-Reply-To: References: Message-ID: Roy Smith wrote: >In article , > "Robert Brewer" wrote: > > > >>Roy Smith wrote: >> >> >>>But how often is it actually useful to do such a thing? I can't >>>remember the last time I wanted to do something like that in >>>Python. >>> >>> >>And Jay O'Connor replied: >> >> >>>Generally, if you are programming to the interface and not to >>>the class (which is what you are usually doing in OO programming, >>>or should be if your language allows it) than testing for the >>>actual type of an object is usually a no-no >>> >>> >>I find this comes up quite often in application interfaces; that is, >>points at which your code manipulates someone else's code in someone >>else's language. A prime example is forming valid SQL statements: >> >>"SELECT * FROM xyz WHERE %(Name)s = %(Value)s" % ({'Name': fieldName, >>'Value': fieldValue}) >> >> > >OK, that's a fair example (and one that I've dealt with myself). > That was another example that came to mind...dealing with external systems that care a bit more. > In >C++, you might write a polymorphic function: > >MyClass::doSqlStuff (String fieldName, int fieldValue); >MyClass::doSqlStuff (String fieldName, String fieldValue); > >In Python you'd just write a single function and embed some logic to do >the right thing depending on which type you got passed: > >def doSqlStuff (fieldName, fieldValue): > if type (fieldValue) == StringType: # or whatever > formatString = "'%s'" > else: > formatString = "%d" > >Either way, it's basicly "if this type, execute this code, if that type, >execute some other code". The only real difference is that in something >like C++, the conditional logic is done implicitly by the compiler (with >hints from you in the form of which polymorphic methods you supply) and >in Python you write the condition explicitly. I find the explicit form >much easier to write, understand, and debug. > > I actually ran into this recently with a Smalltalk application to Postgresql. However, since Smalltalk allows you to add new behavior to existing classes; I just added String>>asDBString and Number>>asDBString. So my above code would look like: MyClass>>doSqlStuff:: filedName with: fieldValue formatString := fieldValue asDBString. And it would polymophically get the right formatted string without any type checking at all. Adding such behavior to Object, Number, String, UndefniedObject etc...is an effective way to get around such checking. For example if a value is undefined (None) than you usually have to print something like "NULL" (on INSERTs) to the database, so I implemented UndefiinedObject>>asDBString to return 'NULL' so my code doensn't have to check for nil values From quentel.pierre at wanadoo.fr Mon Nov 3 11:00:14 2003 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Mon, 03 Nov 2003 16:00:14 -0000 Subject: Two naive Tkinter questions In-Reply-To: Message-ID: When you define self.b1, instead of using "command=self.setcolor" you can bind the event "click with left button" to a callback method by: self.b1=Button(self, bg="red") self.b1.bind("",self.setcolor) With this syntax, setcolor must be defined with an argument, which is an instance of the class Event. This instance has a "widget" attribute, so with event.widget you are sure to get the widget which called the method. You define setcolor by : def setcolor(self,event): event.widget["bg"]="blue" You can try to bind the other button to setcolor the same way. Then if you want a different color for each button, define setcolor by : def setcolor(self,event): if event.widget is self.b1: event.widget["bg"]="blue" elif event.widget is self.b2: event.widget["bg"]="green" From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Nov 10 17:26:03 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 10 Nov 2003 23:26:03 +0100 Subject: What do you think of this Python logo? In-Reply-To: References: Message-ID: <3fb0107b$0$58708$e4fe514c@news.xs4all.nl> Brandon J. Van Every wrote: > What do you think of this Python logo? > http://pythonology.org/logos Mixed feelings. I'm not sure what the globe is doing there. Also as Edward noted it would be nice to have a little bit more detail in the large versions: eyes in the snake, or perhaps even a little tongue sticking out? --Irmen From thorsten at pferdekaemper.com Fri Nov 21 07:39:36 2003 From: thorsten at pferdekaemper.com (Thorsten Pferdekämper) Date: Fri, 21 Nov 2003 13:39:36 +0100 Subject: Empty list as default parameter References: Message-ID: > > class listHolder: > def __init__( self, myList=[] ): > self.myList = myList > > def __repr__( self ): return str( self.myList ) > > # debug: 'a' should contain 42, 'b' should be empty. But no. > a = listHolder() > a.myList.append( 42 ) > b = listHolder() > print a > print b > > - = - = - = - > > I was expecting to see [42] then [], but instead I see [42] then [42]. It > seems that a and b share a reference to the same list object. Why? > Hi, AFAIK, the default parameter values are only instantiated once. So, the default-myList is always the same object. The coding above should be rewritten like... class listHolder: def __init__( self, myList=None ): if myList = None: self.myList = [] else: self.myList = myList Regards, Thorsten From jjl at pobox.com Wed Nov 12 13:56:28 2003 From: jjl at pobox.com (John J. Lee) Date: 12 Nov 2003 18:56:28 +0000 Subject: GUI - Qt Designer References: Message-ID: <87k765fmar.fsf@pobox.com> John Bradbury writes: > Is there any way to take the output produced by Qt designer (or any > other GUI designer) and use it in Python to create a screen? There [...] PyQt. It includes pyuic, which does what you want. John From alan.gauld at btinternet.com Tue Nov 18 18:41:11 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 18 Nov 2003 23:41:11 GMT Subject: OO design, Python, and GUIs References: <0bc1371b047abbb6ab299bf1c1f167ae@news.teranews.com> Message-ID: <3fbaac7b.357240324@news.blueyonder.co.uk> On Tue, 18 Nov 2003 05:16:32 GMT, Christopher Culver wrote: > of such a program. There should be, I gather, a core class "MainClass", > which coordinates everything, other specialised classes which report to > MainClass, and the GUI should ideally be in its own class "GuiClass". That's one solution, it could also be a set of classes - one per window or "form". > Now GuiClass at the moment doesn't know anything about MainClass. When the > program is started, an instance "mainClass" is created, which in turn > creates an instance "guiClass". But how can guiClass report anything to > the mainClass? If when you create the guiClass you pass a refernce to mainClass into the constructor the gui can send messages back to it: class mainClass: def __init__(self): ... self.gui = guiClass(self) ... class guiClass: def __init__(self, application): self.application = application ... def someCommand(self): # called by a widget somewhere self.application.someMethod(self.widgetValue) ... So when the widgets call someCommand it sends the gui data(widgetValue) back to the mainClass instance which it stores in its self.application member. You need to define the protocol between the two classes. There are some fancier variations on this to improve reuse of Gui elements, do a search on Model View Controller or MVC on Google for other ideas. > I imagine that I have to initalise the GuiClass instance in such a way > that it knows about mainClass enough to be able to call its methods, but > I've been unable find out how mainClass could pass itself to the GuiClass > __init__. The self value in the mainClass methods is a reference to the mainClass instance. Just pass self to the GUI init. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From steve at ninereeds.fsnet.co.uk Sun Nov 2 18:51:49 2003 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sun, 02 Nov 2003 23:51:49 +0000 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> <1589qvcdv9bni5fr8opactkgj9n5hecpj7@4ax.com> <2259b0e2.0311020911.57e43c0f@posting.google.com> Message-ID: On 2 Nov 2003 09:11:56 -0800, mis6 at pitt.edu (Michele Simionato) wrote: >> Hmmm - I wonder if 'expansion' or 'scale' is a continuous value in >> space-time, like curvature? Well, I guess it must be really - just >> write the model in those terms and hey presto - but what I mean, I >> guess, is "is there a function that can define that 'scale' in terms >> of local physics to explain things we don't currently have an >> explanation for?". > >I do not understand what you are trying to say here. Once, the shape of space-time (in as much as the concept existed) was assumed separate from things that are located withing the space-time. Now we know that space-time curvature is a function of gravity, which is a function of the distribution of mass. Maybe the distribution of something else determines the 'scale' or 'expansion rate' of space-time. Which suddenly sounds familiar - of course general relativity includes dilation of time and space related to gravity and velocity/acceleration anyway so there is presumably no need to postulate a 'something else' to explain the expansion of space-time (well, besides the already postulated dark energy). Oh well. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From adalke at mindspring.com Mon Nov 17 00:29:38 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 17 Nov 2003 05:29:38 GMT Subject: Python's simplicity philosophy References: <3FAC19F0.284DCB03@alcyone.com> <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <7xoevcf1u2.fsf@ruckus.brouhaha.com> <7x7k1zc0si.fsf@ruckus.brouhaha.com> Message-ID: <61Ztb.3481$sb4.1708@newsread2.news.pas.earthlink.net> Paul Rubin: > I think that decision is a little too CPython-centric. Some other > Python implementation (maybe even Jython) might like to implement the > list.sort method by calling some other sort routine (like the one > already in the library for that language) That's not a problem with Jython, since Java has a stable sort, see http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#sort(java .util.List) There was a OCaml implemenation of a Python variant, called Vyper. OCaml has a stable sort http://caml.inria.fr/devtools/doc_ocaml_classic/Array.html C++'s STL include a stable_sort http://www.codeguru.com/cpp/stlguide/stable_sort.shtml C# doesn't appear to have a stable sort. WWPyPyD? (What Would PyPy do?) I don't know. > Also, someone might want to > implement an indexable class that isn't a list (maybe it's a disk file > or something) and want to give it a sort method that cannot work by > sucking the keys into memory and calling timsort (maybe there are too > many keys to fit in memory, so external methods must be used). There are a couple of misconceptions here: - sort is a method on lists. It only works on lists. Unlike STL, which distinguishes between a container and an algorithm, there is no way to apply sort directly to anything which isn't a list. Your case (using sort on "a disk file or something") cannot occur. - All the keys must fit in memory. This is a consequence of being a list. (The keys may depend on other resource to do the comparison.) C++ is different in this regard as well. - The sort only rearranges references so there's no way to use sort to directly sort the values on disk as you could in C++. > It may > turn out to work best to use some nonstable sorting method, but then > the behavior will be inconsistent with list.sort and that makes more > cruft that the application programmer has to remember. It may have, but now with the restriction on what the sort must do there's been a redefinition of what 'best' means for Python. No implementation of Python is now allowed to do so, so the application programmer won't have to remember it. All it does it make it slightly harder for a C# programmer to write a Python implementation. And I assume there's plenty of 3rd party libraries which can help out. > Most sorting applications don't care about stability. Really? I prefer my sorts to be stable since it best agrees with what a person would do, assuming infinite patience. It's nice because it's well defined and platform independent -- which is important because I've seen bugs crop up in some programs which assumed a sort (3C) under IRIX will give the same order as under Solaris -- C's sort is not stable. > I think if a > new sorting method is going to get added so there's separate methods > for guaranteed-stable and possibly-nonstable sorting, it's best to let > the new method be the stable one (maybe list.ssort) and leave the > existing one alone. Humbug. You want an extra method (and possibly a couple of independent algorithms which can be used on your disk-based but list-like data structures) which for the most widely used version of Python (CPython) will not do anything different and for which the second most widely used version (Jython) is a trivial change, all so that *someday* someone who implements a Python in a language which doesn't have a fast stable search doesn't have to write one (copying out of any standard text book), find a 3rd party version, or translate one? Why not worry about something more complex, like regular expressions. CPython and Jython almost certainly have differences in edge cases, and what will the version of Python written in Prolog use? Andrew dalke at dalkescientific.com From m_tessier at sympatico.ca Sat Nov 8 17:22:04 2003 From: m_tessier at sympatico.ca (Don Low) Date: 8 Nov 2003 22:22:04 GMT Subject: Nested for loop problem Message-ID: Hi, I'm studying the python tutorial at python.org. In introducing the concept of *break* and *continue* Statements, and *else* Clauses on Loops, there's an example that goes as follows: #!/usr/bin/python for n in range(2, 10): for x in range(2, n): if n % x == 0: print n, 'equals', x, '*', n/x break else: # loop fell through without finding a factor print n, 'is a prime number' I have a problem with this nested for loop, because the answer it yields doesn't make sense to me. Here is the answer: 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 Where I have the problem is as follows: n = 2 in the first iteration of range(2, 10); therefore x = [] in the first iteration of range(2, n). More specifically: >>> range(2, 10) [2, 3, 4, 5, 6, 7, 8, 9] >>> range(2, 2) [] >>> for x in range(2, 2): ... print x ... Since x prints nothing, I guess x = NULL. If I try: if 2 % NULL or blank, I get an error message. So the question is when I run the script, why doesn't it produce an error message? OK, I'm sure I'm misunderstanding something, but could someone explain? -- Thanks, Don From bokr at oz.net Thu Nov 27 12:22:41 2003 From: bokr at oz.net (Bengt Richter) Date: 27 Nov 2003 17:22:41 GMT Subject: Simple instructions on how to programmatically download an image from a web page? References: Message-ID: On 26 Nov 2003 23:00:54 -0800, jarrodhroberson at yahoo.com (Y2KYZFR1) wrote: >I have search the group and not found a working example on how to >simply download a .gif from a url. > >something as simple as >http://groups.google.com/images/threadview_logo.gif should be pretty >easy, guess not? > >I don't need to know about using a browser, I need to know how to do >it programmatically from Python. > >Anyone know how to get it done? I just tried this interactively some example lines from httplib (the if 1: was just to execute the indented lines in one go) >>> import httplib >>> if 1: ... conn = httplib.HTTPConnection("www.python.org") ... conn.request("GET", "/pics/PythonPoweredSmall.gif") ... r1 = conn.getresponse() ... print r1.status, r1.reason ... data1 = r1.read() ... 200 OK >>> len(data1) 361 >>> data1[:8] 'GIF89a7\x00' >>> file('pypowgif.gif','wb').write(data1) >>> import os, webbrowser >>> webbrowser.open_new(os.path.abspath('pypowgif.gif')) or using windows file association, also >>> os.system(os.path.abspath('pypowgif.gif')) You should check errors etc., but the data apparently got through (not the logo you asked for though ;-) Regards, Bengt Richter From doctor at doctor.nl2k.ab.ca Thu Nov 13 08:42:10 2003 From: doctor at doctor.nl2k.ab.ca (The Doctor) Date: Thu, 13 Nov 2003 06:42:10 -0700 Subject: [SPAM] HELLO everybody! In-Reply-To: <003001c3a9c1$92eeed60$35c8c8c8@mcgsdev1.com> References: <003001c3a9c1$92eeed60$35c8c8c8@mcgsdev1.com> Message-ID: <20031113134210.GA20327@doctor.nl2k.ab.ca> On Thu, Nov 13, 2003 at 04:38:46PM +0800, ?????? wrote: > I am newbie for python. > -- > http://mail.python.org/mailman/listinfo/python-list Please note that this message is not viewed by anti-spam software as friendly X-Spam-Flag: YES X-Spam-Level: xxxxx X-Spam-Report: Spam detection software, running on the system +"doctor.nl2k.ab.ca", has identified this incoming email as possible spam. The original message has been attached to this so you can view it (if it isn't spam) or block similar future email. If you have any questions, see the administrator of that system for details. ____ Content preview: MIME-Version: 1.0 -- \206?i?=\232\212Zr?^Z'?+?\231??\231??\226+-\212w ?\234?\206\211?\212- [...] ____ Content analysis details: (5.2 points, 5.0 required) ____ pts rule name description ---- ---------------------- -------------------------------------------------- 2.7 SUB_HELLO Subject starts with "Hello" 1.1 MIME_BASE64_TEXT RAW: Message text disguised using base64 encoding 1.4 DNS_FROM_RFCI_DSN RBL: From: sender listed in dsn.rfc-ignorant.org ____ -- Member - Liberal International On 11 Sept 2001 the WORLD was violated. This is doctor at nl2k.ab.ca Ici doctor at nl2k.ab.ca Society MUST be saved! Extremists must dissolve. Merry Christmas 2003 and Happy New Year 2004 From skip at pobox.com Tue Nov 11 15:22:52 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 11 Nov 2003 14:22:52 -0600 Subject: True, False, None (was re. Pruss's manifesto) In-Reply-To: References: <20031110065915.07735.00000461@mb-m07.aol.com> Message-ID: <16305.17693.77530.316261@montanaro.dyndns.org> Thomas> A much better way to achieve the same goal would be to make the Thomas> optimizer recognize that True isn't re-bound within the loop. Easier said than done. Given: while True: foo() how do you know that foo() doesn't twiddle Python's builtins? Thomas> Making the optimizer better would improve the performance of Thomas> much more code than just 'while True' loops. What optimizer? ;-) Skip From usenet at soraia.com Thu Nov 20 13:22:45 2003 From: usenet at soraia.com (Joe Francia) Date: Thu, 20 Nov 2003 18:22:45 GMT Subject: win32com with netscape In-Reply-To: References: Message-ID: jeff wrote: > does anyone know how to dispatch netscape with > win32com.client or using make.py? > I search every place I can include microsoft and > netscape and find nothing about it. > I tried to search ID from vc++, and couldn't find it > neither. > I am trying to open netscape browser with > win32com.client and navigate it. > can anyone help? > > thanks > > > Jeff > There is a Mozilla ActiveX control that you can get here: http://www.iol.ie/~locka/mozilla/mozilla.htm Peace, Joe From tyler at tylereaves.com Mon Nov 3 16:27:54 2003 From: tyler at tylereaves.com (Tyler Eaves) Date: Mon, 03 Nov 2003 16:27:54 -0500 Subject: TypeError: can't multiply sequence to non-int References: Message-ID: On Mon, 03 Nov 2003 13:33:15 -0700, Python wrote: > Hello, > > I am just learning Python and am going through some examples. I found > one very simple example I can't figure out. Here is the script: > > # Enter a number to be squared > x = raw_input("Enter a number: ") > int(x) > sq = x*x > print sq > > I am getting the following error: > > Enter a number: 5 > Traceback (most recent call last): > File "db.py", line 6, in ? > sq = x*x > TypeError: can't multiply sequence to non-int > > Why is the function "int(x)" not changing the input to an integer? It is. The thing is, it doesn't do it "in place". replace that line with x = int(x) From francisgavila at yahoo.com Tue Nov 11 13:43:20 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Tue, 11 Nov 2003 13:43:20 -0500 Subject: Writing UTF-8 string to UNICODE file References: <4e9sb.154$s8.2312@news.on.tac.net> Message-ID: "Michael Weir" wrote in message news:4e9sb.154$s8.2312 at news.on.tac.net... > I'm sure this is a very simple thing to do, once you know how to do it, but > I am having no fun at all trying to write utf-8 strings to a unicode file. > Does anyone have a couple of lines of code that > - opens a file appropriately for output > - writes to this file > Thanks very much. > Michael Weir I don't quite understand, since you seem to be talking about "unicode" as if it were a distinct encoding. Unicode is not an encoding, but a mapping of numbers to meaningful symbolic representations (letters, numbers, whatever). There's no such thing as a "unicode file", strictly speaking, because a file is a byte stream and unicode has nothing to do with bytes. Of course, loosely speaking, "unicode file" means "a file which uses one of those byte-stream encodings by which any arbitrary subset of unicode code points can be represented." If you mean, "how do I encode a unicode string as utf-8", do like this: >>> u"I'm a unicode string in utf-8 encoding.".encode('utf-8') "I'm a unicode string in utf-8 encoding." This serializes an ordered collection of unicode code points into a byte stream, using the encoding method "utf-8". You want to write this byte stream to a file? Go right ahead. If you write a unicode string to something that wants a byte stream, I think Python's internal representation of the unicode string object will get serialized. (I'm not really sure what would happen, but it probably won't be utf-8.) I doubt this is what you want. You have to encode the unicode string first. To avoid having to do explicit conversions for every unicode string you want to write to a file, use codecs.open to open the file. This will wrap all reads/writes in an encoder/decoder, and all reads will give you a unicode string. However, I don't think you'll be able to write raw byte streams anymore--even normal strings will be reencoded. Also, be sure not to accidentally open the file using file() later--you'll be reading and writing raw byte streams, and will make a big mess of things. Perhaps Python should have all "strings" be unicode strings, and make a distinct "byte stream" type? This might make the "codepoint v. representation" distinction cleaner and more explicit, and allow us to go raw if we really want (although, mixing text and binary in a single file isn't such a good idea). It'd also be incredibly messy to change things, and less efficient if all you do is ascii text all day. Oh well. -- Francis Avila From max at alcyone.com Mon Nov 3 20:00:35 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 03 Nov 2003 17:00:35 -0800 Subject: Selling Python Software References: <8765i1d2jb.fsf@pobox.com> <3FA6BCF4.9BC51DF@alcyone.com> <87he1l9k0u.fsf@pobox.com> Message-ID: <3FA6FA33.8F3ED291@alcyone.com> "John J. Lee" wrote: > Oh, absolutely, but we're not (weren't, anyway) talking about a > consumer app here, but a 1000 line Python program written by a > consultant for a company. If he wrote the software for the company under the agreement that they'd buy it if they liked it, what's the likelihood that this is a concern at all? I would hope that if he had a real concern that this was a likely outcome -- that they'd talk to him, wait for him to deliver a product, and then refuse to pay him -- that he wouldn't be dealing with them at all anyway. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Be thine own place, or the world's thy jail. \__/ John Donne From __peter__ at web.de Tue Nov 4 15:36:39 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Nov 2003 21:36:39 +0100 Subject: Mixing generators and recursion References: <3fa808c3.20995000@news.t-online.de> Message-ID: Gerson Kurz wrote: > I stumbled upon a behaviour that would be somewhat nice to have, but > seemingly is not possible (in 2.3 anyway): > > import os, stat > > def walkem(directory): > print "Read files in %s" % directory > for filename in os.listdir(directory): > pathname = os.path.join(directory, filename) > if os.path.isdir(pathname): > print "Before walkem: %s" % pathname > walkem(pathname) You are creating a generator here, but never use it. Change the above line to for subpn in walkem(pathname): yield subpn > print "After walkem: %s" % pathname > else: > yield pathname > > if __name__ == "__main__": > for filename in walkem(""): > print filename > > This code will not recurse subdirectories - because the recursive > walkem() is not called (or so is my interpretation). It is of course > easy to rewrite this; I was just wondering if someone can enlighten me > why this happens (the yield documentation doesn't give me any clues), > and whether this might be a future feature? Calling a generator just creates it. Invoke the next() method to draw the actual items (the for loop does this implicitely). Sometimes it may be instructive to have a look at the library code: in your case os.walk() may be worth investigating since it performs a similar task. Peter From zsolt-public1192 at mailblocks.com Tue Nov 4 23:45:45 2003 From: zsolt-public1192 at mailblocks.com (zsolt) Date: 4 Nov 2003 20:45:45 -0800 Subject: Stuck on inheritance References: Message-ID: <439dca3f.0311042045.722f01f2@posting.google.com> I too am very new to the concept of classes and inheritance in python. I do not have a grasp on how to use "super",nor do I think it is well documented. The below code alterations shows how I learned to subclass. I may not have a complete grasp of what you were trying to do because I had to add .func to a_call_me where you instanciated function. Also,I added args to print_message, to get the the args you are adding passed through. Anyway, I hope I'm not too off the mark. def print_message(*args, **kw): print "I am a message" print args, kw class call_me(object): def __init__(self, func, *args, **kw): self.func = func self.args = args self.kw = kw def __call__(self): print "Execing..." return self.func(*self.args, **self.kw) class function(call_me): def __init__(self, func, name='', info = []): # description, authour, etc call_me.__init__(self, func, name, info) self.name = name self.info = info a_call_me = call_me(print_message) a_call_me() func = function(a_call_me.func, 'fred', []) # also tried func = function(call_me(print_message), 'fred', []) func() From pf_moore at yahoo.co.uk Mon Nov 17 17:05:13 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Mon, 17 Nov 2003 22:05:13 +0000 Subject: PEP 321: Date/Time Parsing and Formatting References: <20031117161752.GA17615@nl.linux.org> Message-ID: <65hi7ism.fsf@yahoo.co.uk> Gerrit Holl writes: > I prefer solution 2. I think it is the most object-oriented way. And we > already have several date/time modules: datetime, time, calendar. I think > we should have only one, and have calendar integrated into time. I try > to avoid using the time module whenever I can. I don't like it. It doesn't > nicely fit into my brain, it isn't object-oriented, I think it is to much > low-level. Just a brief comment here - I'm not sure I see the need to be too object-oriented here. Loading too much into classmethods of date, time, and datetime seems clumsy (not least because everything gets duplicated 3 times - conceptually, if not in terms of implementation). But it's a style issue, and you'll probably always get people with differing opinions. Paul -- This signature intentionally left blank From tjreedy at udel.edu Thu Nov 13 10:41:22 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Nov 2003 10:41:22 -0500 Subject: loop does not count... References: Message-ID: "Jonathan Driller" wrote in message news:a8cff9fb.0311121513.521ca948 at posting.google.com... > I am very new to this A common newbie programmer mistake, having read 'comment your code', is to overcomment to the point of giving a parallel plain-text version of the code, as you did. Your worse example of this is > #initialize counter at 0 > i = 0 The result is to make the code harder and more painful to read, especially for an experienced programmer, rather than easier, which is the proper purpose of comments. If you are going to write a parallel psuedocode version, make it truly parallel by using your space key (or tab key in editor that converts to spaces) to put the comments over to the right: i = 0 #initialize counter at 0 Then someone can much more easily ignore the redundant comments to read the actual code. There is no need to read urlList.txt twice. z = open('urlList.txt') urlList = z.readlines() can be replaced by urlList = urlFile.split('\n') Unless you need to write code for 1.5.2, I recommend you learn now to write string methods as methods rather than as string module functions. The latter is a redundant access path for backwards compatibility that will probably disappear in the future. If you look in the string module, you will find, for instance, def count(s, *args): return s.count(*args), so all you are doing is wrapping the method calls in an extra function call. I hope Johm's answer is the one you needed. Terry J. Reedy From ramen at lackingtalent.com Mon Nov 17 13:29:10 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 17 Nov 2003 18:29:10 -0000 Subject: Books I'd like to see References: <2259b0e2.0311132223.11af146a@posting.google.com> Message-ID: In article , Alex Martelli wrote: > Dave Benjamin wrote: > >> Ruby certainly claims to be more OO (and if Smalltalk is your definition >> of OO, it's a logical conclusion). Of course, everyone has a different >> definition of what OO really is. Including Alan Kay. =) > > I'm familiar with Ruby's claims, but, as methods/functions aren't really > first-class objects there, I don't necessarily buy into them. Well, they are, sort of: irb(main):005:0> 'hello, '.concat('world') => "hello, world" irb(main):006:0> say_hello_to = 'hello, '.method(:concat) => # irb(main):008:0> say_hello_to.call('world') => "hello, world" However: irb(main):007:0> say_hello_to('world') NoMethodError: undefined method say_hello_to' for main:Object Does not work as you would expect it to in Python. So, basically, a method is a first class object, because it's a method object, which is an object just like any other. But a method is not a function, because it's not directly callable. Functions don't really exist in Ruby; everything is a method of some object. So, I suppose it's not surprising that you have to use a "call" method to call a method object, though I'd sincerely prefer the ability to use operator overloading on () to eliminate this. In Python, the same code could be written like this: >>> say_hello_to = 'hello, '.__add__ >>> say_hello_to >>> say_hello_to('world') 'hello, world' Because of Python's simpler syntax for creating and calling method objects, it provides a more seamless integration of functional/procedural and OOP. On the other hand, directly callable objects are more like functions (or closures) than objects, by Alan Kay's definition of objects as entities that respond to messages (one of which potentially being "call"). One might argue that Ruby is more object-oriented in this respect. I think it's mostly a syntax issue, but at least for me, Python's method object syntax is more intuitive and its usefulness is more obvious. Even if both languages accomplish essentially the same result, Python seems more consistent in this regard. >>>> other hand, if you already knew OOP from another language, then you >>>> are an experienced enough programmer and you can learn Python from >>>> the Nutshell, isn't it? >>> >>> But the Nutshell only gets into OO _after_ it has covered functions, flow >>> control, etc; it doesn't _start_ from OO, which is the original poster's >>> request. >> >> Was this a conscious decision? If so, what were your motivations behind >> procedural-first vs. objects-first? > > You can productively use Python without understanding nor using 'class'. > > Sure, you'll be defining and using objects all the time, but that's much > like Monsieur Jourdain's "speaking prose for over forty years" without > knowing he was doing so... not necessarily an issue. On the other hand, > functions and flow control (and other minutiae:-) _are_ indispensable, so, > there would be nothing truly gained by introducing 'class' before them. Seems reasonable to me. It doesn't make much sense to teach the creation of classes before the creation of functions (since you'd need to know how to build a function anyway), but a diehard OOP fan would argue that this is merely the result of the fact that our current languages insist on using procedures "under the hood" to define objects, though procedures aren't really part of the definition of an object. How would you make an object without procedures? I don't really know, but then, I was taught procedural first before I was taught OOP, so I'm corrupted like the rest of us. ;) Still, there are other proponents of "objects first"... I dug up this thread last week, which is what prompted me to ask you about your motives: http://lists.bluej.org/pipermail/bluej-discuss/2002-June/001218.html Cheers, Dave -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From rmunn at pobox.com Fri Nov 21 10:00:45 2003 From: rmunn at pobox.com (Robin Munn) Date: Fri, 21 Nov 2003 15:00:45 GMT Subject: a scipy installation problem? References: Message-ID: avik wrote: > Hi. I need to use SciPy (a library of scientific tools for python) but > I runned upon a problem after installing it. I downloaded the binaries > from scipy.org and copied the contents of the archive in the > /usr/lib/python2.2/site-packages/ (there I have a number of other > modules and the "/usr/lib/python2.2/site-packages" is in the > sys.path). What I use are: Python 2.2.1 on linux2 and > SciPy-0.2.0_alpha_200.4161.linux2_py.tar.gz > Then, this is what I get... > >>>> from scipy import * > Segmentation fault (core dumped) > > Everything seems to be ok when I import a different module (for > plotting) that comes together with scipy (simply, it is another folder > isnide of the same folder /usr/lib/python2.2/site-packages/chaco): > >>>> from chaco import * >>>> > > This is probably something simple, but I just start to use python and > have no experience in programming, so I can not figure out where the > problem is. > Does anyone know what's needed to do so as to make it working? > Thanks in advance. > Regards What happens if you do "import scipy" instead of "from scipy import *"? "from ... import *" is _almost_ always a bad idea anyway, since it clutters up your namespace. It also causes issues with the reload() function. Avoid that usage unless you *really* know what you're doing. -- Robin Munn rmunn at pobox.com From __peter__ at web.de Thu Nov 27 04:05:09 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Nov 2003 10:05:09 +0100 Subject: newb comment request References: <3fc55fbc_3@news.bluewin.ch> Message-ID: Alexandre wrote: > Hi, > > Im a newb to dev and python... my first sefl assigned mission was to read > a pickled file containing a list with DB like data and convert this to > MySQL... So i wrote my first module which reads this pickled file and > writes an XML file with list of tables and fields (... next step will the > module who creates the tables according to details found in the XML file). > > If anyone has some minutes to spare, suggestions and comments would be > verry much appreciated to help me make my next modules better.. and not > starting with bad habit :) I would suggest that you repost the script without the excessive comments. Most programmers find Python very readable, your comments actually make it harder to parse for the human eye. Also, make it work if you can, or point to the actual errors that you cannot fix yourself. Provide actual test data in your post instead of the unpickling code, so that others can easily reproduce your errors. Only then you should ask for improvements. Random remarks: Object oriented programming is about programming against interfaces, so exessive type checking is a strong hint to design errors. Avoid using global variables in your functions; rather pass them explicitly as arguments. Where is valuesD introduced? "%s" % str(1.23) is the same as "%s" % 1.23 type(value) is not types.NoneType is the same as value is not None Module level code is habitually wrapped like so: if __name__ == "__main__": infile = open('cached-objects-Python-pickled-sample', 'rb') _data = pickle.load(infile) infile.close() # process _data... That way, you can import the module as well as use it as a standalone script. I'm sure, there is more, but then again, clean up the comments, try to make it work, and then repost. Peter From john at rygannon.com Sun Nov 16 16:41:26 2003 From: john at rygannon.com (John Dean) Date: Sun, 16 Nov 2003 21:41:26 GMT Subject: Rekall and associated software go 100% GPL References: <3fae9c76$0$12714$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <3fb7eed4$0$12693$fa0fcedb@lovejoy.zen.co.uk> On 10-Nov-2003, Ben Finney wrote: > On Sun, 9 Nov 2003 19:59:28 GMT, John Dean wrote: > > It gives me great pleasure to inform you that Rekall, the > > cross-platform alternative to MS Access, is now totally GPL. > > Like others have stated, I'm waiting to see if the other parties with > copyright interest in Rekall (i.e. TheKompany) agree to the release of > code under the GPL. TheKompany should be making an announcement on NewForge/Slashdot tomorrow, 17th Nov. > > > In order for you to be able to download you must register with the > > Total Rekall Portal. > > Or, wait for someone who has already downloaded it to redistribute > without this requirement, since the GPL permits this. This is quite true > > > The reason we have have made this a requirement is because we would > > like to be able to notify everybody when a new version becomes > > available. > > Surely it would be sufficient to encourage (*not* require) users to > subscribe to a rekall-anounce mailing list? There isn't a rekall-anounce mailing list and since very few people sign up to mailing lists in the first place, I have chosen to do it this way > > > You should also be aware that in order for for us to continue the > > future development of Rekall we will have to charge for technical > > support, customisation, training and consulting, therefore, now that > > we have gone wholly GPL, you will have to take out a technical support > > subscription. > > Sounds like a fine way to fund development and infrastructure. We have to make a living. Now you wouldn't begrudge that, would you. Besides nobody is compelling you to take out a subscripion, are they. We could always revert back to the commercial license, if you would prefer. -- Best Regards John From Google_Post at slink-software.com Wed Nov 12 00:07:31 2003 From: Google_Post at slink-software.com (K_Lee) Date: 11 Nov 2003 21:07:31 -0800 Subject: Regular expression code implementation review between Tcl vs Python References: <394af34.0311110758.3b1781ea@posting.google.com> <3fb10cc1.7910169@News.CIS.DFN.DE> Message-ID: <394af34.0311112107.20b9a34f@posting.google.com> hgiese at ratiosoft.com (Helmut Giese) wrote in message news:<3fb10cc1.7910169 at News.CIS.DFN.DE>... > On 11 Nov 2003 07:58:14 -0800, Google_Post at slink-software.com (K_Lee) > wrote: > > >I documented the regex internal implementation code for both Tcl and Python. > > > >As much as I like Tcl, I like Python's code much more. > >Tcl's Stub interface to the external commands is confusing to > >outsider. I still don't get why the stub interface is needed. > Simple. Let's create an example. > If you don't use it, than you have to link your extension against the > current version of Tcl, say, tcl84.lib. Easy, no problem. > > But tomorrow Tcl 8.5 comes out and you have the problem, that > tcl85.dll is running (used by tclsh or wish) and your extension needs > tcl84.dll, since (during its linking) you created an un-breakable > connection between the two. > Solutions: > - Stick with the older version of Tcl. > - Re-compile the extension now linking against Tcl85.lib (and repeat > for Tcl 8.6, 8.7, etc.) > - Don't link against Tcl8.x lib but use the 'stub interface'. This > avoids creating this fixed connection between your extension and a > particular version of Tcl, and you can use the extension with any > future version of Tcl and be happy ever after (unless the stub > interface itself changes, but this will be in a completely different > time frame- if it should ever happen at all). > > >One aspect I don't understanding about python is that the Python > >language itself is object oriented and all the internal is implement > >as C object. Why not C++ object? > Just my 0.02: I suppose that C++ compilers still differ a lot more on > different platforms (concerning their conformance to the standard) > than C compilers do. So, if portability is high on your check list, C > still is the language of choice - but in the future C++ will catch up > (IMHO). > Best regards > Helmut Giese Helmut, Thanks for the 0.02. :-) The "normal" os's dll, .so system use dlsym() call to resolve the function "string_name" to function pointers. They seems to work for upward compatibilities for most of the cases. But I kind understand the argument from the statics link library point of view, just think the price is too high for such "features". I guess the TCL original goal was also to support Win16, DOS, etc. For example, here's the python's code for regexp methods functions pointers. They are cleaner more modular than the TCL's stub table. (My 0.005) http://www.slink-software.com/W/SL_TopGetSL/Python-2.3/Python-2.3.slk/ID_regex_global_methods/FILE_Modules/regexmodule.c/L_635/LN_635#L_632 static struct PyMethodDef regex_global_methods[] = { {"compile", regex_compile, METH_VARARGS}, {"symcomp", regex_symcomp, METH_VARARGS}, {"match", regex_match, METH_VARARGS}, {"search", regex_search, METH_VARARGS}, {"set_syntax", regex_set_syntax, METH_VARARGS}, {"get_syntax", (PyCFunction)regex_get_syntax, METH_NOARGS}, {NULL, NULL} /* sentinel */ }; Here's the code for TCL Stub: http://www.slink-software.com/W/SL_TopGetSL/tcl8.4.4/tcl8.4.4.slk/ID_Tcl_RegExpCompile/FILE_generic/tclStubInit.c/L_650/LN_647#L_644 ... Tcl_RegExpCompile, /* 212 */ Tcl_RegExpExec, /* 213 */ Tcl_RegExpMatch, /* 214 */ Tcl_RegExpRange, /* 215 */ ... From v.Abazarov at comAcast.net Tue Nov 25 17:59:58 2003 From: v.Abazarov at comAcast.net (Victor Bazarov) Date: Tue, 25 Nov 2003 22:59:58 GMT Subject: Problem with PyRun_SimpleFile and MFC Application References: <188007e5.0311251232.6c4b6254@posting.google.com> Message-ID: "Mark Hammond" wrote... > vincent wehren wrote: > > "Susanne" schrieb im Newsbeitrag > > news:188007e5.0311251232.6c4b6254 at posting.google.com... > > | Hello! > > > > [...] > > PyRun_SimpleFile() reportedly (and I can second that) when certain compiler > > flags are different from the pythonxx(_d).dll. [...] > > > > (Don't know if or how this affects any of your MFC stuff though) > > Yes, this will be the OPs issue. However, you don't always use the > debug CRT - the important thing is [...] This is all OT in comp.lang.c++. Please trim your cross-posting. [follow-ups set to Python group only] Victor From op73418 at mail.telepac.pt Mon Nov 17 07:55:21 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Mon, 17 Nov 2003 12:55:21 +0000 Subject: Newbie - Variable Scope References: Message-ID: <43hhrvsc95n7urhldve4673fp36shqlrnd@4ax.com> On Mon, 17 Nov 2003 16:02:14 +0530, "RN" wrote: >I have a 2 Python scripts that contain the following lines: > >test.py >------- >from testmod import * >a1 = 10 >modfunc() > >testmod.py >----------- >def modfunc(): > print a1 > >When I run test.py, it returns the following error: > > File "testmod.py", line 2, in modfunc > print a1 >NameError: global name 'a1' is not defined > >My intent is to make a1 a global variable - so that I can access its value >in all functions of imported modules. What should I do? > The only truly global names in Python are the builtin ones and you shouldn't be mucking with those unless you have a very good reason to. Plain global variables are just global at module-level not across modules. To solve your problem: - import test.py everywhere you need a1. - Even better, reorganize your code so that you do not need global variables in the first place. Any more questions just holler, with my best regards, G. Rodrigues From steve at ninereeds.fsnet.co.uk Sun Nov 2 20:48:23 2003 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Mon, 03 Nov 2003 01:48:23 +0000 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <87he1vsopi.fsf@pobox.com> <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> <2259b0e2.0311012219.73aa445f@posting.google.com> Message-ID: On 3 Nov 2003 00:13:58 GMT, bokr at oz.net (Bengt Richter) wrote: >On 1 Nov 2003 22:19:11 -0800, mis6 at pitt.edu (Michele Simionato) wrote: > >>Stephen Horne wrote in message news:... >[...] >>> The evidence suggests that conscious minds exist >>> within the universe as an arrangement of matter subject to the same >>> laws as any other arrangement of matter. >If there is some "stuff" whose state can eventually be shown to have 1:1 relationship >with the state of a particular individual's conscious experience No-one has ever shown that. Actually, exactly the opposite. Our consciousness is a very poor substitute for reality. You may see you conscious awareness as detailed, but that is only because as soon as you shift you focus on some detail it naturally enters the consciousness (indeed it often gets backdated, so that you think it was in your consciousness at a time that it simply wasn't there at all). What would be a particularly valued aspect of consciousness? How about 'agency' - the sense of owning and controlling our own actions - the sense of free will? Well, if electrodes are placed on your brain in the right place, they can directly move your arm. So what? Well, you will be completely unaware of the remote control - unless you are told about it, you will claim that you chose to move your arm of your own free will. You will even have an excuse for why you moved your arm which you believe implicitly. In fact you don't even need electrodes on the brain - the same effect can be seen with people whose left and right brains are separated (corpus callosum cut). Hold up a card saying 'get a drink' so that it is visible only to one eye and they will go to get a drink. Hold up a card saying 'why did you get a drink?' to the other eye and they will show no awareness of the first card, insisting they just felt thirsty or whatever. Quite simply, consciousness is nothing special. It is a product of information processing in the brain. Sometimes that information processing goes wrong for some reason or another, and consciousness gets distorted as a result. The 'transducers' are our senses, providing information about reality (imperfectly) to our brains. >From the fact that my consciousness goes out like a light almost every night, I speculate that >that what persists day to day (brains, synaptic connections, proteins, etc) is not the _essential_ >basis of my experience, but rather, those persistent things somehow _shape_ the medium through >whose state-changes my conscious experience arises. What if the thing that woke up the next day was a perfect copy of you, complete with the same memories, rather like Arnie in the Sixth Day? No - not a clone. A clone is at best an identical twin with a different age as well as different memories, and identical twins do not have identical brains even at birth - there isn't enough information in our DNA to give an exact blueprint for the initial connections between the neurons in our brains. But assume a perfect copy of a person, complete with memories, could be made. How would it know that it wasn't the same self that it remembered from yesterday? Now consider this... The brain really does change during sleep. In a way, you literally are not the same person when you wake up as when you went to sleep. More worryingly, the continuity of consciousness even when awake is itself an illusion. Think of the fridge light that turns off when the fridge is shut - if you didn't know about fridge lights, and could only see it when the door is open, you would assume the light was always on. Similarly, whenever you try to observe your state of consciousness it is inherently on so it apears to be always on and continuous, but science strongly suggests that this appearance is simply wrong. So do we have any more claim to our conscious sense of self than this hypothetical copy would have? The fact is that no-one has shown me anything to make me believe that we have 'experience' separate from the information processing capacity of the brain. So far as I can see, the copy would have as much claim to the conscious sense of self, 'continuing on' from prior memory, as the original. >Now consider the experience of being "convinced" that a theory "is true." What does that mean? Science suggests that all subjective meaning is linked to either direct senses or action potentials in the brain. If you think of the concept 'democracy', for instance, you may actually generate the action potentials for raising your hand to vote (depending on your particular subjective understanding of that abstract term) - though those potentials get instantly suppressed. In fact a key language area (Brocas area IIRC) is also strongly linked to gesture - hence sign language, I suppose. This makes good sense. Evolution always works by modifying and extending what it already has. The mental 'vocabulary' has always been in terms of the bodily inputs and outputs, so as the capacity for more abstract thought evolved it would of course build upon the existing body-based 'vocabulary' foundations. I can easily suggest possible associations for the term 'convinced' by referring to a thesaurus - 'unshakeable', for instance, is a clear body/motion related metaphor. Or maybe it relates to the body language action potentials associated with the appearance of being convinced? At which point I'm suddenly having an a-ha moment - maybe the verbal and nonverbal communication deficits in Asperger syndrome and autism are strongly linked. Maybe a person who is unable to associate an idea to its body language, for instance, loses a lot of the intuitive sense of that idea. Thus the idea must be learned verbally and the verbal definition inherently gets taken too literally. Basically, if a person has to give the concept a new, abstract, internal symbol instead of using the normal body-language associated internal symbol, then any innate intuitions relating to that concept will be lost. The neurological implementation of the intuitions may exist but never get invoked - and therefore it will tend to atrophy, even if its normal development doesn't depend on somatosensory feedback in the first place. That could explain some odd 'coincidences'. Hmmmm. I think I might post this idea somewhere where it is actually on topic ;-) >Is it pain and pleasure at bottom Nope - the innate circuitry of our brain brings a lot more than that. 'Pain' and 'pleasure' are actually quite high level concepts, things which we experience as 'good' or 'bad' only because we have the information processing machinery that makes those associations. >I think we will find out a lot yet. Beautiful, subtle stuff ;-) Too bad we are >wasting so much on ugly, dumb stuff ;-/ 'Ugly' and 'dumb' are themselves only subjective perceptions. If you really want to know the truth, you must accept that it will not always be what you want to hear. >>I am also quite skeptical about IA claims. >Yes, but AI doesn't have to be all that "I" to have a huge economic and social impact. I thought IA != AI, though I have to admit I'm not sure what IA stands for. Instrumentalist something-or-other? As for AI, I'd say I agree. Having a human-style consciousness is not necessarily a practical asset for an intelligent machine. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From larry_Goodman at yahoo.com Tue Nov 25 13:18:28 2003 From: larry_Goodman at yahoo.com (Larry goodman) Date: Tue, 25 Nov 2003 13:18:28 -0500 Subject: In a bit of a pickle here :) Message-ID: <5777svgdl2kchbvg8idbm8kdefoan88o9j@4ax.com> Hi, Im an old C++ salt who is doing his first large project using python/wxPython. Fantastically productive are python and wxWindows. If you could bear with me, I have a couple of questions for people who have implemented python projects with similar characterstics. I'm building a client/server app where the client is a windows or linux desktop and the back end is pyhton middleware (im going to write) running on linux with a postgres SQL back end. I started out using the typical client/server approach starting with my data model. The more i've used python, the more i've gotten to think I really dont need a relational data model at all. All the middlware does is serve up pickled python objects to my desktop via sockets. The desktop model contains all of the logic as my app runs in an offline briefcase model. So I came up with the idea of just storing all of the python objects in the postgres database pickled in a blob field. Im sure about ten thousand other people came up with this idea before me. The only other data stored in the table will be the id of the object and the last time the object was modified. I may also store a CRC for resolution conflict. For instance, if a client tries to change an object that was also changed by someone else since they last received it, the server would throw an exception. Are there any holes with this approach? Is there a better approach? I have to stress that I cannot use remoting like pyro because the laptop will be offline most of the day. They will resync with the server at most a few times a day. I have one other question about the pickle system. If I add new attributes to an object and try to unpickle an old version will it work? How do you handle versioning of objects with pickle? My last questions involve using sockets as a transport. If I use python to exchange data via sockets on the server, will my server be susceptible to buffer overflow attacks? Because I may need to support handhelds with no SSL capability, I may need to expose a socket to the internet unsecured. Any idea what the best approach would be to keeping the bad people out in this instance? How should I secure my middleware if I cannot support SSL? If I have to I will only support SSL or running sockets over SSH. Thanks so much for helping out. From Raaijmakers, Vincent (IndSys, Wed Nov 5 11:59:11 2003 From: Raaijmakers, Vincent (IndSys, (Raaijmakers, Vincent (IndSys,) Date: Wed, 5 Nov 2003 10:59:11 -0600 Subject: Importing MySQLdb module causes malformed header error.. pls help!!! Message-ID: <971323274247EB44B9A01D0A3B424C8502DA7303@FTWMLVEM02.e2k.ad.ge.com> Looking at your code I see some weird things... Is this code complete or a cut and paste version? 1) missing the """ at the end of: def printContent(): print "Content-type: text/html\n\n" print print """ Registration results """???? Also: in your person info: what is it what you want to do in < form[ "firstname" ].value > form[ "firstname" ] already gives you the value. What IDE are you using? You should already get error messages on a higher level. Vincent -----Original Message----- From: kiranb_102 at yahoo.com [mailto:kiranb_102 at yahoo.com] Sent: Wednesday, November 05, 2003 8:52 AM To: python-list at python.org Subject: Importing MySQLdb module causes malformed header error.. pls help!!! Hello, im having this error while using Apache and the MySQLdb module. [error] [client 127.0.0.1] malformed header from script. Bad header=*** You don't have the (right): c:/program files/apache group/apache/cgi-bin/fig28_18.py I have connected all databases already. If I remove the import MySQL statement, theres no problem. But i need to use the database. . what could possibly be wrong??? pls help.. I have the MySQLdb installed in my Python directory already.. #!c:\Python23\python.exe import cgi import MySQLdb def printContent(): print "Content-type: text/html\n\n" print print """ Registration results def printReply(): from convert import genPrime, genPrimeE p1 = genPrime() q1 = genPrime() e1 = genPrimeE() N1 = p1 * q1 M1 = (p1-1)*(q1-1) print 'e1 %d, m1 %d' %(e1,M1) while(e1 % M1 == 0): e1 = genPrimeE() connection = MySQLdb.connect( db = "try" ) cursor = connection.cursor() cursor.execute("insert into trials (p,q,n,m) values ('p1','q1','n1','m1');") authorList = cursor.fetchall() cursor.close() # close cursor connection.close() printContent() form = cgi.FieldStorage() personInfo = { 'firstName' : form[ "firstname" ].value, 'lastName' : form[ "lastname" ].value, 'email' : form[ "email" ].value, 'phone' : form[ "phone" ].value, 'book' : form[ "book" ].value, 'os' : form[ "os" ].value, 'message' : form["message"].value } printReply() thanks!! -- http://mail.python.org/mailman/listinfo/python-list From jsbenson at bensonsystems.com Sat Nov 22 16:59:55 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Sat, 22 Nov 2003 13:59:55 -0800 Subject: elimination of the annoying flash Re: tkinter window geometry Message-ID: <011c01c3b143$f82ba180$210110ac@jsbwxp3> The following is just book-larnin' but may be helpful: Re elimination of an annoying flash: I'll quote from p 98 of John Grayson's book, Python and Tkinter Programming from Manning Publications, 2nd ed. 2000: Colormap events If a new colormap is installed, ColormapNotify event is generated. This may be used by your application to prevent the annoying colormap flashing which can occur when another application installs a colormap. (end quote) My ***guess*** is that you'd trap this event in the area where flashing occurs, and terminate the event propagation right there by returning "break" from the special event handler (ibid, p 107) you'd have to install, on the assumption that the colormap event propagation is causing the flashing problem higher up in the hierarchy. Then deinstall the handler once you're out of the flashing area of the code. There are possibly other display recombobulation events that are causing the flash (Exposure? Configure Notify? etc.) which also might be amenable to the above workaround. From peter at engcorp.com Fri Nov 7 10:29:57 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 07 Nov 2003 10:29:57 -0500 Subject: Question re threading and serial i/o References: <246a4e07.0311040705.5f8d9a9@posting.google.com> <3FA7CB03.6B650215@engcorp.com> <246a4e07.0311060251.3a24d5b@posting.google.com> <3FAA5A50.C05D7C0D@engcorp.com> <246a4e07.0311070443.11e85c2d@posting.google.com> Message-ID: <3FABBA75.FC1DA3C0@engcorp.com> Frank Millman wrote: > > I changed > p = file('/dev/ttyS0') > p.read(1) > to > p = os.open('/dev/ttyS0',os.O_RDONLY|os.O_NONBLOCK) > os.read(p,1) > and it behaved correctly. > > Out of interest, is there another way to open a serial port in > non-blocking mode? I think you're supposed to use module "fcntl" after opening with the standard builtin open() method, rather than having to resort to os.open(). Don't know the details. -Peter From peter at engcorp.com Wed Nov 19 12:21:14 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 19 Nov 2003 12:21:14 -0500 Subject: rotor alternative? References: <87u150cuvu.fsf@pobox.com> <3FBB805D.40A8DA75@engcorp.com> Message-ID: <3FBBA68A.6D819C5C@engcorp.com> Dave Brueck wrote: > > Rotor was nice because for very little costs in terms of CPU / coding nuisance > you could protect semi-sensitive data from nearly everyone. Sure it's > strength-per-bit-of-key-size doesn't stack up well against more modern > algorithms That's kind of the heart of the matter right there: just how good _is_ rotor, compared to modern algorithms? Can anyone describe it perhaps in comparison with DES/3DES using a kind of "equivalent key size" estimate? My guess is that it's so insecure that most people wouldn't really want to use it if they knew how insecure it was, or they would actually decide that something like XORing the data is actually adequate and stick with that. I suspect that those who want rotor actually want something stronger than it really is, but could actually get by with something even weaker than it is (though they don't believe that), and leaving it out of the standard library isn't a real problem, just a perceived one. I also suspect that statement will generate quite a bit of debate. :-) -Peter From joconnor at cybermesa.com Sat Nov 29 13:00:40 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Sat, 29 Nov 2003 11:00:40 -0700 Subject: Printing dots in single-line In-Reply-To: References: <3fb39e32$1_1@nova.entelchile.net> Message-ID: Alok Singhal wrote: >On Thu, 13 Nov 2003 12:22:01 -0300, trofe wrote: > > > >>Hey there, >> >>I want to print some dots in a single-line while my program loads or >>does something. I tried with he following but it didn't work :(. >> >>while 1: >> print '.', >> >>Prints line of dots separated by a whitespace (. . . . . . etc). Is >>there a way I can get it to display them without that white space >>(.......etc)? >> >> > >print('.' * n) > >where n is the number of dots you want to print. > >Incidentally, I saw other responses, and most of them suggest >sys.stdout.write(). Is there a reason that is preferable over the >solution above? > > The solution you give will not work when you want to do processing between each dot. From andy at fourkochs.com Tue Nov 18 16:15:33 2003 From: andy at fourkochs.com (Andy Koch) Date: Tue, 18 Nov 2003 21:15:33 GMT Subject: Looking for code Message-ID: Hello. I am new to Python and for the most part new to programming. The best way to learn to write is to read, so I have been looking for a website that has the code of programs written in Python. If anyone knows of a good place to find something like this, I would be very grateful if you could respond. Thanks! From tzot at sil-tec.gr Mon Nov 3 19:36:16 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 04 Nov 2003 02:36:16 +0200 Subject: Unexpected problem: DirsSync-1.3-rc3 - directories synchronizer References: <3fa41a05$0$79347$5fc3050@dreader2.news.tiscali.nl> Message-ID: On Sat, 1 Nov 2003 21:39:47 +0100, rumours say that "GerritM" might have written: >I downloaded and tried the recently announced dirsync program. It looks >nice, but... > >I have two presumably identical directories: one at home and one at work. I >keep them synchronized by means of zipping changed files and extracting them >at the other side. When comparing both directories by means of this nice >program I discovered that all files differ, with an mtime difference of >exactly 1 hour. I am working on a windows 98 machine at home, Windows 2000 >at work. Winzip 8.0. Somewhere in the chain a time coversion takes place, >errorneously... > >Most suspect for me is the fileserver at work, since I try to compare a >recent snapshot made at work with my directory at home. Careful examination >of a zipfile created before the wintertime started and a zipfile created >after this date shows a one hour difference for files before the critical >date.All zipfiles were made at work (windows 2000, data residing on a >fileserver; make unknown, presumably on Linux/Unix). > >Anyone seen comparable problems? This effect is rather disastrous if you use >timestamps for synchronization :-( > >regards Gerrit I presume you also live in a Daylight Savings Time timezone? Yes, welcome to the beautiful world of Windows timestamps... windows system calls that return file timestamps do not take into account that a file changed during summer time had +1 hour difference from UTC compared to a file changed after the end of summer time, and they assume constant time difference throughout the year. If you don't believe me, change the date/time to a little before time changes in your location, create a file, check its timestamp, wait a little till the time changes, then check its timestamp again. I believe POSIX compatibility did not specifically include honesty in the requirements for the return values of system calls... or even cluefulness on behalf of the POSIX-compatible-OS-wannabe-developers. The only thing I could do in my own directory sync code (mind you, using sets.Set helps a lot in finding differences!) was to optionally add 1 hour to the returned timestamp if the timestamp falls between last Sunday of March, 03:00 localtime and last Sunday of October, 03:00 localtime. I also carefully avoid to touch files in the involved computer when the time is between one hour minus and one hour plus the time-change times for various precautionary reasons :) How many times can I use the word time in a sentence? -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From logan at phreaker.nospam Thu Nov 27 08:16:22 2003 From: logan at phreaker.nospam (Logan) Date: Thu, 27 Nov 2003 14:16:22 +0100 Subject: List index - why ? References: Message-ID: On Thu, 27 Nov 2003 10:48:04 +0100, Kepes Krisztian wrote: > The string object have a method named "index", and have a method named > "find". > It is good, because many times we need to find anything, and it is > very long to write this: > > try: > i=s.index('a') > except: > i=-1 > if i<>-1: pass > > and not this: > > if (s.find('a')<>-1): pass > > Why don't exists same method in the list object ? > > It is very ugly thing (sorry, but I must say that). > > I must write in every times: > > l=[1,2,3,4] > try: > i=l.index(5) > except: > i=-1 > if i<>-1: pass > > and not this: > if (l.find(5)<>-1): pass > You can simply use the 'in' operator: a = "test" b = ['t', 'e', 's', 't'] if 's' in a: ... if 's' in b: ... 'find' and 'index' will give you the position of the first occurrence of what you are looking for; but 'find' will return -1 if what you are looking for is not in the string whereas 'index' will return a ValueError (s. example below). If you just want to test, whether something is in a string or a list, use 'in'. 's' in a --> True 's' in b --> True a.find('s') --> 2 b.index('s') --> 2 'z' in a --> False 'z' in b --> False a.find('z') --> -1 a.index('z') --> ValueError HTH, L. -- mailto: logan at phreaker(NoSpam).net From sheu at bu.edu Fri Nov 7 10:59:44 2003 From: sheu at bu.edu (Shu-Hsien Sheu) Date: Fri, 07 Nov 2003 10:59:44 -0500 Subject: Request for simple a customisable Python editor In-Reply-To: References: Message-ID: <3FABC170.5090203@bu.edu> Hi, SciTE, which is based on Scintilla is very nice. I settled down with it after 3+months of trying around. I tried emacs and VI at first, but the customization in emacs was confusing (to me) and some of vi's behavior isn't what I used to (in Win32), and it lacks code foding. -shuhsien >I want to develop a simple Python program to edit source code that is >persisted in a database (memo fields). >The code to be edited is iHTML and SQL and I want syntax colouring and good >basic features including tabs for multiple 'files' and searching. >It will be a Win32 deployment. > >My question is can anyone recommend a good Python editor program that I can >use as a starting point for customisation? >I'd like to base it on Scintilla and wxPython (though I really want the >easiest/fastest solution). Or does something already exist? >I prefer to keep it simple and focused on our requirements so an full >python IDE is probably not a good starting point. :) >The requirements are bound to grow so a good architecture is important. >Obviously I'll need source to add the required DB connectivity. > >So far I have Dave Kuhlman's wxEditor and Patrick O'Brien's Py family >shortlisted. > >Cheers > >Steve Lee >This mail has been scanned by Nortons Anti Virus Version 8 for Lotus Notes > > > > From jdhunter at ace.bsd.uchicago.edu Wed Nov 19 09:42:57 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 19 Nov 2003 08:42:57 -0600 Subject: scalar references In-Reply-To: ("Fredrik Lundh"'s message of "Wed, 19 Nov 2003 08:47:57 +0100") References: Message-ID: >>>>> "Fredrik" == Fredrik Lundh writes: Fredrik> The next step is to factor out common subexpressions that Fredrik> involve the DPI from the individual components and move Fredrik> them into the context object, via precalculated Fredrik> attributes or helper methods. Use a setdpi() method or Fredrik> descriptors to make sure all attributes are updated when Fredrik> the DPI is changed (Should individual parts even have to Fredrik> know about the current DPI, by the way? Shouldn't they Fredrik> work in the "plot value domain" or the "actual size Fredrik> domain"? Maybe you should route all drawing operations Fredrik> through the new context class? Can you think of any other Fredrik> methods that belong to the context class? Refactor!). Hi Fredrik, As for refactoring, I am! Can one refactor in the midst of refactoring ? I guess that's the best time.... I am worried about the performance hit with all the gets, especially the ones embedded by the binops. For the most part my components *are* insulated from things like DPI. It comes up in initializing transforms from physical coords to display coords. Most of the components only store their locations and transforms (using refvals or scalars) so they don't worry about these details of dpi, bounding boxes, and the like. But the code that creates the locations and transforms must. The current implementation lets me do things like specify a location as 'the top of the xtick label is 3 points below the xaxis' with top = self.bbox.y.get_refmin() - self.dpi*RRef(3/72.0) where self.bbox.y.get_refmin() is a reference to the bottom of the yaxis, dpi is a reference to DPI, and these are combined with the BinOp class posted above to return a reference to a location that updates automagically on resize events and dpi changes. If I were using a context class rather than a reference class, self.bbox.y.min would store the new min of axes, but 'top', which is defined by an arithmetic relationship to the ymin, would not be updated. I would have to propagate the resize call through all of my components (which is certainly doable) and reupdate the positions and transforms. What I like about the reference architecture combined with the binops is that I don't have to do propogate set_dpi and set_canvas_size through all the components since they all store refs to them; all locations and transformations of the components are updated with no function calls, admittedly at the expense of all the gets. John Hunter From anabell at sh163.net Thu Nov 13 04:14:12 2003 From: anabell at sh163.net (achan) Date: Thu, 13 Nov 2003 17:14:12 +0800 Subject: Metaclass' __init__ Does not Initialize Message-ID: Thanks for all who responded! I did figure out the solution while thinking about how to get the values of __slots__ iteratively. That is, by using getattrib(obj, name, value). Therefore, the opposite way should be setattrib(obj, name). :-) And for those who are puzzled why I insist on using __slots__, I'm using it to reduce errors and not for saving space, wink! BR, Anabell From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Nov 1 19:51:52 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sun, 02 Nov 2003 01:51:52 +0100 Subject: Removing Unicode from Python? In-Reply-To: <7xbrrvptmd.fsf@ruckus.brouhaha.com> References: <3fa43b28$0$58698$e4fe514c@news.xs4all.nl> <7xbrrvptmd.fsf@ruckus.brouhaha.com> Message-ID: <3fa45528$0$58709$e4fe514c@news.xs4all.nl> Paul Rubin wrote: > Irmen de Jong writes: > >>While I think I am reasonably aware of things like Unicode, >>character encodings, and assorted related stuff, I still found that >>article highly interesting. Thanks for the link! > > > Actually I think the Wikipedia article on unicode is much better. > http://www.wikipedia.org/wiki/unicode I still like Joel's article better, partly because of his writing style ;-) The wiki article is very to-the-point. Joel's article is slightly funny but still accurate. Or did I miss something-- does the wiki article address points Joel's article misses, or are there any mistakes in Joel's article? --Irmen From brett at python.org Mon Nov 24 14:47:37 2003 From: brett at python.org (Brett C.) Date: 24 Nov 2003 11:47:37 -0800 Subject: Garbage collection working improperly? References: Message-ID: <8ab0589d.0311241147.4fb44482@posting.google.com> Andrew Bennetts wrote in message news:... > On Fri, Nov 21, 2003 at 11:58:24AM +0100, Oliver Walczak wrote: > > Dear List, > > Trying the following hack: > > > > >>> a = [] > > >>> for i in range(0,9999999): > a.append(i) > > >>> del(a) > > > > Builds up a great list in memory and immediately deletes it. Unfortunately > > the task manager shows me that i allocated about 155MB in memory before > > del(), but del only releases about 40MB of them so i'm leaving about 117 MB > > of reserved memory after deleting the list. > > I believe space allocated for integers is never freed, it is instead added > to a free-list. So long as you never have a ridiculous number of integers > alive simultaneously, it's not a significant problem... > You're right. Since an integer is a full-blown object, Python keeps a list of all created integers alive for maximal reuse. But there is also no guarantee the object will be collected right away. The language spec explicitly states that there is no guarantee an object will be collected immediately. If you *have* to collect immediately then run gc.collect() . -Brett From marc.lentz at ctrceal.caisse-epargne.fr Tue Nov 18 02:50:23 2003 From: marc.lentz at ctrceal.caisse-epargne.fr (marco) Date: Tue, 18 Nov 2003 08:50:23 +0100 Subject: "python exe" and "py plugins" Message-ID: Hi, first of all ; sorry for my poor english ; i'm french ... and i hope you can understand below I use python (and wxpython) on a win32 platform, to build a simple "home theater pc". I want to release it in a package (with all needed to run) so i use (the wonderful) py2exe to build it ... it works like a charm ... nothing to say but, i'd like to make my program "plugin'able" ... so i ask myself (and you too ;-), if i could do that : - release all "core program" in an exe (with py2exe) - release the plugins in ".py" files ... and distribute them in a subfolder of my core program. and i like to call these "py files" from my core program ... (with execfile() ?) can the exe call theses, without an "installed python runtime" ? (i hope ;-) i hope you understand my need ... and could answer at my question (wish) marc From usenet at soraia.com Sat Nov 1 17:23:37 2003 From: usenet at soraia.com (Joe Francia) Date: Sat, 01 Nov 2003 22:23:37 GMT Subject: dictionaries with nested lists In-Reply-To: References: Message-ID: ruari mactaggart wrote: > can i write > >>>>dictionary[key][list][3] > > to mean the 3rd item in the list that is the corresponding value for 'key' ? You don't need the [list] part. Assuming you mean something like: bands = {'beatles': ['john','paul','george','ringo']} ...then bands['beatles'][3] == 'ringo' Peace, Joe From tjreedy at udel.edu Sun Nov 9 22:40:12 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 9 Nov 2003 22:40:12 -0500 Subject: recursion vs iteration (was Re: reduce()--what is it good for?) References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> Message-ID: "David Eppstein" wrote in message news:eppstein-3EA31B.11393809112003 at news.service.uci.edu... > Recursive memoization can be better than iteration when the recursion > can avoid evaluating a large fraction of the possible subproblems. > > An example would be the 0-1 knapsack code in > http://www.ics.uci.edu/~eppstein/161/python/knapsack.py > > If there are n items and size limit L, the iterative versions (pack4 and > pack5) take time O(nL), while the recursive version (pack3) takes time > O(min(2^n, nL)). So the recursion can be better when L is really large. Are you claiming that one *cannot* write an iterative version (with auxiliary stacks) of the same algorithm (which evaluates once each the same restricted subset subproblems) -- or merely that it would be more difficult, and more difficult to recognize correctness (without having mechanically translated the recursive version)? > An example of this came up in one of my research papers some years ago, > http://www.ics.uci.edu/~eppstein/pubs/p-3lp.html > which involved a randomized recursive memoization technique with runtime > significantly faster than that for iterating through all possible > subproblems. And it is surely also faster than recursing through all possible subproblems ;-). It seems to me that the issue of algorithm efficiency is one of avoiding unnecessary and redundant computation and that iterative versus recursive syntax has little to do, per se, with such avoidance. Standard example: the fibonacci function has at least two non-constant-time, non-memoized algorithms: one exponential (due to gross redundancy) and the other linear. Either can be expressed with either recursion or iteration. Too often, people present recursive exponential and iterative linear algorithms and falsely claim 'iteration is better (faster) than recursion'. I could just as well present iterative exponential and recursive linear algorithms and make opposite false claim. Having said all this, I quite agree that recursive expression is sometime far better for getting a clear, visibly correct implementation, which is why I consider iteration-only algorithm books to be somewhat incomplete. Terry J. Reedy From usenetBLOCK at myrealbox.com Thu Nov 20 22:35:07 2003 From: usenetBLOCK at myrealbox.com (Charlie Orford) Date: Fri, 21 Nov 2003 03:35:07 +0000 Subject: Best method for an NT service and python to interact? References: <9arqrv4umfpe1dhnicfjuod1bv7ihf8pds@4ax.com> <3FBD7C3A.AC542F65@engcorp.com> Message-ID: On Thu, 20 Nov 2003 21:45:14 -0500, Peter Hansen fought his way into comp.lang.python, paused briefly and let forth upon the unsuspecting patrons the following literary masterpiece: >My first thought would be to send a UDP packet to localhost from the >NT service whenever the event of interest happens. That's assuming >that it's meaningful to the service that this is happening... if the >service is more generic, maybe send UDP whenever any file is accessed. > >The client, when running, simply listens for those packets on a >predetermined port. If you aren't doing the file-type filtering in >the service, the client does it and the NT service can stay very >simple and generic which, since it's C code, is probably best. > >-Peter Thanks Peter. I am so clowded with Win32 programming that all I think about is window messaging. Setting up a simple UDP server is a great idea and I think I will go down this route. Many Thanks, -- Charlie E-mail? Remove the BLOCK to reply From inaleagueofmyown at hotmail.com Thu Nov 27 08:55:47 2003 From: inaleagueofmyown at hotmail.com (A. T.) Date: Thu, 27 Nov 2003 13:55:47 +0000 Subject: Writing an NLP System in Python Message-ID: My First time here, I am trying to write a program in python that can parse simple sentences like: ''I need a train from London to Brighton'' and get a query response from a database. Can anyone help me begin this task by suggesting what components I will need to look at. I am learning python, for the first time, and would be grateful for any help. Thanks A.T. _________________________________________________________________ Get Hotmail on your mobile phone http://www.msn.co.uk/msnmobile From paul at boddie.net Mon Nov 24 06:42:30 2003 From: paul at boddie.net (Paul Boddie) Date: 24 Nov 2003 03:42:30 -0800 Subject: jython lacks working xml processing modules? References: Message-ID: <23891c90.0311240342.46419188@posting.google.com> janeaustine50 at hotmail.com (Jane Austine) wrote in message news:... > I'm trying to parse an xml file with jython (not through java parsers > like xerces). > > I tried minidom in jython 2.1 and 2.2a but all failed. > > What can I do? The last resort would be using java parsers. Then how > can I use them like python xml parsers? It seems like javadom and > javasax has something to do, but I don't know how. The Java parsers seem to work quite well with the xml.dom.javadom package. First, update your CLASSPATH with references to the necessary .jar files - this can be a frustrating process, but I found that xercesImpl-2.5.0.jar and xml-apis.jar were a good combination: export CLASSPATH=.../xercesImpl-2.5.0.jar:.../xml-apis.jar Then, start jython and try the following: import xml.dom.javadom impl = xml.dom.javadom.XercesDomImplementation() # Use your own filename below! doc = impl.buildDocumentFile("example.xml") # Now, try some PyXML-style DOM properties and methods. doc.childNodes doc.childNodes[0].getAttribute("some-attr") I'd seen javadom lurking in PyXML before now, but it's a nice surprise to see that it works rather well, especially since I've never seen any evidence of anyone using it (as far as I remember). Paul From eric.brunel at pragmadev.N0SP4M.com Mon Nov 3 12:21:24 2003 From: eric.brunel at pragmadev.N0SP4M.com (Eric Brunel) Date: Mon, 03 Nov 2003 18:21:24 +0100 Subject: Two naive Tkinter questions References: Message-ID: Pierre Quentel wrote: > When you define self.b1, instead of using "command=self.setcolor" > you can bind the event "click with left button" to a callback method > by: > self.b1=Button(self, bg="red") > self.b1.bind("",self.setcolor) You shouldn't do that: the usual way buttons work is to run the associated command when the mouse button is pressed in it, then released in it too. Having the command run when the button is just clicked may seem awkward to many users. And emulating the way button usually work with bindings would be quite difficult, if not impossible. > With this syntax, setcolor must be defined with an argument, which > is an instance of the class Event. This instance has a "widget" > attribute, so with event.widget you are sure to get the widget which > called the method. You define setcolor by : > > def setcolor(self,event): > event.widget["bg"]="blue" > > You can try to bind the other button to setcolor the same way. Then > if you want a different color for each button, define setcolor by : > > def setcolor(self,event): > if event.widget is self.b1: > event.widget["bg"]="blue" > elif event.widget is self.b2: > event.widget["bg"]="green" This actually works, but you'd really better get used to using lambda's or Callback classes: they're far more generic and will solve many problems that this approach can't. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From fredrik at pythonware.com Fri Nov 28 06:14:08 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 28 Nov 2003 12:14:08 +0100 Subject: Buffer restriction in dom.minidom? References: Message-ID: Oliver Walczak wrote: > In one of my projects i use dom.minidom as XML parser. I recently had a > problem when the value of a text node as a child of an element node was > larger than 1024 characters. It created 2 or more child nodes out of it so i > had to concatenate both items again manually. On another machine it only > created one child node out of the text node as i further expected although > both are running Python 2.2.3 on WinXP. > Does anyone know whats going on there? the parser may chose to split CDATA over multiple Text nodes: http://www.python.org/doc/current/lib/dom-text-objects.html "A single CDATA section may be represented by more than one node in the document tree." if this matters to your program, use "normalize" before accessing the contents: http://www.python.org/doc/current/lib/dom-node-objects.html (using normalize is a good idea even if you're using a normalizing parser; it prevents nasty surprises the day you or someone else wants to use your code on a DOM tree created by some other part of your program...) From bokr at oz.net Sun Nov 9 12:25:17 2003 From: bokr at oz.net (Bengt Richter) Date: 9 Nov 2003 17:25:17 GMT Subject: how to read in an array in text file? References: Message-ID: On Sun, 9 Nov 2003 12:17:39 +0100, "Ulrich Petri" wrote: >"Yun Mao" schrieb im Newsbeitrag >news:bokiea$bn00$1 at netnews.upenn.edu... >> Hi, what's the easy way of reading in a two-dimentional array from a text >> file? >> The text file looks like this: >> 0.1 1.1 2.3 12.1 >> 0.3 33.0 4.1 1.1 >> >> I'm using Numeric Python now. Other solutions are also welcome. Thanks a >> lot! >> Yun > >f = file("myfile", "r") >data = [line.split() for line in f] # or (untested), to get floats when you access data[row][col] data = [map(float,line.split()) for line in f] >f.close() > Hate to leave that "(untested)" ... so, simulating the file with StringIO... >>> from StringIO import StringIO >>> f = StringIO("""\ ... 0.1 1.1 2.3 12.1 ... 0.3 33.0 4.1 1.1 ... """) >>> data = [map(float,line.split()) for line in f] >>> data [[0.10000000000000001, 1.1000000000000001, 2.2999999999999998, 12.1], [0.29999999999999999, 33.0 , 4.0999999999999996, 1.1000000000000001]] >>> for row in data: ... for colitem in row: print '%10.3f' %colitem, ... print ... 0.100 1.100 2.300 12.100 0.300 33.000 4.100 1.100 Regards, Bengt Richter From aleax at aleax.it Wed Nov 5 10:07:08 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 05 Nov 2003 15:07:08 GMT Subject: Please explain the meaning of 'stealing' a ref References: <7h3wuagiagy.fsf@pc150.maths.bris.ac.uk> Message-ID: Christos TZOTZIOY Georgiou wrote: ... >>Yes, you have to incref IF you want to keep owning that reference. > > So, "owning a reference" means simply that some code did an incref and > is responsible to decref, right? This is my first request for "Owning a reference" means "I'll dispose of that reference when I'm done with it". As per: http://www.python.org/doc/current/api/refcountDetails.html """ The reference count behavior of functions in the Python/C API is best explained in terms of ownership of references. Note that we talk of owning references, never of owning objects; objects are always shared! When a function owns a reference, it has to dispose of it properly -- either by passing ownership on (usually to its caller) or by calling Py_DECREF() or Py_XDECREF(). When a function passes ownership of a reference on to its caller, the caller is said to receive a new reference. When no ownership is transferred, the caller is said to borrow the reference. Nothing needs to be done for a borrowed reference. """ I really don't know how we could have expressed this any more clearly; if you can indicate what is hard for you to understand here, and how we could make it easier, I'd be really greateful! > clarification, although I understand that so far I was confusing "owning > a reference" and "owning an object". Ditto: I don't know how we could try to dispell this common doubt any more clearly than by saying "we talk of owning references, never of owning objects; objects are always shared!". >>> decref afterwards yourself. What's the reason? Efficiency for >> >>You'll decref when you don't want to own that reference any more, >>and you incref'd it, but if you do that soon, why bother incref'ing?-) > > I'd do that because I did not understand what "stealing a reference" > means; therefore I translated "stealing" = decref, so I presumed that I > should issue an incref in advance in order to make sure the object > passed to the function does not cease to exist before the function > returns. I assumed based on unclear (to me) terms. Hmmm -- wasn't the example on the same URL I just quoted, right after the 2nd paragrap, clear enough in terms of no incref being needed? Can you suggest a way in which we could make it clearer to you? > I understand that. So, a function "stealing" a reference means the > function takes away from the caller the responsibility for decref'ing > the object, and "stealing a reference" does not translate into some C > code, right? This is my second request for clarification. Right. There is no specific C code to which you can point and say "see, right here, the reference is being stolen". If you looked at the source for e.g. PyTuple_SetItem you might notice it *doesn't* incref (nor of course decref) its 3rd argument -- it copies that PyObject* somewhere _and that's it_ -- contrasted with the "normal" case of e.g. PySequence_SetItem which copies the PyObject* s/where AND incref's it. So the "stealing" is the copying-somewhere plus the LACK of the incref that would normally go with copying, in terms of C source. >>> Also, "borrowing" and "stealing" are the same thing? I just think that >> >>No! You get a borrowed reference when you get a reference but are not >>transferred the ownership of it. That's a pretty widespread use regarding >>references that are returned to objects that surely pre-existed. You >>must then incref in the relatively rare case you want to keep hold of >>that reference for the longer term. > > So a function "borrowing" a reference means that the function does not > incref or decref an object which was passed to it, right? That is the > third request. The function will incref the reference passed to if IF it's copying it somewhere (and will then arrange for that copy to be decref'd later when that reference is not needed any more). If the function is just using the reference and is done with it when it returns, then the function doesn't bother incref'ing it. The caller keeps ownership if it originally had it (i.e. unless it was borrowing from somewhere else, then ownership remains with whoever ultimately had it), there is no ownership transfer for that reference. > I assume that most functions of the python API "borrow" references? Yes, and so do all functions you'll be writing to be callable from Python -- it's the normal case. > Thanks for your time. You're welcome! Now I'd like, if possible, to enhance the docs so that other people's future doubts might be similarly helped -- that's the reason I'm asking you for advice on this! If you could spend some time to visit safari.oreilly.com -- subscribe and be sure to cancel before 2 weeks so you don't have to pay! -- and check the penultimate chapter of Python in a Nutshell, where I've tried an alternate "concise mixed reference/tutorial" tack to the whole issue of extending Python, I'd be particularly grateful of any feedback about that, too... thanks! Alex From max at alcyone.com Thu Nov 20 20:02:17 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 20 Nov 2003 17:02:17 -0800 Subject: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com> <3FBC2025.B2A33B6F@alcyone.com> <87d6bncbaj.fsf@einstein.electron.net> <3FBD3D6F.E4068821@alcyone.com> <878ymad3ga.fsf@einstein.electron.net> Message-ID: <3FBD6419.A5A863C8@alcyone.com> Curt wrote: > Well, changing the order of the lines in my sample to ensure the > contiguity of identical entries _is_ sorting. The tweak I made to your sample file wasn't sorted. It just had two identical adjacent lines. The modified sample again was: max at oxygen:~/tmp% cat > uniq.txt flirty curty curty flirty ^D max at oxygen:~/tmp% uniq uniq.txt flirty curty flirty You don't really think the sequence [flirty, curty, curty, flirty] is sorted, do you? > I don't know what else > one could call that procedure, but "non-sorted" appears to me to be > a rather provocative description of the modified sample which you were > constrained to alter in order that it meet a criterion whose existence > you deny. man uniq on GNU: DESCRIPTION Discard all but one of successive identical lines from INPUT (or standard input), writing to OUTPUT (or standard output). This says nothing about sorting. man uniq on Solaris 8: DESCRIPTION The uniq utility will read an input file comparing adjacent lines, and write one copy of each input line on the output. The second and succeeding copies of repeated adjacent input lines will not be written. Repeated lines in the input will not be detected if they are not adjacent. Neither of these detailed descriptions makes any reference to sorting whatsoever; uniq acts completely locally and doesn't care whether its input is sorted or not. As a more extended example, consider processing by uniq with a hypothetical log file: max at oxygen:~/tmp% cat > uniq2.txt startup connect from A message from A message from A message from A message from A disconnect from B mark mark connect from B message from B disconnect from B shutdown ^D max at oxygen:~/tmp% uniq uniq2.txt startup connect from A message from A disconnect from B mark connect from B message from B disconnect from B shutdown max at oxygen:~/tmp% uniq -c uniq2.txt # to see the number of duplicates 1 startup 1 connect from A 4 message from A 1 disconnect from B 2 mark 1 connect from B 1 message from B 1 disconnect from B 1 shutdown I hope you'd agree that this input is obviously not sorted in any way. Yet uniq works precisely as described. Yes, obviously sending uniq sorted input is a common way it is invoked. But it is by no means required. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ We are victims of our circumstance. -- Sade Adu From michael at petroni.cc Sun Nov 9 10:59:24 2003 From: michael at petroni.cc (Michael Petroni) Date: Sun, 09 Nov 2003 16:59:24 +0100 Subject: socket library problem under aix Message-ID: <3FAE645C.4050705@petroni.cc> hello *, i have a problem with python 2.2.3 under aix 4.3.3 compiled with gcc version 2.9-aix51-020209 (rpm package from ibm). the following code works fine under all other systems: --- import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 7111)) s.listen(1) while 1: (c, addr) = s.accept() c.close() --- the first connect against this miniserver works (even the connection is closed again as expected from the code). the second loop hangs at the accept call and never comes back. a netstat -a command tells me that the program is still listening on that port, but a telnet against the server brings a connection timeout. i've tried the same code under different operating systems (win, linux, openbsd) with different python versions and it works fine there. does anyone know where the problem is? thanx! rg. mike From ville.spammehardvainio at spamtut.fi Fri Nov 28 15:17:03 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 28 Nov 2003 22:17:03 +0200 Subject: newbie : using python to generate web-pages References: Message-ID: Rene Pijlman writes: Quoting: > For advanced templating tasks, I recommend Cheetah (available at > http://www.cheetahtemplate.org)." And I recommend EmPy. http://www.alcyone.com/software/empy/ It appears to be more Pythonic and elegant to me (disclaimer: I've only looked at cheetah docs, not tried it). Shameless plug: also check out my very own pywiz, a prompting system for EmPy, at: http://www.students.tut.fi/~vainio24/pywiz/ -- Ville Vainio http://www.students.tut.fi/~vainio24 From eppstein at ics.uci.edu Mon Nov 17 13:51:29 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 17 Nov 2003 10:51:29 -0800 Subject: Python's simplicity philosophy References: <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <653b7547.0311112220.2b2352e7@posting.google.com> <7xoevcf1u2.fsf@ruckus.brouhaha.com> <7x7k1zc0si.fsf@ruckus.brouhaha.com> <61Ztb.3481$sb4.1708@newsread2.news.pas.earthlink.net> <7xk75ysycx.fsf@ruckus.brouhaha.com> <7xislikga7.fsf@ruckus.brouhaha.com> Message-ID: In article <7xislikga7.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > I generally haven't found stability to be important. When I've cared > about doing something other than sorting (possibly unstably) on some > obvious key, I've generally needed some kind of DSU. Just sorting > stably wouldn't be enough. If I'm using DSU anyway, then getting > stability is trivial if I happen to need it. If you're doing the DSU by hand, getting stability is not so hard. But it's not obvious how to do it with the new key= sort argument for simplifying DSU. So there was a long discussion on python-dev about how maybe sort needed yet another keyword argument on top of key= for specifying that the DSU should include the item positions and be stable; but this seemed redundant and overcomplicated given that both current Python sorts are already stable. So Guido ended the discussion by declaring that sorts would remain stable, hence no extra keyword argument is necessary. Since DSU is now built in to the sort mechanism anyway, if you're rolling your own sort to match that mechanism you shouldn't find it difficult to include the positions on top of the other DSU you already have to do. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From sgaranti at mebnet.net Thu Nov 13 07:41:26 2003 From: sgaranti at mebnet.net (=?iso-8859-9?Q?Sel=E7uk_Garanti?=) Date: Thu, 13 Nov 2003 14:41:26 +0200 Subject: %1 is not a valid Win32 application? Message-ID: <000601c3a9e3$749814a0$04940a0a@mebnet.net> An HTML attachment was scrubbed... URL: From jjl at pobox.com Mon Nov 3 08:09:50 2003 From: jjl at pobox.com (John J. Lee) Date: 03 Nov 2003 13:09:50 +0000 Subject: best GUI toolkit for python: tkinter, wxPython or what? References: Message-ID: <87y8uxbntt.fsf@pobox.com> JanC writes: [...] > Some people outside of Trolltech are working on a GPL'ed version for Win32: > > (This should compile using mingw.) Are these people popular with TT? John From vze4rx4y at verizon.net Fri Nov 28 12:22:56 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Fri, 28 Nov 2003 17:22:56 GMT Subject: sets References: Message-ID: > Brett C. wrote: > > Sets now at blazing C speeds! > > ----------------------------- > > Raymond Hettinger implemented the sets API in C! The new built-ins are > > set (which replaces sets.Set) and frozenset (which replaces > > sets.ImmutableSet). The APIs are the same as the sets module sans the > > name change from ImmutableSet to frozenset. "Gerrit Holl" > Will the sets module now be deprecated? No, sets.py will be left alone so that existing code continues to run. Also, sets.py continues to have value for anyone needing its autoconversion feature that was not included for set(). Also, sets.py was made compatible with Py2.2, so it can be shipped with code that needs to run on older pythons. > Or will they stay and be re-implemented so they become like UserDict, > UserList, UserString? Do not expect more additions to the User**** series, the need for them was almost completely subsumed by the ability to subclass a builtin type. One could envision a SetMixin; however, performance considerations will be a strong force towards always using real sets. Raymond Hettinger From nessus at mit.edu Wed Nov 12 17:34:10 2003 From: nessus at mit.edu (Douglas Alan) Date: Wed, 12 Nov 2003 17:34:10 -0500 Subject: Python's simplicity philosophy References: <3fbqb.97878$e5.3584611@news1.tin.it> <3FAB8399.687F2021@alcyone.com> <1pQqb.432528$R32.14304849@news2.tin.it> <3FAC19F0.284DCB03@alcyone.com> <847upWAopMs$EwBp@jessikat.fsnet.co.uk> <8hfsb.7707$nz.895@newsread2.news.pas.earthlink.net> Message-ID: "Andrew Dalke" writes: > Me: >> > But I well knew what 'sum' did. > Douglas Alan >> How's that? I've never used a programming language that has sum() in >> it. > 1) From Microsoft Multiplan (a pre-Excel spreadsheet). That > was one of its functions, which I used to help my Mom manage > her cheese co-op accounts in ... 1985? Okay, well I can certainly see that a spreadsheet program should have a built-in sum() function, since that's about 50% of what spreadsheets do! But general-purpose programming languages rarely have it. >> I wouldn't even think to look in the manual for a function that adds up >> a sequence of numbers, since such a function is so uncommon and >> special-purpose. > Uncommon? Here's two pre-CS 101 assignments that use > exactly that idea: > - make a computerized grade book (A=4.0, B=3.0, etc.) which > can give the grade point average > - make a program to compute the current balance of a bank > account given the initial amount and I'm not saying that it's uncommon to want to sum a sequence of numbers (though it's not all that common, either, for most typical programming tasks) -- just that it's uncommon to build into the language a special function to do it. reduce(+, seq) apply(+, seq) are much more common, since reduce and/or apply can do the job fine and are more general. Or just a good old-fashioned loop. >> It's irrelevant whether or not many people have received poor CS >> educations -- there are many people who haven't. These people should >> be pleased to find reduce() in Python. And the people who received >> poor or no CS educations can learn reduce() in under a minute and >> should be happy to have been introduced to a cool and useful concept! > Actually, your claim is 'anyone can be explained reduce() in 10 seconds' ;) Now you want consistency from me? Boy, you ask a lot! Besides, 10 seconds is under a minute, is it not? Also, I said it could be explained in 10 seconds. Perhaps it takes a minute to learn because one would need the other 50 seconds for it to sink in. > I tell you this. Your estimate is completely off-base. Reduce is > more difficult to understand than sum. It requires knowing that > functions can be passed around. Something that anyone learning the language should learn by the time they need a special-purpose summing function! Before then, they can use a loop. They need the practice anyway. > That is non-trivial to most, based on my experience in explaining it > to other people (which for the most part have been computational > physicists, chemists, and biologists). I find this truly hard to believe. APL was a favorite among physicists who worked at John's Hopkins Applied Physics Laboratory where I lived for a year when I was in high school, and you wouldn't survive five minutes in APL without being able to grok this kind of thing. > It may be different with the people you hang around -- your email > address says 'mit.edu' which is one of the *few* places in the world > which teach Scheme as the intro language for undergrads, so you > already have a strong sampling bias. Yeah, and using Scheme was the *right* way to teach CS-101, dangit! But, like I said, I was taught APL in high-school in MD, and no one seemed troubled by reduce-like things, so it was hardly just an MIT thing. In fact, people seemed to like reduce() and friends -- people seemed to think it was a much more fun way to program, rather than using boring ol' loops. > (I acknowledge my own sampling bias from observing people in > computational sciences. I hazard to guess that I know more of those > people than you do people who have studied computer science.) Hmm, well I work for X-ray astronomers. Perhaps I should take a poll. |>oug From larsdoer at yahoo.com Mon Nov 3 23:31:02 2003 From: larsdoer at yahoo.com (Lars) Date: 3 Nov 2003 20:31:02 -0800 Subject: Converting GIFs with Python Image Library Message-ID: Hi, I'm using PIL to convert image formats supported by PIL into JPEGs. When I convert GIFs with transparency, the backgrounds turn out black. Is there a way to specify the background color when converting images with transparency? # PIL 1.1.4 import Image im = Image.open('yahoo.gif') im.convert('RGB') im.save('yahoo.jpg', 'JPEG') Thanks, Lars From seberino at spawar.navy.mil Sat Nov 22 14:39:01 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 22 Nov 2003 11:39:01 -0800 Subject: Problems sending list/tuple to a C extension. References: Message-ID: Martin Thanks for your reply. I found an example on python.org of parens for PyArg_ParseTuple at http://python.org/doc/current/ext/parseTuple.html And an example of parens AND square brackets for Py_BuildValue at: http://python.org/doc/current/ext/buildValue.html but you are right... no square bracket for PyArg_ParseTuple. I was not able to get parens (tuples) to work for either successfully. Any ideas? Chris martin at v.loewis.de (Martin v. L?wis) wrote in message news:... > seberino at spawar.navy.mil (Christian Seberino) writes: > > > python.org docs seem to suggest that sending in lists and tuples > > was as simple as changing string in PyArg_ParseTuple to contain > > parens or brackets.... > > What documentation are you specifically referring to? PyArg_ParseTuple > does not support square brackets. > > Regards, > Martin From tjreedy at udel.edu Sat Nov 1 14:44:24 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 1 Nov 2003 14:44:24 -0500 Subject: ANN: pyfromc - Python from C++ and vice versa References: <3fa3488c.12101640@news.t-online.de> <3FA3B325.1491D228@engcorp.com> <3fa3c4e1.43930000@news.t-online.de> Message-ID: <2dGdncyBTpWEkDmiRVn-ig@comcast.com> "Gerson Kurz" wrote in message news:3fa3c4e1.43930000 at news.t-online.de... > I find "licensing" example code, at best, ridiculous. And that's > basically all it is: it is an example, a starting point - it contains > only one method "test". Please. It took some work to figure out how to > exactly put the pieces together - but now that it works its almost > trivial. Licensing example code is anal-retentive, over-protective and > paranoid. There are way too many licenses attached to way too much > unlicenseworthy stuff, just for the sake of license fetishism, I agree with you that the legal stuff is pretty nasty. But you perhaps underestimate the protective aspect of minimal o.s. licenses. Your statement "Use at own risk." *is* a license term. It is, in summary, the second of two conditions in the MIT license pointed to by Peter: http://www.opensource.org/licenses/mit-license.php (The first, to acknowledge authorship, really is hardly applicable to an example that would have to be reworked). > Back in the 80s, when I started programming on the Atari & Amiga, > before the GPL became any public issue, we had three kinds of licenses > : None, Public Domain and Other. Public Domain is *not* a license, but a disclaimer of license with unilateral permission to use. Such donations, being *unconditional*, allow false claims of authorship and do nothing to prevent 'anti-good-Samaritan' lawsuits. Software authors, in the U.S. at least, increasingly feel the need for 'good-Samaritan' no-sue clauses for the same reason doctors want 'good-Samaritan' no-sue laws. The current Caldera-Sco Unix v. Linux lawsuits and $$$ demands suggests that programmer paranoia was not so paranoid afterall. Terry J. Reedy From brian at sweetapp.com Wed Nov 12 23:13:56 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 12 Nov 2003 20:13:56 -0800 Subject: looking for a name for a python SIP phone In-Reply-To: <200311122316.hACNGiNu024330@localhost.localdomain> Message-ID: <000101c3a99c$8e5a9800$21795418@dell8200> > So I've implemented a first cut at a pure-Python SIP (VoIP) phone, > and now I need a name for it. Off the top of my head, I can't think > of any Monty Python sketches involving a telephone - can anyone > else? Other names? How about "Iggy", from the Iggy Pop song "Talking Snake" (http://www.american-buddha.com/iggy.talking%20snake.htm)? You could also call it "Eve" or "Hawwah", because she got taken in by a talking snake in Genesis :-) > (As an aside, it's impressive (to me) that this can be done in python > - a bit of a 'bah' to those people who think that an interpreted > language is "too slow" for complex tasks) Yes, very impressive, please keep us updated. Cheers, Brian From jcb at iteris.com Mon Nov 17 16:53:49 2003 From: jcb at iteris.com (MetalOne) Date: 17 Nov 2003 13:53:49 -0800 Subject: asyncore/asynchat References: <698f09f8.0311141355.2430c07b@posting.google.com> Message-ID: <92c59a2c.0311171353.645955fb@posting.google.com> A map argument may be passed to asyncore.loop() asyncore.socket_map constains either a reference to the argument passed to asyncore.loop() or a global map object. asyncore.socket_map contains all the connections. You may also keep track of connections yourself by handling the callback functions asyncore.handle_accept() asyncore.handle_connect() aysncore.handle_close() From s-rube at uselessbastard.net Sun Nov 9 23:12:31 2003 From: s-rube at uselessbastard.net (Eric Williams) Date: Mon, 10 Nov 2003 05:12:31 +0100 Subject: PyQt and DCOP Documentation References: <_LDrb.3898$Lf2.1123101767@twister2.starband.net> Message-ID: Jim Bublitz wrote: > Eric Williams wrote: > > The type of 'res' is actually a DCOPReply instance - DCOPReply is > a class in Python and has 'data' and 'type' data members. 'data' > is a QByteArray instance, and 'type' is a Py string. > > > The following will work for setting the volume: > > self.call ("noatun", "Noatun", "setVolume(int)", > "\0\0\0\50", "x", "x") > > Works for me. (See (4) below) ------------------------ Thanks a lot, Jim, that's exactly what I needed. ------------------------ > > 1. You should get the KDE class ref docs if you don't have them > already. They have a good section on dcop. The docs at this > link: > > ftp://ftp.kde.com/pub/devel/kdeapidocs/kdeapidoc-cvs.tar.bz2 > ------------------------ Done. I'll really have to brush up on my c++, though; now that I'm getting a clearer picture of the api's I'm starting to grasp it a little better. ------------------------ > 2. PyKDE's dcop has never been tested. It exists primarily so the > kdecore module will build. I have pointed this out on the PyKDE > list, and no one has ever shown any interest. Yeah it'd be nice > if all of this stuff worked, but I'm one person doing 3 or 4 > releases a year. ------------------------ I can't believe you're the only person working on this stuff; with the amount of good work that's already gone into it, together with how useful an application it really is, I'd figured there was a whole gaggle of people on it. ------------------------ > 3. PyQt and PyKDE docs - mobody writes them beyond the bare > minimum (methods that take different args than in C++, or aren't > implemented, etc). PyKDE has 600 classes and 10,000 methods. I'm > not writing that many docs - sorry. The C++ docs aren't *that* > hard for non-C++ programmers to read. Ignore the '&s' and think > of '->' == "." and for anything that looks like a template (<> > in the declaration) look at the PyKDE docs and see what I > substituted for that (if anything). Contributions are always > welcome. The PyKDE list handles questions promptly. ------------------------ I just subscribed to the list. For the size and nature of the KDE project, the docs aren't bad at all. My statement above was simply that I'm in way over my head for the most part, mainly due to my general inability to program :-( ------------------------ > 4. The two 'x's above are necessary because they actually hold > the return data and return data type (they're return values). > This method should return a Python tuple with those values - it > doesn't (see 2). Now that I have some concept of how this is > supposed to work, I'll implement that. > > If you leave the "x"x out, PyKDE/sip won't be able to parse the > args for the call - it expects to see values there, but never > uses them. > > There isn't any way to determine those are return values by > looking at the method signature, and the code for this is all > machine generated. The computer did it :) QCStrings are also a > special case - I don't believe they're really objects in Python > - they're strings and strings aren't mutable. It's fairly simple > to convert them to return values "internally* in PyKDE, but it > requires a little handwritten code. > > 5. There are actually a large number of dcopRef.call methods, > varying only by how many parameters they marshall. The only > version implemented is the one that takes no parameters. I'll > look at whether those are worth implementing - probably are, but > they also probably won't work the way the C++ version works. It > actually looks pretty messy to implement, because the args are > template types. > > 6. It would be nice if there were easy conversions - for example, > the volume() method call actually returned an int instead of a > QByteArray - or there was at least a built-in QByteArray->type > convertor. I'll also look at that and see if it's worth doing > something about. Otherwise I'll just document it. > > None of this wonderful stuff will happen until the next PyKDE > release. KDE 3.2 is due Dec 8 (if on schedule). PyKDE for KDE > 3.2 will follow by probably 2 weeks to a month (he said > optimistically) - the changes will be backported to all 3.1.x > versions though (none of this appears to exist in 3.0, but I > haven't really checked it out yet). The next release will build > against KDE 3.x.y where 0 < x <= 2. I'll probably provide some > test code and examples for dcop too. > > Actually, THANKS for inquiring about this - it always helps to > know what users want to see implemented. > > Jim Thank you for taking the time to explain it. Thanks to your work and the overall KDE-coolness I'm well on the way to turning lirc into a useful application :-) cya, Eric -- --- s- should be removed to contact me... From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Nov 12 13:17:20 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 12 Nov 2003 19:17:20 +0100 Subject: socket's strange behavior with subprocesses In-Reply-To: References: Message-ID: <3fb27932$0$58699$e4fe514c@news.xs4all.nl> Jane Austine wrote: > and the server side tries to close the socket: > > #server side > >>>>z[0].close() >>>>#yes, it seems to have worked. > > > Alas, the client side doesn't wake up! It doesn't wake up unless the > notepad is exited first; only after that, 'Connection reset by peer' > is raised. What does the socket has to do with subprocesses? Nothing, I guess... try to shutdown the socket explicitly before closing it: z[0].shutdown(2) z[0].close() does that work? --Irmen From davygrvy at pobox.com Thu Nov 13 00:26:16 2003 From: davygrvy at pobox.com (David Gravereaux) Date: Wed, 12 Nov 2003 21:26:16 -0800 Subject: Regular expression code implementation review between Tcl vs Python References: <394af34.0311110758.3b1781ea@posting.google.com> <3fb10cc1.7910169@News.CIS.DFN.DE> <394af34.0311112107.20b9a34f@posting.google.com> Message-ID: <2b56rv0ql3tea10ggap26fnii9qrh2vbrq@4ax.com> David Gravereaux wrote: >Say for example I build all of Tcl statically into my application (kinda >dumb, but let's just say). Not dumb, sorry. Whoop. Starpacs do this and for good reason: to be a single file application distribution without dependencies. -- David Gravereaux [species: human; planet: earth,milkyway(western spiral arm),alpha sector] From alberto.mantovaniNOSPAM at bologna.marelli.it Wed Nov 5 06:46:10 2003 From: alberto.mantovaniNOSPAM at bologna.marelli.it (Alberto Mantovani) Date: Wed, 05 Nov 2003 11:46:10 GMT Subject: from python1.5.2 to python2.2.2 Message-ID: <3ef166ac.3608218@news.marelli.it> Hi, I have a lot of scripts written in python1.5.2 that I want to bring in python2.2.2. Someone could give me some informations about the sintax difference between this 2 version? Where can I get documents about it? Are there some available tools to do this automatically? thanks Alberto From mfranklin1 at gatwick.westerngeco.slb.com Thu Nov 27 06:08:59 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 27 Nov 2003 11:08:59 +0000 Subject: No messages... In-Reply-To: <3FC4ECD5.2060703@dem.feis.unesp.br> References: <3FC4ECD5.2060703@dem.feis.unesp.br> Message-ID: <1069931338.3604.6.camel@m-franklin> On Wed, 2003-11-26 at 18:11, Emanuel Rocha Woiski wrote: > I wonder what happened to the list.... > Is it just me being punished for an alleged "bouncing"? (I have no > problem at all with my mail server...) > Thanks for any enlightenment.. > woiski woiski, Did you get un-subscribed too? It's the third time i've been un-subscribed recently (in the last month or so) I haven't investigated my local mail server... yet. Martin BTW, I've cc'd you directly (just in case!) -- Martin Franklin From bokr at oz.net Mon Nov 3 16:02:06 2003 From: bokr at oz.net (Bengt Richter) Date: 3 Nov 2003 21:02:06 GMT Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <87he1vsopi.fsf@pobox.com> <2259b0e2.0310280832.6571dbfc@posting.google.com> <2259b0e2.0310290523.2dce18d2@posting.google.com> <2259b0e2.0310292326.55f07581@posting.google.com> <2259b0e2.0311012219.73aa445f@posting.google.com> Message-ID: On Mon, 03 Nov 2003 01:48:23 +0000, Stephen Horne wrote: >On 3 Nov 2003 00:13:58 GMT, bokr at oz.net (Bengt Richter) wrote: > >>On 1 Nov 2003 22:19:11 -0800, mis6 at pitt.edu (Michele Simionato) wrote: >> >>>Stephen Horne wrote in message news:... >>[...] >>>> The evidence suggests that conscious minds exist >>>> within the universe as an arrangement of matter subject to the same >>>> laws as any other arrangement of matter. > >>If there is some "stuff" whose state can eventually be shown to have 1:1 relationship >>with the state of a particular individual's conscious experience > >No-one has ever shown that. Actually, exactly the opposite. Our ^^^^^^^^^^^^^^^^^^^^^^^^^^-- fits well with "can eventually," no? ;-) >consciousness is a very poor substitute for reality. You may see you who proposed consciousness as a _substitute_? ;-) >conscious awareness as detailed, but that is only because as soon as >you shift you focus on some detail it naturally enters the >consciousness (indeed it often gets backdated, so that you think it >was in your consciousness at a time that it simply wasn't there at >all). I am sure there is a lot to say about how conscious experience deviates from some concept of what it should be if it was better, in someone's judgement, but that is not what I was trying to get at ;-) > >What would be a particularly valued aspect of consciousness? How about >'agency' - the sense of owning and controlling our own actions - the >sense of free will? Well, that too is an interesting topic, but not my attempted focus. > >Well, if electrodes are placed on your brain in the right place, they >can directly move your arm. So what? Well, you will be completely >unaware of the remote control - unless you are told about it, you will >claim that you chose to move your arm of your own free will. You will >even have an excuse for why you moved your arm which you believe >implicitly. I've heard similar things about post-hypnotic suggestion. > >In fact you don't even need electrodes on the brain - the same effect >can be seen with people whose left and right brains are separated >(corpus callosum cut). Hold up a card saying 'get a drink' so that it >is visible only to one eye and they will go to get a drink. Hold up a >card saying 'why did you get a drink?' to the other eye and they will >show no awareness of the first card, insisting they just felt thirsty >or whatever. > >Quite simply, consciousness is nothing special. It is a product of If it is "nothing special," would you give it up?! (forever, I don't mean a nap ;-) >information processing in the brain. Sometimes that information I am uncomfortable with "information processing" as summary of what produces consciousness. "Information processing" is a bit dry for my feeling about consciousness ;-) >processing goes wrong for some reason or another, and consciousness >gets distorted as a result. Well, you are getting close to my subject, but haven't yet focused on it, AFAICS. I don't say that to be rude, or accuse you of any lack, I'm just trying to trace the failure of my attempted communication (which, after this post, I may have to decide to live with, not having infinite time for interesting threads ;-) > >The 'transducers' are our senses, providing information about reality >(imperfectly) to our brains. I don't think the buck stops there. Certainly our senses are the first level of transducers, but I was proposing that the brain itself was a "transducer." I.e., in current experience, the brain is so far a sine-qua-non for conscious experience. But why? How? IMO talking about the brain as if that were then final zoom setting on attention to consciousness is like the beginning talk by the Greeks about atoms. We have to get to sub-atomic particles and waves etc., at least. > >>From the fact that my consciousness goes out like a light almost every night, I speculate that >>that what persists day to day (brains, synaptic connections, proteins, etc) is not the _essential_ >>basis of my experience, but rather, those persistent things somehow _shape_ the medium through >>whose state-changes my conscious experience arises. > >What if the thing that woke up the next day was a perfect copy of you, Well, close again. I was trying to explore the notion of a distinction between the "thing" as physical shape holder, and something non-physical that could be given a particular shape as a consequence, like an electric or magnetic field in the neighborhood. (Or, what if consciousness is a peculiar dynamic thing like lasing, something that happens under certain conditions, which as evolution would have it, occurs in brains a lot). As a metaphor for the essential medium of consciousness, imagine that water had consciousness associated with it, namely a consciousness of its physical boundaries and distribution in space, but of _nothing outside_ of the given connected blob of water. Now if you pour this water into a bottle, it will experience bottle-shape, but the essential concept that I am trying to get across is that it would be its _own_ bottle shape that it was experiencing, not the bottle's bottle shape, even though the latter might be the current cause of the water's configuration. So, metaphorically, I am suggesting that our brains are like flexible bottles that change shape due to influences from the real world (and are a physical part of the real world), but the brains themselves are not the "water," and not the ultimate basis for experience. Rather, the experience comes from the "water," which is experiencing its _own_ shape as it flows and follows the changes in its brain_as_container's shape. An experiment to explore this might be to set get some of this "water" into contact with an alternative shape-influence at the same time as being largely influenced by normal brain function. The experience would presumably be normal reality with some artificial content. Electric stimulation of brain areas is getting into the ball park, but finding where the puddle of magic water in the ballpark is will require closer investigation, I think. Also, the probings will cause persistent changes in the "bottle" so it will be a subtle matter to distinguish water-shape from container-shape. This is obviously a simplistic metaphor, the trick being to find something better than "water" to talk about as something that is/can be modulated to create conscious content, and then to demonstrate its modulation by means other than normal brain processes. IWT it would have to be by extension of normal consciousness processes in order to have an i/o path for the effects -- i.e., a site of ordinary consciousness associated with a person who can talk to us about their experience -- but it will be tricky to demonstrate that e.g., some nano-device is playing the full role of "bottle" for some part of the total conscious experience, as opposed to merely deforming the old bottle in some subtle way. >complete with the same memories, rather like Arnie in the Sixth Day? >No - not a clone. A clone is at best an identical twin with a >different age as well as different memories, and identical twins do >not have identical brains even at birth - there isn't enough >information in our DNA to give an exact blueprint for the initial >connections between the neurons in our brains. > >But assume a perfect copy of a person, complete with memories, could >be made. How would it know that it wasn't the same self that it >remembered from yesterday? The id() function returns a different number, being a different instance, even though == says True ;-) Seriously, the ego is probably somewhat illusory ;-) > >Now consider this... > >The brain really does change during sleep. In a way, you literally are >not the same person when you wake up as when you went to sleep. The physical state-holder is not identical, but what do you identify with? The more your body changes as you age, the more you have to recognize that your body's persistence is more like the persistence of an eddy near a rock in a stream than the persistence of the rock. What then of your consciousness, which perhaps is not even associated with the same atoms after some years? IOW, it looksto me like the important aspect is essentially form, not substance. > >More worryingly, the continuity of consciousness even when awake is >itself an illusion. Think of the fridge light that turns off when the >fridge is shut - if you didn't know about fridge lights, and could >only see it when the door is open, you would assume the light was >always on. Similarly, whenever you try to observe your state of >consciousness it is inherently on so it apears to be always on and >continuous, but science strongly suggests that this appearance is >simply wrong. This doesn't in the least clash with e.g. the concept of some kind of field-like basis for experience. It could flicker on and off and flit around. No prob. > >So do we have any more claim to our conscious sense of self than this >hypothetical copy would have? If the field hypothesis were a useful description of how things work, then the two identical physical copies would be identical transducers, and given the identical contact with reality (a little difficult if not physically congruent ;-) they would presumably give rise to identical "field effects" hypothetically tracking respective conscious experiences, however flitty etc. > >The fact is that no-one has shown me anything to make me believe that >we have 'experience' separate from the information processing capacity >of the brain. So far as I can see, the copy would have as much claim >to the conscious sense of self, 'continuing on' from prior memory, as >the original. Yes, if I understand you correctly. But I am interested in whether we should be trying to look with sensitive devices for some kind of field/energy processes that correlate with reported subjective conscious experience. (I.e., the "water" in the metaphor above) I feel blocked if I have to limit myself to talking about "information processing capacity of the brain." While interesting, IMO it is not on the path to discovering the _basis_ for consciousness in some measurable events/processes/tranformations/relationships/etc. Information processing is more of a modulator than a medium in my view. Talking about information processing is like talking about chopping vegetables. It is only one factor in giving taste to the soup, and the subject is how we experiece the taste of soup. And what we are, that we can have a tasting-soup experience without being soup. > >>Now consider the experience of being "convinced" that a theory "is true." What does that mean? > >Science suggests that all subjective meaning is linked to either Who is Science? Some person made some observations and concocted a story about them, that's my take ;-) >direct senses or action potentials in the brain. If you think of the >concept 'democracy', for instance, you may actually generate the >action potentials for raising your hand to vote (depending on your >particular subjective understanding of that abstract term) - though >those potentials get instantly suppressed. Sounds a stretch to apply this linkage story too broadly. > >In fact a key language area (Brocas area IIRC) is also strongly linked >to gesture - hence sign language, I suppose. IMO, language is only limited by your imagination and that of the other in your communication. That's why we speak of body language, etc. Anything perceptible can serve, if the two are in tune (~ at the same point in a context-sensitive parse). The fact that there is generally muscular effort in creating a perceptible signal should not IMO be taken to mean that our understanding must be limited to things with associated 'action potentials' ;-) > >This makes good sense. Evolution always works by modifying and >extending what it already has. The mental 'vocabulary' has always been >in terms of the bodily inputs and outputs, so as the capacity for more "Always" is a way to prune your thought tree. Careful ;-) >abstract thought evolved it would of course build upon the existing >body-based 'vocabulary' foundations. Ditto about "of course." > >I can easily suggest possible associations for the term 'convinced' by >referring to a thesaurus - 'unshakeable', for instance, is a clear >body/motion related metaphor. > >Or maybe it relates to the body language action potentials associated >with the appearance of being convinced? ISTM you are building up a pattern of words, and stirring a lot of lingual action potentials ;-) But what happens when you stop talking to yourself? How do you _feel_ when you _feel_ convinced? Lies may be written with the same ink as truths. And when the squiggles on paper become nano-squiggles in/amongst your brain molecules and somehow your conscious experience is affected, what is the difference between what happens when you are deceived and when you are convinced of a truth? > >At which point I'm suddenly having an a-ha moment - maybe the verbal >and nonverbal communication deficits in Asperger syndrome and autism >are strongly linked. Maybe a person who is unable to associate an idea >to its body language, for instance, loses a lot of the intuitive sense >of that idea. Thus the idea must be learned verbally and the verbal >definition inherently gets taken too literally. > I am afraid I can't follow your thoughts re Asperger syndrome as I don't know anything about it beyond the label (unless I have it to some degree, but then I would have to know how to classify my experience as related to that or not ;-) >Basically, if a person has to give the concept a new, abstract, >internal symbol instead of using the normal body-language associated >internal symbol, then any innate intuitions relating to that concept >will be lost. The neurological implementation of the intuitions may >exist but never get invoked - and therefore it will tend to atrophy, >even if its normal development doesn't depend on somatosensory >feedback in the first place. ISTM the brain is fairly adept at selecting metaphor-stand-in players to keep a show going when there seems to be a need for some new role-player on the stage. IOW, I suspect that our core ability is not in the linguistics of stage directions, but in putting on a mental show (sometimes silent mime ;-) with some useful relation to "reality-out-there." If some show-production capability has failed to develop (e.g., presenting other humans as more than cardboard cartoon cliches), I suppose it could be due to some bit players being locked in their dressing rooms and having starved to death, but I think I would look for a reason other than a building contractor's mistake to figure why the lockup. Perhaps one of the bit players early on created a traumatic disturbance on the stage, and the theatre owner just decided no more of that, perhaps being too young and inexperienced to manage a frightening crew incident at the time. Of course, I'm just playing with a metaphor here without knowing anything about how _your_ theater is run, and just a little about my own ;-) > >That could explain some odd 'coincidences'. > >Hmmmm. > >I think I might post this idea somewhere where it is actually on topic >;-) > >>Is it pain and pleasure at bottom > >Nope - the innate circuitry of our brain brings a lot more than that. I am not sure what to make of your apparent confidence in asserting truths ;-) >'Pain' and 'pleasure' are actually quite high level concepts, things If you experience pleasure only as a high level concept, you are missing something ;-) Ok, re pain, it's nice to be able to withdraw to a conceptual refuge, but what's going on at the place you are avoiding is not high level, ISTM. >which we experience as 'good' or 'bad' only because we have the >information processing machinery that makes those associations. I think I know it _feels_ good or _feels_ bad without having to have words for it. OTOH, I do think we can channel different signals to whatever generates the good or bad feelings (perhaps accounting for some of those tastes for which there is no accounting ;-) > >>I think we will find out a lot yet. Beautiful, subtle stuff ;-) Too bad we are >>wasting so much on ugly, dumb stuff ;-/ > >'Ugly' and 'dumb' are themselves only subjective perceptions. If you I disagree with the 'only' part ;-) Subjective perceptions participate in feedback loops that include effects in the real world. When I say 'ugly' and 'dumb' of course it is from my POV, and related to how I am currently wired for pain and pleasure, etc. Would that Hitler's (yes it was bound to come up ;-/) subjective perceptions had affected 'only' his delusional internal world, and likewise wrt some current personages. >really want to know the truth, you must accept that it will not always >be what you want to hear. Sure, but there is a part of truth that you create by the way you think and the way it guides you to participate in the world (so hurtful self-fulfilling delusions in the powerful cause much unnecessary misery). The staight-out mean predators who have found a way to wire themselves (disconnecting some compassion circuits) for comfort with that way of being presumably exist too. I don't like to think of that as normal for evolved humans even though obviously there are relatively successful models for predatory survival in the animal world (and in human history, depending on your definition of success). I view it is being stuck in an unenlightened mode of existence, for humans. As for dealing with bad stuff, it is hard to avoid "having to do" bad stuff in response I suppose, but IMO attitude is important, and should shape response, and IWT probably should best be based on trying to undertand the quotation, "Forgive them, for they know not what they do." -- especially since one may not really know what one is doing oneself ;-) > >>>I am also quite skeptical about IA claims. >>Yes, but AI doesn't have to be all that "I" to have a huge economic and social impact. > >I thought IA != AI, though I have to admit I'm not sure what IA stands >for. Instrumentalist something-or-other? Don't know. Sorry, I took it for a typo. > >As for AI, I'd say I agree. Having a human-style consciousness is not >necessarily a practical asset for an intelligent machine. > Whatever human-style means ;-) Regards, Bengt Richter From deets_noospaam at web.de Tue Nov 11 18:08:15 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Wed, 12 Nov 2003 00:08:15 +0100 Subject: On python syntax... References: Message-ID: > While this solution would work, I'm less than happy that the > programmer is left to ensure calls to Open are matched with calls to > close. It is significant to note that every call to open is at the > beginning of a nested context, and every call to close is at the > corresponing end of the same nested context. Maybe you can take advantage of python beeing an interpreted language and try to analyse the code fragment your programmer gives to you. As long as he doesn't do any really nasty stuff, you could try to analyse the parse tree and find blocks finishing without a close call. The parser module would make this possible. I'm not sure if its possible to get a parse tree out of a compiled function, but somewhere the source code must be, so you should be able to access it. Mind you, I never worked with that stuff before - I think it could be done, but I'm not sure if its worth the effort :) Regards, Diez From amk at amk.ca Wed Nov 19 20:06:43 2003 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 19 Nov 2003 19:06:43 -0600 Subject: Python's simplicity philosophy References: <653b7547.0311112220.2b2352e7@posting.google.com> Message-ID: <5sednRMoe_Q-jiGiRVn-tg@speakeasy.net> On 19 Nov 2003 19:45:59 -0500, Aahz wrote: > Huh?!?! uniq has always to my knowledge only worked on sorted input. > Reading the man page on two different systems confirms my knowledge. Yes, but uniq doesn't report an error if its input isn't sorted. --amk From zhoney at wildmail.com Thu Nov 20 16:27:24 2003 From: zhoney at wildmail.com (Zora Honey) Date: Thu, 20 Nov 2003 15:27:24 -0600 Subject: tkinter window geometry Message-ID: <3FBD31BC.3070203@wildmail.com> I'm trying to get a Tkinter window to open up in the same place on my screen that I left it the last time I quit the application. To do this, I simply write the position to a file at "exit" and at startup, I read the file. Simple enough, but it doesn't work. Oftentimes it's "close", but over several iterations, the window will wander all over the screen. In the output below, you can see that the x offset is "off" by +4 each iteration. Until I move the window. Then x and y are off for one iteration. Then back to just x. Anybody know what the heck is going on here? Thanks, Zora ------Output------- > python alarmsend.py in= +12+795 before=, 1x1+0+0 after= 200x200+16+795 out= +16+795 > python alarmsend.py in= +16+795 before=, 1x1+0+0 after= 200x200+20+795 out= +20+795 > python alarmsend.py in= +20+795 before=, 1x1+0+0 after= 200x200+24+795 out= +24+795 ##move window## > python alarmsend.py in= +24+795 before=, 1x1+0+0 after= 200x200+28+795 out= +1045+856 > python alarmsend.py in= +1045+856 before=, 1x1+0+0 after= 200x200+1049+795 out= +1049+795 > python alarmsend.py in= +1049+795 before=, 1x1+0+0 after= 200x200+1053+795 out= +1053+795 > python alarmsend.py in= +1053+795 before=, 1x1+0+0 after= 200x200+1057+795 -------Code-------- from Tkinter import * if __name__=="__main__": def die(): root.update_idletasks() newGeometry='+%d+%d' % (root.winfo_x(), root.winfo_y()) print "out=", newGeometry if (newGeometry!=geometryConfig): config=open("alarm.config", 'w') config.write(newGeometry+'\n') sys.exit(0) root=Tk() try: config=open("alarm.config") geometryConfig=config.readline()[:-1] config.close() print "in=", geometryConfig print "before=,", root.geometry(newGeometry=None) root.geometry(newGeometry=geometryConfig) root.update() print "after=", root.geometry(newGeometry=None) except : pass exitb=Button(root, text="Exit", command=die) exitb.pack(side=LEFT) root.mainloop() From peter at engcorp.com Mon Nov 3 15:17:40 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Nov 2003 15:17:40 -0500 Subject: simple echo server References: <3fa3fab9$0$58702$e4fe514c@news.xs4all.nl> <3FA4284A.6010701@zg.htnet.hr> <3fa4395a$0$58698$e4fe514c@news.xs4all.nl> <3FA4CB41.8080306@zg.htnet.hr> <3FA548D2.6080900@zg.htnet.hr> <3fa54ada$0$58712$e4fe514c@news.xs4all.nl> <3FA6B125.3070706@zg.hitnet.hr> Message-ID: <3FA6B7E4.86E32361@engcorp.com> Haris Bogdanovic wrote: > > I removed firewall from my computer but I still get "Permission denied" > message. I'm not really an expert on firewalls so can you tell me some > things : > Does firewall works with both sides i.e. will firewall block me from > sending something from inside of remote host to my localhost ? > If that's the case how do I lookup for open ports on that remote host > through which I can send data ? Haris, the best way to deal with technical problems like this is to start simple. Shut off the firewall, turn off anything else that might interfere, and try the program. If you get the same error message(*) you are obviously not dealing with a firewall problem, so you can cross that off your list and move on to the next potential cause. You should also simplify the program to the point where "it cannot possibly fail". Make it so simple that if it doesn't work, there is almost nothing left to blame. Usually you'll find something laughably trivial, some tiny bug, and once you've fixed it and proven that was the cause, you can apply the same fix to the full (unsimplified) program and continue troubleshooting additional problems. Two more pieces of advice: These are not necessarily Python problems, at least not based on your description, so you should be working *very* hard to help those helping you, since they are not really here to provide basic PC training or troubleshooting for problems unrelated to Python. The participants in this group are quite generous with their time, for the most part, but at some point if it becomes clear that you aren't really trying, they'll just give up. Item two, and *this is very important*. You've been asked before, yet still have not acted on this. You MUST provide the *actual* error message, cut and pasted, using your mouse, from the window where you see it, into the newsgroup posting or email message. If you don't do this, but merely type "permission denied" over and over, nobody will be able to help you. Python always produces a "traceback" when a program raises an exception, complete with line numbers and module names, showing the failing lines in detail. If there is one, include it. If this is not a Python traceback, but rather an operating system error message, cut and paste the actual *command and response* that you see in your console window. Include the prompt, include the previous command, include anything that might help. If you don't do this, please don't expect much help since you're forcing everyone to guess. -Peter From keflimarcusx at aol.comNOSPAM Mon Nov 10 06:59:15 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 10 Nov 2003 11:59:15 GMT Subject: Am I the only one who would love these extentions? - Python 3.0 proposals (long) References: Message-ID: <20031110065915.07735.00000461@mb-m07.aol.com> >But I forget a colon for >each 'else' and I feel that I'm not the only one. Funny...I always remember it on the 'else' statement and forget it on the 'if' statement. ;) Yet, I'm in favor of leaving the colon there. All you have to do to make sure that your module is syntactically correct, in case you're worried about it, is try to import it (it doesn't have to be in the context of your program). The colon also helps programs such as text editors, code processing tools, and such figure out where blocks begin: all blocks begin with a colon. Think of it as an opening brace, or a 'begin' statement, and nobody has to argue over where it belongs. ;) You'll get used to it in time and I don't think it really hurts anything. And I do think it makes code a little more readable, by saying "Hey! A block begins here!", which is why the colon was put into the language in the first place. As for the rest of your suggestions, well, from what I've heard, half of the issues have been beaten to death, and some of the rest seem silly. Why make "True" a keyword when it's fine as it is? There's no ?: operator because nobody can agree on its syntax, and most of the people who commented on the matter said that if they couldn't have their way, they wouldn't have it at all, so nobody has it. When the primary idea in a PEP is rejected, it has almost zero chance of ever resurfacing. regexps aren't built into the language because, for one thing, they really aren't pretty. Most Python code, assuming a competent programmer, is pretty. You wouldn't want to ruin that prettiness by making a non-pretty feature too tempting, would you? ;) Of course, you still have regexps when you need them, so what does it cost you? And so on. I don't think your ideas are the worst things I've ever heard or anything, but I have to say that you might be better served in trying to figure out why it is the way it is, rather than thinking "I don't like this, what can I do to change it?"...and if you can't figure it out for yourself, you can always ask here. :) - Kef From sunking77 at hotmail.com Sat Nov 1 21:26:56 2003 From: sunking77 at hotmail.com (Ray) Date: Sat, 1 Nov 2003 18:26:56 -0800 Subject: Py2exe on windows Message-ID: <000001c3a0e8$c982b870$041ad20c@computer> I'm trying to change the icon py2exe gives you for your win32 App. According to their website the syntax is : python setup.py py2exe --icon I've tried this without success. Is there another way to do this? From try_vanevery_at_mycompanyname at yahoo.com Fri Nov 14 06:03:03 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Fri, 14 Nov 2003 03:03:03 -0800 Subject: Python for .NET 1.0 beta 2 released References: Message-ID: "Brian Lloyd" wrote in message news:mailman.734.1068775234.702.python-list at python.org... > > Python for .NET 1.0 beta 2 has been released - you can download > it from: > > http://www.zope.org/Members/Brian/PythonNet/ Cool! I'll be interested to see how it works! -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA Brandon's Law (after Godwin's Law): "As a Usenet discussion grows longer, the probability of a person being called a troll approaches one RAPIDLY."