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 "