From gagsl-py2 at yahoo.com.ar Sat Aug 1 00:04:27 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 01 Aug 2009 01:04:27 -0300 Subject: problem on socket programming References: <3de0863c-15ef-4153-8d0f-6b7a438b98f5@c2g2000yqi.googlegroups.com> <67ec3e6d-0995-459a-a7a5-3bc296729664@b15g2000yqd.googlegroups.com> <7dg2niF2bue0tU2@mid.uni-berlin.de> <5dbf451d-a289-40d1-83db-ce655d47f698@r38g2000yqn.googlegroups.com> <7dg55pF2bfubpU1@mid.uni-berlin.de> <72f851f9-a2d4-4448-900d-3fe20e4ebeb0@w41g2000yqb.googlegroups.com> Message-ID: En Fri, 31 Jul 2009 10:43:49 -0300, MalC0de escribi?: > none of you can't interpret it ? do you have errors like me !? Have you tried Diez B. Roggisch suggestion? : >> Can you ping and telnet to the port on the desired server? >> Firewalls can be an issue here. The official doc page for the socket module contains a working example of an echo client/server program like yours: http://docs.python.org/library/socket.html#example -- Gabriel Genellina From emmanuel.surleau at gmail.com Sat Aug 1 00:20:28 2009 From: emmanuel.surleau at gmail.com (Emmanuel Surleau) Date: Sat, 1 Aug 2009 06:20:28 +0200 Subject: Confessions of a Python fanboy In-Reply-To: <008f7990$0$9756$c3e8da3@news.astraweb.com> References: <008f7990$0$9756$c3e8da3@news.astraweb.com> Message-ID: <200908010620.28665.emmanuel.surleau@gmail.com> On Saturday 01 August 2009 03:46:12 Steven D'Aprano wrote: > On Fri, 31 Jul 2009 20:41:12 +0200, Emmanuel Surleau wrote: > >> We don't actually *declare* that something is constant and then have > >> that declaration ignored. Python doesn't lie to us, although (as in any > >> language) a programmer might. > > > > You could say that Ruby doesn't either, > > Well you could say a lot of things. Admittedly you don't need a separate > "constant" declaration, but creating a variable name with an initial > uppercase letter is sufficient to make it a (supposed) constant: *shrugs* I see it as a way to encourage (but not force) people to follow a coding convention. Is this such a bad thing? > irb(main):049:0* Thing = 5 > => 5 > irb(main):050:0> Thing = 7 > (irb):50: warning: already initialized constant Thing > => 7 > > As you can see, Ruby (well, irb at least) considers that Thing is a > constant, and then goes ahead and changes it anyway. I'm quite aware of how constants work in Ruby, yes :) > Apart from the use of an arbitrary naming convention instead of an > explicit "make this constant" declaration, and the feeble way Ruby > capitulates when you change it, I think having actual write-once > constants is actually a plus. Nothing wrong with naming conventions. This encourages a uniform coding style, something which Python could really use. > > you just need to read the > > documentation. Ruby's unwritten motto is "flexibility ?ber alles". In > > this regard, it is consistent (1). > > "It's consistent in its inconsistency" sort of thing perhaps? No, just consistent. > > Not much is really bolted down in > > Ruby. You get encapsulation, but it's so easy to break that it's mostly > > symbolic. > > Out of curiosity, can you read/write class and instance attributes from > outside the class without using a getter/setter? If you have an instance f class with a attribute @foo which doesn't have an accessor, you could do: f.instance_eval("@foo='bar'") And yes, instance_eval is evil. Cheers, Emm From gagsl-py2 at yahoo.com.ar Sat Aug 1 00:48:50 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 01 Aug 2009 01:48:50 -0300 Subject: Newbie Question regarding __init__() References: Message-ID: En Sat, 01 Aug 2009 00:13:05 -0300, Nat Williams escribi?: > One other thing. I'm a little confused by the first line of > dcObject.__init__: > > self.init_Pre() and self.init_Exec() > > I suspect this does not do what you think it does. init_Pre and > init_Exec > will both be called by this expression (unless init_Pre throws an > exception, > of course). You're not getting anything here that you wouldn't by just > calling each method on a separate line, except just making it harder to > read. Well, perhaps Simon didn't grasp Python's syntax and semantics very well yet, but his code would work as designed after fixing obvious errors: class dcObject(object): """Base Object""" def __init__(self): """default init method has the form of init_Pre() and init_Exec init_Post()""" self.init_Pre() and self.init_Exec() self.init_Post() def init_Pre(self): """Always called before init_Exec() if it returns false init_Exec is not executed""" return True def init_Exec(self): """Base __init__ code goes here and this is only executed if init_Pre() returns true""" return True def init_Post(self): """Always called after the init_Pre() and init_Exec()""" return True init_Pre might return False, in that case init_Exec would not be executed. init_Post is always called. And that's exactly what the docstrings say. I would use an `if` statement instead: if self.init_Pre(): self.init_Exec() and make init_Exec and init_Post not return anything if they have no intrinsic meaning. And probably use better names. But basically the structure is OK. -- Gabriel Genellina From nad at acm.org Sat Aug 1 00:55:34 2009 From: nad at acm.org (Ned Deily) Date: Fri, 31 Jul 2009 21:55:34 -0700 Subject: Python docs disappointing References: <4A73AAE3.1050209@tim.thechases.com> Message-ID: In article , Terry Reedy wrote: > This is one area where Windows users seems to have an advantage. The > standard installer includes the doc set as a Windows help file. I often > keep that open in one window while programming in others. I only later > discovered that this was a copy of the online docs ;-), which I only use > to check the in-development version before submitting a doc bug. The python.org Mac OS X installers include the complete documentation set for that version in HTML; the IDLE Help menu will open the front page in a browser (from where you can bookmark it for later use). -- Ned Deily, nad at acm.org From riaz.ahmadskh at gmail.com Sat Aug 1 03:02:51 2009 From: riaz.ahmadskh at gmail.com (Riaz Ahmad) Date: Sat, 1 Aug 2009 00:02:51 -0700 (PDT) Subject: "ADMISSION IN FA FSC" "ADMISSION IN FA/FSC" "ADMISSION IN GC UNIVERSITY LAHORE" "ADMISSION IN SCIENCE COLLEGE LAHORE" "ADMISSION IN KIPS LAHORE" "ADMISSION IN LEADERSHIP COLLEGE LAHORE" "ADMISSION IN BAHAUDDIN ZAKARIYA UNIVERSITY MULTAN" Message-ID: <38954c7f-1af5-4739-8982-6193b280d4da@d36g2000prb.googlegroups.com> "ADMISSION IN FA FSC" www.admissionspk.blogspot.com "ADMISSION IN FA/FSC" www.admissionspk.blogspot.com "ADMISSION IN GC UNIVERSITY LAHORE" www.admissionspk.blogspot.com "ADMISSION IN SCIENCE COLLEGE LAHORE" www.admissionspk.blogspot.com "ADMISSION IN KIPS LAHORE" www.admissionspk.blogspot.com "ADMISSION IN LEADERSHIP COLLEGE LAHORE" www.admissionspk.blogspot.com "ADMISSION IN BAHAUDDIN ZAKARIYA UNIVERSITY MULTAN" www.admissionspk.blogspot.com www.admissionspk.blogspot.com From robertrobert93 at yahoo.com Sat Aug 1 03:34:58 2009 From: robertrobert93 at yahoo.com (Robert Robert) Date: Sat, 1 Aug 2009 00:34:58 -0700 (PDT) Subject: fil open close very slow Message-ID: <950181.91001.qm@web59306.mail.re1.yahoo.com> hiya all, I have a "large" script written in python. There is in that big script at a certain point a loop in which I create a lots of simple small text files. Each text file just contain I think 4 or 5 short lines. When I simply run it in IDLE, it runs fast. But when?I compile it to binary files, it becomes very slow. I turned on the profiler and discorvered it was slow at the open() and close() calls. I removed those calls to confirm this, and yes my program runs very fast then. Does anyone has an idea or suggestion why this can be possible. I only compile them to .pyc files, which as what I see, when I normally run in IDLe these files are created as well, so I really got no clue. rh. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Sat Aug 1 03:53:51 2009 From: rt8396 at gmail.com (r) Date: Sat, 1 Aug 2009 00:53:51 -0700 (PDT) Subject: possible to round number and convert to string? References: <24763821.post@talk.nabble.com> <4a737350$0$28514$4fafbaef@reader2.news.tin.it> Message-ID: <4e60ee41-44a2-4e23-b3dd-70a8549026e0@a13g2000yqc.googlegroups.com> On Jul 31, 7:42?pm, "Dr. Phillip M. Feldman" wrote: > This was very close to what I wanted. ?Thanks! ?My final code looks like > this: > > def num2str(x,f=4): > ? ?"""Convert x (int or float) to a string with f digits to right of > ? ?the decimal point. ?f may be zero or negative, in which case the decimal > ? ?point is suppressed.""" > ? ?s= str(round(x,f)) > ? ?if f<=0: > ? ? ? # Delete decimal point: > ? ? ? i= s.find('.') > ? ? ? if i>0: s= s[:i] > ? ?return s Is it *really* necessary to create a named function for something as trivial as this? >>> import math >>> '%0.3f' %math.pi '3.142' >>> '%d' %math.pi '3' Seems string formatting is more "pythonic" -- opps, now why did i have to go and say that... :) From dickinsm at gmail.com Sat Aug 1 04:36:11 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 1 Aug 2009 01:36:11 -0700 (PDT) Subject: possible to round number and convert to string? References: Message-ID: On Jul 31, 11:17?pm, "Dr. Phillip M. Feldman" wrote: > I'd like to be able to convert a float to a string representation in which > the number is rounded to a specified number of digits. ?If num2str is a > hypothetical function that does this, then num2str(pi,3) would be '3.142' > (not '3.141'). Python's string formatting does exactly this. Python 2.6.2 (r262:71600, Jul 8 2009, 09:56:31) [GCC 4.0.1 (Apple Inc. build 5490)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> num2str = '{0:.{1}f}'.format >>> num2str(3.14159, 3) '3.142' (In Python 3.1, num2str = '{:.{}f}'.format is enough.) Mark From john_re at fastmail.us Sat Aug 1 04:52:28 2009 From: john_re at fastmail.us (john_re) Date: Sat, 01 Aug 2009 01:52:28 -0700 Subject: Aug 1 & 16- Global VOIP Free SW HW Culture meeting, BerkeleyTIP, For Forwarding Message-ID: <1249116748.25769.1327808157@webmail.messagingengine.com> Interested in joining the friendly global Free SW HW & Culture communities in a global Voice meeting? You?re invited. :) You can join from your home, or better: get a local meeting together. Tip: a college WiFi cafe could be a great local meeting place. Make sure you have a VOIP headset! For all details, see the website (I?m leaving out many sublinks to make this email smaller). http://sites.google.com/site/berkeleytip Start by joining #berkeleytip on IRC freenode.net. We?ll help you get your VOIP connection working. :) ===== MARK YOUR CALENDARS: 1st Sat & 3rd Sunday each month. August 1 & 16. 10A - 6P Pacific US time (+7H GMT, IIRC) = 1P-9P Eastern US time = 5P - 1A GMT ? Or, come to the local meeting on the UC Berkeley campus. NOTE: SPECIAL LOCATION AUG 1: SEE BTIP WEBSITE FOR LOCATION, & RSVP TO ME OR THE BTIP LISTS. AUG 1 MEETING WILL BE 12N - 3P AT THE BTIP VOIP SERVER LOCATION ON THE UCB CAMPUS. SEE THE WEBSITE FOR ROOM LOCATION. We?ll hack on the new BTIP Asterisk VOIP server, in its presence. PLEASE RSVP TO ME (John) OR THE LIST IF YOU WANT TO MEET AT OUR USUAL LOCATION, THE FREE SPEECH CAFE, 10A-12n, 3-6PM, (otherwise i might not be there). ===== MEETING TOPICS FOR AUGUST: 1) Whatever _you_ want to work on - Email the BTIPGlobal list & let us know what your interests are. 2) Our VOIP conference server, using Asterisk. 3) Planning for year 2. ===== JOIN FOR THE START OF YEAR 2 GLOBAL MEETINGs: We had a great first year. We had local attendees from around the San Francisco Bay Area & Northern California. High School, College, Grad Students, & working & retired people attended. >From the US, people joined the meeting (IRC or VOIP) from Hawaii to Virgina, Washington to Michigan to Florida. (+ California & other states.) Globally, Sweden, Germany, England, Ireland, Iran & India (& maybe others I don?t recall right now.) :) In May Richard Stallman joined the global meeting for Q & A about free SW & HW. == YEAR 2 FOCUS: COLLEGE LOCAL MEETINGS, & AMERICAS? ANNOUNCEMENTS. Two main things I?ll focus on this year: 1) Inviting groups to join at colleges & universities - BTIP is educational. My hope: if more students learn about free SW hw & culture, some of them will then go on to become _contributors_. :) 2) I?ll try to get monthly announcements out to the biggest LUGs in the 10 largest countries in the Americas. == What would _YOU_ like to accomplish this year? Email the BTIP mail list, say ?hi?, tell us about your interests, projects & desires. ===== FOR FORWARDING - You are invited to forward this announcement wherever you think it might be appreciated. From hitechpundir at gmail.com Sat Aug 1 05:22:28 2009 From: hitechpundir at gmail.com (sirjee) Date: Sat, 1 Aug 2009 02:22:28 -0700 (PDT) Subject: problem in event handling on change of variable value. Message-ID: <9c0d7a31-0310-4499-9974-92afc588f315@d15g2000prc.googlegroups.com> hello; i m facing a problem in handling events on change of value of environment variable in a tool CANoe. class CANoeEvents: def OnChange(self,value): print "value of environment variable has changed" def OnOpen(self,App): print "opening Application" App_Event = DispatchWithEvents('CANoe.Application',CANoeEvents) time.sleep(2) App_Event.Open("C:\projectConfig.cfg") # printd "opening Application" and event handled properly. .......(now a code file runs in the canoe in which value of environment variable called dummy is changed during execution. Just like OnOpen; OnChange is defined in specification which should be called on change of environment variable.But it is not happening.) while (): myenvVar = App_Event.Environment.GetVariable("dummy") The VB does it very easily and defines a subroutine called : Sub myenvVar _OnChange(value) print "value of environment variable has changed" End Sub //////////////////////////////////////////////////however the alternative for subroutine for OnOpen in VB (defined below) works fine as shown above in python. Sub AppEvent_OnOpen(App) print "opening Application" End Sub for VB; all this stuff is cake work.... object_eventname subroutine and done.....what in python? From paul at subsignal.org Sat Aug 1 05:28:32 2009 From: paul at subsignal.org (paul) Date: Sat, 01 Aug 2009 11:28:32 +0200 Subject: socket policy flash help In-Reply-To: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> Message-ID: NighterNet schrieb: > I need help on the policy to able to let access to user to the server > once the policy access is finish. I been trying to find a good > example, but I got no luck. Using python version 3.1. > > Here the code I tested but it not working. > > if str(buff) == str("b\'\\x00\'"): > print ('policy FOUND >>> sending...') > rawinput = str(' access-from domain=\"*\" to-ports=\"*\" />') > print (rawinput) > b = bytes ( ord(c) for c in rawinput) > self.sockfd.send(b); And the error is? Doesn't Flash use http as transport? cheers Paul From davea at ieee.org Sat Aug 1 05:52:11 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 01 Aug 2009 05:52:11 -0400 Subject: Newbie Question regarding __init__() In-Reply-To: References: Message-ID: <4A74104B.7080403@ieee.org> Nat Williams wrote: > As MRAB described, ALL instance methods need to accept 'self' as a first > parameter, as that will be passed to them implicitly when they are called. > This includes __init__. The name 'self' is just a commonly accepted > convention for the name of the instance object passed to methods. You don't > have to call it that, but you really should. > > Take a look at http://docs.python.org/tutorial/classes.html#class-objects > It might help shed some light on how methods and instances work. > > One other thing. I'm a little confused by the first line of > dcObject.__init__: > > self.init_Pre() and self.init_Exec() > > I suspect this does not do what you think it does. init_Pre and init_Exec > will both be called by this expression (unless init_Pre throws an exception, > of course). You're not getting anything here that you wouldn't by just > calling each method on a separate line, except just making it harder to > read. > > Read the doc-string for init_Pre() and for init_Exec(). The final version of init_Pre() will return False in some circumstances, and in those circumstances Simon doesn't want init_Exec() to be called. He's deliberately using the short-circuit evaluation of 'and' to accomplish that. > > On Fri, Jul 31, 2009 at 8:53 PM, Simon wrote: > > >> Hi >> >> So should the dcObject class include the "self" as well since I have >> not defined an __init__ method in dcCursor? >> >> Simon >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > Every one of those methods in both of those classes need a "self" first argument. As others have said, all instance methods need a 'self.' From vinay_sajip at yahoo.co.uk Sat Aug 1 05:57:13 2009 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Sat, 1 Aug 2009 02:57:13 -0700 (PDT) Subject: Confused About Python Loggin References: <534A6695-37D9-4200-9872-9E844AE50681@cs.ucl.ac.uk> <14CCA71D-F575-4B8A-8C99-67BDAAC2C6E0@cs.ucl.ac.uk> Message-ID: On Jul 31, 2:04?pm, Jean-Michel Pichavant wrote: > Jannik Sund? wrote: > > Hi all. I think I fixed this problem by setting fileLogger.propagate = > > 0. Otherwise it will propagate up to the root logger, which outputs to > > stdout, as far as I can understand. > > > On 31 Jul 2009, at 01:17, Jannik Sund? wrote: > > >> Dear all, I am quite confused about the Pythonlogging. I have read > >> and re-read the Python documentation for the Pythonloggingmodule > >> and googled, but to no avail. I simply want one logger to log to a > >> file and another logger to log to the console. Neither should log the > >> other's messages. The code below causes fileLogger to log to BOTH a > >> file and the console, how come? It seems to me that a call such as > >> "consoleHandler =logging.StreamHandler()" affects other loggers, > >> which I do not want. Also, if I do not do > >>logging.basicConfig(level=logging.INFO) in one of the classes of my > >> application, theloggingdoes not work. Any ideas how come? > > >> Thanks a lot for any help! :) > > >> fileHandler =logging.FileHandler('../../logs/log.txt') > >> fileLogger =logging.getLogger('TESTHARNESSFILE') > >> fileLogger.addHandler(fileHandler) > >> fileLogger.setLevel(logging.INFO) > >> consoleHandler =logging.StreamHandler() > >> logger =logging.getLogger('TESTHARNESS') > >> logger.addHandler(consoleHandler) > >> logger.setLevel(logging.INFO) > > > --http://mail.python.org/mailman/listinfo/python-list > > Please do not top post :o) > > Are sure you have used the code provided above ? > Loggers only propagate events to its parent. > > fileLogger =logging.getLogger('TESTHARNESSFILE" > logger =logging.getLogger('TESTHARNESS') > Those one have no parent relationship. > > However these one have parent relationship: > fileLogger =logging.getLogger('TESTHARNESS.FILE") # note the dotted name > logger =logging.getLogger('TESTHARNESS') > > Or maybe you have added a handler to the root logger... > > Using the propagate attribute is correct only between 2 loggers that are > meant to be parents. > > JM What you say is true, Jean-Michel, but the OP might be meaning the parent-child relationship both his loggers have with the mother of all loggers - the root logger ;-) Regards, Vinay Sajip From piet at cs.uu.nl Sat Aug 1 07:52:16 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sat, 01 Aug 2009 13:52:16 +0200 Subject: socket policy flash help References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> Message-ID: >>>>> NighterNet (N) wrote: >N> I need help on the policy to able to let access to user to the server >N> once the policy access is finish. I been trying to find a good >N> example, but I got no luck. Using python version 3.1. >N> Here the code I tested but it not working. >N> if str(buff) == str("b\'\\x00\'"): What is buff supposed to contain here? I assume a byte sequence? Do you reaaly mean that buff[0] contains the byte 'b' and buff[1] contains a single quote? And the last byte also a single quote? And the four bytes with \ x 0 0 before that instead of a null byte? In total 29 bytes? Or did you mean just the 23 bytes long b'\x00'? Maybe it should be if buff == b'\x00': >N> print ('policy FOUND >>> sending...') >N> rawinput = str('') The str here is unnecessary as you have already a string. >N> print (rawinput) >N> b = bytes ( ord(c) for c in rawinput) Why not b = b'' ? >N> self.sockfd.send(b); -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From tarundevnani at gmail.com Sat Aug 1 09:32:53 2009 From: tarundevnani at gmail.com (tarun) Date: Sat, 1 Aug 2009 19:02:53 +0530 Subject: How to read webpage Message-ID: Dear All,I want to read a webpage and copy the contents of it in word file. I tried to write following code: import urllib2 urllib2.urlopen("http://www.rediff .com/") *Error:-* urllib2.urlopen("http://www.icicibank.com/") File "C:\Python25\lib\urllib2.py", line 121, in urlopen return _opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 374, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 392, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 353, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1100, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python25\lib\urllib2.py", line 1075, in do_open raise URLError(err) urllib2.URLError: -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sat Aug 1 09:52:17 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 01 Aug 2009 14:52:17 +0100 Subject: How to read webpage In-Reply-To: References: Message-ID: <4A744891.7050808@mrabarnett.plus.com> tarun wrote: > Dear All, > I want to read a webpage and copy the contents of it in word file. I > tried to write following code: > > import urllib2 > urllib2.urlopen("http://www.rediff.com/") > > *Error:-* > > urllib2.urlopen("http://www.icicibank.com/") > File "C:\Python25\lib\urllib2.py", line 121, in urlopen > return _opener.open(url, data) > File "C:\Python25\lib\urllib2.py", line 374, in open > response = self._open(req, data) > File "C:\Python25\lib\urllib2.py", line 392, in _open > '_open', req) > File "C:\Python25\lib\urllib2.py", line 353, in _call_chain > result = func(*args) > File "C:\Python25\lib\urllib2.py", line 1100, in http_open > return self.do_open(httplib.HTTPConnection, req) > File "C:\Python25\lib\urllib2.py", line 1075, in do_open > raise URLError(err) > urllib2.URLError: > I've just tried it. I didn't get an exception, so your problem must be elsewhere. From koranthala at gmail.com Sat Aug 1 11:19:28 2009 From: koranthala at gmail.com (koranthala) Date: Sat, 1 Aug 2009 08:19:28 -0700 (PDT) Subject: How to read webpage References: Message-ID: <67de4ef0-0da7-47e6-8e2e-23be4a6b452c@t11g2000prh.googlegroups.com> On Aug 1, 6:52?pm, MRAB wrote: > tarun wrote: > > Dear All, > > I want to read a webpage and copy the contents of it in word file. I > > tried to write following code: > > > import urllib2 > > urllib2.urlopen("http://www.rediff.com/") > > > *Error:-* > > > ? ? urllib2.urlopen("http://www.icicibank.com/") > > ? File "C:\Python25\lib\urllib2.py", line 121, in urlopen > > ? ? return _opener.open(url, data) > > ? File "C:\Python25\lib\urllib2.py", line 374, in open > > ? ? response = self._open(req, data) > > ? File "C:\Python25\lib\urllib2.py", line 392, in _open > > ? ? '_open', req) > > ? File "C:\Python25\lib\urllib2.py", line 353, in _call_chain > > ? ? result = func(*args) > > ? File "C:\Python25\lib\urllib2.py", line 1100, in http_open > > ? ? return self.do_open(httplib.HTTPConnection, req) > > ? File "C:\Python25\lib\urllib2.py", line 1075, in do_open > > ? ? raise URLError(err) > > urllib2.URLError: > > I've just tried it. I didn't get an exception, so your problem must be > elsewhere. Is it that the website expects a valid browser? In that case, spoof a browser and try to get the site. From joncle at googlemail.com Sat Aug 1 11:31:09 2009 From: joncle at googlemail.com (Jon Clements) Date: Sat, 1 Aug 2009 08:31:09 -0700 (PDT) Subject: How to read webpage References: Message-ID: <7690d42e-ea99-4aec-9029-5cfae119ffcf@o32g2000yqm.googlegroups.com> On 1 Aug, 14:52, MRAB wrote: > tarun wrote: > > Dear All, > > I want to read a webpage and copy the contents of it in word file. I > > tried to write following code: > > > import urllib2 > > urllib2.urlopen("http://www.rediff.com/") > > > *Error:-* > > > ? ? urllib2.urlopen("http://www.icicibank.com/") > > ? File "C:\Python25\lib\urllib2.py", line 121, in urlopen > > ? ? return _opener.open(url, data) > > ? File "C:\Python25\lib\urllib2.py", line 374, in open > > ? ? response = self._open(req, data) > > ? File "C:\Python25\lib\urllib2.py", line 392, in _open > > ? ? '_open', req) > > ? File "C:\Python25\lib\urllib2.py", line 353, in _call_chain > > ? ? result = func(*args) > > ? File "C:\Python25\lib\urllib2.py", line 1100, in http_open > > ? ? return self.do_open(httplib.HTTPConnection, req) > > ? File "C:\Python25\lib\urllib2.py", line 1075, in do_open > > ? ? raise URLError(err) > > urllib2.URLError: > > I've just tried it. I didn't get an exception, so your problem must be > elsewhere. I'm hoping this adds to MRAB's reply; it is intended however for the OP. Jeeze -- been a while since I've had to deal with Sockets (directly anyway). If memory serves correctly, it's where the system can't name resolve the required address. So best guess is it's either a temporary glitch, or an issue with your routing. Jon. Jon. From darkneter at gmail.com Sat Aug 1 11:34:57 2009 From: darkneter at gmail.com (NighterNet) Date: Sat, 1 Aug 2009 08:34:57 -0700 (PDT) Subject: socket policy flash help References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> Message-ID: <8bede581-f260-4c69-abf0-1e8071380b76@z4g2000prh.googlegroups.com> On Aug 1, 4:52?am, Piet van Oostrum wrote: > >>>>> NighterNet (N) wrote: > >N> I need help on the policy to able to let access to user to the server > >N> once the policy access is finish. I been trying to find a good > >N> example, but I got no luck. Using python version 3.1. > >N> Here the code I tested but it not working. > >N> if str(buff) == str("b\'\\x00\'"): > > What is buff supposed to contain here? I assume a byte sequence? > Do you reaaly mean that buff[0] contains the byte 'b' and buff[1] > contains a single quote? And the last byte also a single quote? And the > four bytes with \ x 0 0 before that instead of a null byte? In total 29 bytes? > > Or did you mean just the 23 bytes long b'\x00'? > > Maybe it should be if buff == b'\x00': > > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print ('policy FOUND >>> sending...') > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? rawinput = str('') > > The str here is unnecessary as you have already a string. > > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print (rawinput) > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? b = bytes ( ord(c) for c in rawinput) > > Why not > b = b'' ? > > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.sockfd.send(b); > > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org I try that method and flash socket is not getting the policy. b = b'' self.sockfd.send(b); server = socket.socket( socket.AF_INET, socket.SOCK_STREAM) When it able to read the policy it send it but it fail to send to flash some reason and send it again and then d/c. From marcusw at cox.net Sat Aug 1 11:43:15 2009 From: marcusw at cox.net (Marcus Wanner) Date: Sat, 01 Aug 2009 11:43:15 -0400 Subject: How to read webpage In-Reply-To: <7690d42e-ea99-4aec-9029-5cfae119ffcf@o32g2000yqm.googlegroups.com> References: <7690d42e-ea99-4aec-9029-5cfae119ffcf@o32g2000yqm.googlegroups.com> Message-ID: On 8/1/2009 11:31 AM, Jon Clements wrote: > On 1 Aug, 14:52, MRAB wrote: >> tarun wrote: >>> Dear All, >>> I want to read a webpage and copy the contents of it in word file. I >>> tried to write following code: >>> import urllib2 >>> urllib2.urlopen("http://www.rediff.com/") >>> *Error:-* >>> urllib2.urlopen("http://www.icicibank.com/") >>> File "C:\Python25\lib\urllib2.py", line 121, in urlopen >>> return _opener.open(url, data) >>> File "C:\Python25\lib\urllib2.py", line 374, in open >>> response = self._open(req, data) >>> File "C:\Python25\lib\urllib2.py", line 392, in _open >>> '_open', req) >>> File "C:\Python25\lib\urllib2.py", line 353, in _call_chain >>> result = func(*args) >>> File "C:\Python25\lib\urllib2.py", line 1100, in http_open >>> return self.do_open(httplib.HTTPConnection, req) >>> File "C:\Python25\lib\urllib2.py", line 1075, in do_open >>> raise URLError(err) >>> urllib2.URLError: >> I've just tried it. I didn't get an exception, so your problem must be >> elsewhere. > > I'm hoping this adds to MRAB's reply; it is intended however for the > OP. > > Jeeze -- been a while since I've had to deal with Sockets (directly > anyway). > If memory serves correctly, it's where the system can't name resolve > the required address. > So best guess is it's either a temporary glitch, or an issue with your > routing. > > Jon. > Jon. 'getaddrinfo failed' means that the nameserver can't be found, or that it has no records of that address (I'm 90% sure of that). Marcus From nobody at nowhere.com Sat Aug 1 13:11:18 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 01 Aug 2009 18:11:18 +0100 Subject: Python docs disappointing References: Message-ID: On Fri, 31 Jul 2009 20:10:45 +0000, kj wrote: > I'm pretty new to Python, and I like a lot overall, but I find the > documentation for Python rather poor, overall. FWIW, I find the module documentation to be mostly adequate. What's missing is a human-readable language *manual*. The tutorial omits too much; the language reference may be fine for language lawyering, but it's not much use otherwise. From MatzeGuentert at gmx.de Sat Aug 1 13:16:14 2009 From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=) Date: Sat, 01 Aug 2009 19:16:14 +0200 Subject: M2Crypto: AttributeError: 'CSR' object has no attribute 'pkey' Message-ID: <1249146974.3330.1.camel@celsius> Hello python-guys I am trying to build a python based certificate authority using m2crypto. I am quite new to python and I am asking myself why my code snippets below throw the following Traceback: $ python csr.py ...++++++++++++ ...............++++++++++++ Traceback (most recent call last): File "csr.py", line 48, in csr.create_cert_signing_request(pubkey, cert_name) File "csr.py", line 17, in create_cert_signing_request cert_request.set_pubkey(keypair) File "/usr/lib64/python2.6/site-packages/M2Crypto/X509.py", line 926, in set_pubkey return m2.x509_req_set_pubkey( self.req, pkey.pkey ) AttributeError: 'CSR' object has no attribute 'pkey' Bellow are my modules containing two classes CSR and Keypair. There seems to be something wrong in the way I am calling csr.create_cert_signing_request(), because if I directly add the key generation part to the create_cert_singing_request function it works... http://www.heikkitoivonen.net/m2crypto/api/M2Crypto.X509.Request-class.html#set_pubkey This link states out, that the instance function set_pubkey takes an EVP_KEY object as argument, and thats what I am passing to it, or not? I really would be happy if someone could give me a helping hand on this and maybe could comment every style / ... mistake I made to accelerate my learning experience. Thanks, Matthias $ cat csr.py from config import * from keypair import * from M2Crypto import X509, EVP class CSR(object): def __init__(self): pass def create_cert_signing_request(keypair, cert_name, cert_extension_stack=None): # create a certificate signing request object cert_request = X509.Request() # set certificate version to 3 cert_request.set_version(3) # which rsa public key should be used? cert_request.set_pubkey(keypair) # create an subject for the certificate request cert_request.set_subject_name(cert_name) if cert_extension_stack != None: # add the extensions to the request cert_request.add_extensions(cert_extension_stack) # sign the request using the RSA key pair cert_request.sign(keypair, 'sha1') return cert_request if __name__ == "__main__": csr = CSR() cert_name = X509.X509_Name() keyp = Keypair() keyp.create_keypair() keyp.save_keypair("host.key") pubkey = keyp.get_keypair() cert_name.C = "GB" cert_name.ST = "Greater Manchester" cert_name.L = "Salford" cert_name.O = "COMODO CA Limited" cert_name.CN = "COMODO Certification Authority" cert_name.OU = "Information Technology" cert_name.Email = "contact at comodo.com" csr.create_cert_signing_request(pubkey, cert_name) $ cat keypair.py from M2Crypto import X509, m2, RSA, EVP from config import * class Keypair(object): def __init__(self): self.config = Config() self.keypair = EVP.PKey() def create_keypair(self): # generate an RSA key pair # OpenSSL book page 232 # second argument should be a constant RSA_F4 or RSA_3 rsa_key_pair = RSA.gen_key(int(self.config.get_attribute('CA','key_size')), m2.RSA_F4) # check if RSA key pair is usable # OpenSSL book page 232 if rsa_key_pair.check_key() != 1: print 'error while generating key!' sys.exit() # EVP object which can hold either a DSA or an RSA object # OpenSSL book page 236 evp_key_container = EVP.PKey() evp_key_container.assign_rsa(rsa_key_pair) self.keypair = evp_key_container def save_keypair(self, filename): self.keypair.save_key(filename, None) def load_keypair(self, filename): self.keypair = EVP.load_key(filename) def get_keypair(self): return self.keypair def get_public_key(self): return self.keypair.pkey def print_keypair(self): print self.keypair.as_pem(None) if __name__ == "__main__": key = Keypair() key.create_keypair() key.save_keypair("test.key") print key.get_keypair() print key.get_public_key() From enleverLesX_XXmcX at XmclavXeauX.com Sat Aug 1 13:20:35 2009 From: enleverLesX_XXmcX at XmclavXeauX.com (Michel Claveau - MVP) Date: Sat, 01 Aug 2009 19:20:35 +0200 Subject: os.path.exists() and Samba shares References: Message-ID: <4a747965$0$23487$ba4acef3@news.orange.fr> Hi! > SAMBA is a Linux implementation of the SMB protocol, natively supported on Windows. Right. But, with Vista or Seven, only recents releases of Samba are supported. And, Samba know only NTLM release 2 (in register: HKLM\SYSTEM\CurrentControlSet\Control\Lsa value LMCompatibilityLevel ; set 1 or 0. ) @-salutations -- Michel Claveau From justindecell at gmail.com Sat Aug 1 14:07:15 2009 From: justindecell at gmail.com (Justin DeCell) Date: Sat, 1 Aug 2009 11:07:15 -0700 Subject: Queryable Daemon Message-ID: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> Hi All, I was hoping for a little help with a project I'm working on. I'm writing a daemon in python that I want to be queryable (i.e. I should be able to run foo -s and it will report some internal information about the foo daemon if it's running) but I can't figure out a way get information from that process from an external process. I was thinking that there should be a way to open a file descriptor, have the daemon write to that every so often and then have the query process just read from that fd but it looks like on the process reading from an fd has to be a child of the daemon for this to work. The only other way I thought of would be to write to a file on disk every so often from the daemon and just read the from the query process but it seems like there should be a more elegant way to do this... By the way I'm writing this for unix only so there's no need to worry about compatibility with other os'. Thanks, -Justin -------------- next part -------------- An HTML attachment was scrubbed... URL: From luke.leighton at googlemail.com Sat Aug 1 14:07:51 2009 From: luke.leighton at googlemail.com (lkcl) Date: Sat, 1 Aug 2009 11:07:51 -0700 (PDT) Subject: JavaScript toolkits (was Re: ANN: Porcupine Web Application Server 0.6 is released!) References: Message-ID: <01133210-f03b-4a71-aa9e-d69fe44ac9a5@r38g2000yqn.googlegroups.com> On Jul 20, 4:00 pm, a... at pythoncraft.com (Aahz) wrote: > Out of curiosity, are there anyJavaScripttoolkits or python-to-javascript compilers > that generate code > that degrades gracefully whenJavaScriptis disabled? http://advogato.org/article/981.html you'll need to do a little bit of work - use a state-machine-based framework (such as twisted, from what i can gather), or use fastcgi, or solve the problem of storing the state of the pyjamas application "in between" web requests - but yes, pyjamas-web is a port of pyjamas to the web server. so, by writing an app that conforms to the pyjamas API, you get to compile it to native javascript, to run in the web browser; you get to run it as pure python using pyjamas-desktop (python-hulahop underneath or pywebkitgtk) and then, if you want to finish off the experiment that i started, you get to run the _same_ python app server-side on behalf of the users. all quite quite mad, to be honest :) l. From luke.leighton at googlemail.com Sat Aug 1 14:11:02 2009 From: luke.leighton at googlemail.com (lkcl) Date: Sat, 1 Aug 2009 11:11:02 -0700 (PDT) Subject: JavaScript toolkits (was Re: ANN: Porcupine Web Application Server 0.6 is released!) References: <1c994086-8c58-488f-b3b3-6161c4b2ba05@k30g2000yqf.googlegroups.com> Message-ID: <2a2f05af-a87e-44bf-8d36-774697dbd794@c29g2000yqd.googlegroups.com> On Jul 21, 12:55 pm, Paul Boddie wrote: > On 20 Jul, 18:00, a... at pythoncraft.com (Aahz) wrote: > > > > > Out of curiosity, are there anyJavaScripttoolkits that generate code > > that degrades gracefully whenJavaScriptis disabled? > > You mean "Web toolkits which useJavaScript", I presume. I have > written (and use myself) a toolkit/framework called XSLForms (part of > the XSLTools distribution) which supports in-page updates (AJAX, > effectively) that degrade to vanilla whole-page requests ifJavaScript > is switched off: yeahhh.... i remember doing something like that. each portion of the page i did as a separate AJAX load, and then there was some loader- infrastructure where you could, if javascript was switched off, do a tree-walk-reconstruction of the page. if anyone's interested i can provide source code. l. From hjtoi-better-remove-before-reply at comcast.net Sat Aug 1 14:19:13 2009 From: hjtoi-better-remove-before-reply at comcast.net (Heikki Toivonen) Date: Sat, 01 Aug 2009 11:19:13 -0700 Subject: M2Crypto: AttributeError: 'CSR' object has no attribute 'pkey' References: Message-ID: Matthias G?ntert wrote: > class CSR(object): > def __init__(self): > pass > > def create_cert_signing_request(keypair, cert_name, > cert_extension_stack=None): You missed self. Although this method does not seem to be using any instance data so there isn't actually much reason to have a CSR object unless you intend to expand it in ways that require it. > if cert_extension_stack != None: A word of advice: always check equality/inequality to None with 'is', because that way it is a straight pointer conversion which is faster and won't cause any surprises. In other words, write the above as: if cert_extension_stack is not None: -- Heikki Toivonen - http://heikkitoivonen.net From jkn_gg at nicorp.f9.co.uk Sat Aug 1 15:01:32 2009 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Sat, 1 Aug 2009 12:01:32 -0700 (PDT) Subject: Python docs disappointing References: <4A73AAE3.1050209@tim.thechases.com> Message-ID: On Aug 1, 4:18?am, Terry Reedy wrote: > This is one area where Windows users seems to have an advantage. The > standard installer includes the doc set as a Windows help file. I often > keep that open in one window while programming in others. I only later > discovered that this was a copy of the online docs ;-), which I only use > to check the in-development version before submitting a doc bug. The ActiveState distribution also includes the doc set as a CHM file (the canonical version didn't used to; one reason why I've used ActiveState in the past). I run a dual-boot system and have used a CHM (Windows Compiled help file format) viewer under Linux to read the Windows help file. This has been pretty handy in the past. Unfortunately, the combination of the python 2.6 CHM helpfile style, and the KChmViewer application gives me body text which is almost unreadable (black text on dark blue background). I'm not sure if this a bug in KChmViewer but it's pretty annoying. Anyone else see this? J^n From python at mrabarnett.plus.com Sat Aug 1 15:32:21 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 01 Aug 2009 20:32:21 +0100 Subject: Queryable Daemon In-Reply-To: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> References: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> Message-ID: <4A749845.4020208@mrabarnett.plus.com> Justin DeCell wrote: > Hi All, > > I was hoping for a little help with a project I'm working on. I'm > writing a daemon in python that I want to be queryable (i.e. I should > be able to run foo -s and it will report some internal information about > the foo daemon if it's running) but I can't figure out a way get > information from that process from an external process. I was thinking > that there should be a way to open a file descriptor, have the daemon > write to that every so often and then have the query process just read > from that fd but it looks like on the process reading from an fd has to > be a child of the daemon for this to work. The only other way I thought > of would be to write to a file on disk every so often from the daemon > and just read the from the query process but it seems like there should > be a more elegant way to do this... > > By the way I'm writing this for unix only so there's no need to worry > about compatibility with other os'. > Instead of a file descriptor, how about a socket? A certain port at "127.0.0.1"? From mail at timgolden.me.uk Sat Aug 1 15:32:31 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 01 Aug 2009 20:32:31 +0100 Subject: Python docs disappointing In-Reply-To: References: <4A73AAE3.1050209@tim.thechases.com> Message-ID: <4A74984F.9010805@timgolden.me.uk> jkn wrote: > The ActiveState distribution also includes the doc set as a CHM file > (the canonical version didn't used to; one reason why I've used > ActiveState in the past). It has done for quite some while now: Python 2.3 was the first and that was released, what, six years ago. Still, you're right; it used to use plain HTML. > Unfortunately, the combination of the python 2.6 CHM helpfile style, > and the KChmViewer application gives me body text which is almost > unreadable (black text on dark blue background). I'm not sure if this > a bug in KChmViewer but it's pretty annoying. Anyone else see this? This was noised about when the new-style docs were first released. Somehow (I don't run Linux usually) I had the impression it had been fixed; presumably not. However, rebuilding the docs is not at all hard: you just need a Python installation and the HTMLHelp Workshop. Then you can fiddle about with the CSS to your heart's content. TJG From geomajor56 at gmail.com Sat Aug 1 15:39:12 2009 From: geomajor56 at gmail.com (Michael Savarese) Date: Sat, 1 Aug 2009 15:39:12 -0400 Subject: iterate lines with regex Message-ID: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> I'm a python newbie and I'm trying to test several regular expressions on the same line before moving on to next line. it seems to move on to next line before trying all regular expressions which is my goal. it only returns true for first regular expression does the curser have to be rest to beginning of line? If so, how would I do that. remember I'm new thanks in advance to any advice Mike S. the following is part of my code, readThis=open('c:/9320.txt','r') for line in readThis: try: thisKey = key.search(line).group(1) thisMap = map.search(line).group(1) thisParcel = parcel.search(line).group(1) except: continue -------------- next part -------------- An HTML attachment was scrubbed... URL: From jkn_gg at nicorp.f9.co.uk Sat Aug 1 15:44:14 2009 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Sat, 1 Aug 2009 12:44:14 -0700 (PDT) Subject: Python docs disappointing References: <4A73AAE3.1050209@tim.thechases.com> Message-ID: Hi Tim On Aug 1, 8:32?pm, Tim Golden wrote: > > > Unfortunately, the combination of the python 2.6 CHM helpfile style, > > and the KChmViewer application gives me body text which is almost > > unreadable (black text on dark blue background). I'm not sure if this > > a bug in KChmViewer but it's pretty annoying. Anyone else see this? > > This was noised about when the new-style docs were first released. > Somehow (I don't run Linux usually) I had the impression it had > been fixed; presumably not. However, rebuilding the docs is not > at all hard: you just need a Python installation and the > HTMLHelp Workshop. Then you can fiddle about with the CSS to > your heart's content. > The HTML form of the documents (on python.org) seem fine (dark text on a light background, with a 'light blue on dark blue' sidebar). I was guessing that the .CHM was intended to have the same style, and therefore there was a problem with either my viwer, or with the conversion. Is this not the case then? I've just checked using xchm, and this displays OK - but I don't think it's taking any notice of any styles. FWIW I'm running 4.0-r1; there is a later release but it's not yet available for my Gentoo distribution. Can you point me at any references to this bug in the Python release world please? Thanks J^n From jkn_gg at nicorp.f9.co.uk Sat Aug 1 15:47:50 2009 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Sat, 1 Aug 2009 12:47:50 -0700 (PDT) Subject: Python docs disappointing References: <4A73AAE3.1050209@tim.thechases.com> Message-ID: <5cdcdc4a-5dd5-4c0a-a7cd-cdd078f8c262@a13g2000yqc.googlegroups.com> update: if I set 'use KHTMLPart-based widget' instead of 'QTextBrowser- based Widget' to display HTML content in the application settings of KchmViewer, all is readable. Hurrah! I wonder if it is picing up some QT stylesheet I have lying around in an over-clever way... J^n From ml at well-adjusted.de Sat Aug 1 15:55:31 2009 From: ml at well-adjusted.de (Jochen Schulz) Date: Sat, 1 Aug 2009 21:55:31 +0200 Subject: iterate lines with regex In-Reply-To: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> Message-ID: <20090801195531.GH15902@wasteland.homelinux.net> Michael Savarese: > > for line in readThis: > try: > thisKey = key.search(line).group(1) > thisMap = map.search(line).group(1) > thisParcel = parcel.search(line).group(1) > except: > continue Why do you catch all exceptions in that loop? Remove the try-except clause including the 'continue' and a stacktrace will probybably tell you why your loop appears to do nothing. J. -- A passionate argument means more to me than a blockbuster movie. [Agree] [Disagree] -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 204 bytes Desc: Digital signature URL: From breamoreboy at yahoo.co.uk Sat Aug 1 16:08:14 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 01 Aug 2009 21:08:14 +0100 Subject: iterate lines with regex In-Reply-To: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> Message-ID: Michael Savarese wrote: > I'm a python newbie and I'm trying to test several regular expressions on > the same line before moving on to next line. > it seems to move on to next line before trying all regular expressions which > is my goal. > it only returns true for first regular expression > does the curser have to be rest to beginning of line? If so, how would I do > that. > remember I'm new > thanks in advance to any advice > Mike S. > > the following is part of my code, > readThis=open('c:/9320.txt','r') > > for line in readThis: > try: > thisKey = key.search(line).group(1) > thisMap = map.search(line).group(1) > thisParcel = parcel.search(line).group(1) > except: > continue > > The bare except will hide any errors in the lines above it. Either catch errors that you expect or take the try-except out. -- Kindest regards. Mark Lawrence. From workitharder at gmail.com Sat Aug 1 16:42:16 2009 From: workitharder at gmail.com (Buck) Date: Sat, 1 Aug 2009 13:42:16 -0700 (PDT) Subject: Module updating plans for Python 3.1: feedparser, MySQLdb References: <4a739a96$0$1615$742ec2ed@news.sonic.net> Message-ID: I use MySQLdb quite a bit in my work. I could volunteer to help update it. Are there any particular bugs we're talking about or just a straight port to 3.0? --Buck On Jul 31, 6:32?pm, John Nagle wrote: > ? ? Any progress on updating feedparser and MySQLdb for Python 3.x in the > foreseeable future? > > ? ? Feedparser shouldn't be that hard; it's just that nobody is working on it. > MySQLdb is known to be hard, and that may be a while. > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle From garabik-news-2005-05 at kassiopeia.juls.savba.sk Sat Aug 1 17:14:59 2009 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Sat, 1 Aug 2009 21:14:59 +0000 (UTC) Subject: Queryable Daemon References: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> Message-ID: MRAB wrote: > Justin DeCell wrote: >> Hi All, >> ... >> The only other way I thought >> of would be to write to a file on disk every so often from the daemon >> and just read the from the query process but it seems like there should >> be a more elegant way to do this... >> >> By the way I'm writing this for unix only so there's no need to worry >> about compatibility with other os'. >> > Instead of a file descriptor, how about a socket? A certain port at > "127.0.0.1"? Or a Unix domain socket. Or let the demon catch signal, say SIGUSR1 and dump its state to a file. A bit easier programming that a socket, a bit less elegant. -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.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 saimapk81 at gmail.com Sat Aug 1 17:29:25 2009 From: saimapk81 at gmail.com (saima81) Date: Sat, 1 Aug 2009 14:29:25 -0700 (PDT) Subject: "PAK WEB PAGES" "PAK WEB SITES" "PAK WEB PAGES" "PAK WEB SITES" "PAK WEB PAGES" "PAK WEB SITES" ON www.pak-web-pages.blogspot.com Message-ID: "PAK WEB PAGES" www.pak-web-pages.blogspot.com "PAK WEB SITES" www.pak-web-pages.blogspot.com "PAK WEB PAGES" www.pak-web-pages.blogspot.com "PAK WEB SITES" www.pak-web-pages.blogspot.com "PAK WEB PAGES" www.pak-web-pages.blogspot.com "PAK WEB SITES" www.pak-web-pages.blogspot.com ON www.pak-web-pages.blogspot.com www.pak-web-pages.blogspot.com From michael at altra-optics.co.uk Sat Aug 1 17:58:53 2009 From: michael at altra-optics.co.uk (Michael M Mason) Date: Sat, 1 Aug 2009 22:58:53 +0100 Subject: Newbie thwarted by sys.path on Vista Message-ID: <7djs50F2bsubuU1@mid.individual.net> I'm running Python 3.1 on Vista and I can't figure out how to add my own directory to sys.path. The docs suggest that I can either add it to the PYTHONPATH environment variable or to the PythonPath key in the registry. However, PYTHONPATH doesn't exist, and updating the registry key has no effect (and in any case the contents aren't the same as sys.path). So where does sys.path get its value from, and how do I change it? -- Michael From nytrokiss at gmail.com Sat Aug 1 19:01:45 2009 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 2 Aug 2009 02:01:45 +0300 Subject: How to read webpage In-Reply-To: References: <7690d42e-ea99-4aec-9029-5cfae119ffcf@o32g2000yqm.googlegroups.com> Message-ID: <8a6b8e350908011601v4d2ab86bp5618c6171cfb9a98@mail.gmail.com> Check your connection to the internet. On Sat, Aug 1, 2009 at 6:43 PM, Marcus Wanner wrote: > On 8/1/2009 11:31 AM, Jon Clements wrote: > >> On 1 Aug, 14:52, MRAB wrote: >> >>> tarun wrote: >>> >>>> Dear All, >>>> I want to read a webpage and copy the contents of it in word file. I >>>> tried to write following code: >>>> import urllib2 >>>> urllib2.urlopen("http://www.rediff.com/") >>>> *Error:-* >>>> urllib2.urlopen("http://www.icicibank.com/") >>>> File "C:\Python25\lib\urllib2.py", line 121, in urlopen >>>> return _opener.open(url, data) >>>> File "C:\Python25\lib\urllib2.py", line 374, in open >>>> response = self._open(req, data) >>>> File "C:\Python25\lib\urllib2.py", line 392, in _open >>>> '_open', req) >>>> File "C:\Python25\lib\urllib2.py", line 353, in _call_chain >>>> result = func(*args) >>>> File "C:\Python25\lib\urllib2.py", line 1100, in http_open >>>> return self.do_open(httplib.HTTPConnection, req) >>>> File "C:\Python25\lib\urllib2.py", line 1075, in do_open >>>> raise URLError(err) >>>> urllib2.URLError: >>>> >>> I've just tried it. I didn't get an exception, so your problem must be >>> elsewhere. >>> >> >> I'm hoping this adds to MRAB's reply; it is intended however for the >> OP. >> >> Jeeze -- been a while since I've had to deal with Sockets (directly >> anyway). >> If memory serves correctly, it's where the system can't name resolve >> the required address. >> So best guess is it's either a temporary glitch, or an issue with your >> routing. >> >> Jon. >> Jon. >> > > 'getaddrinfo failed' means that the nameserver can't be found, or that it > has no records of that address (I'm 90% sure of that). > > Marcus > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From luke.leighton at googlemail.com Sat Aug 1 19:19:55 2009 From: luke.leighton at googlemail.com (lkcl) Date: Sat, 1 Aug 2009 16:19:55 -0700 (PDT) Subject: Calling functions: Why this complicated ? References: <89dd3da60907141340i46a6d913mb333788e85507128@mail.gmail.com> Message-ID: <5e089462-dbc1-4764-a57c-86c94cb0ae14@u16g2000yqe.googlegroups.com> On Jul 14, 11:31 pm, Chris Rebert wrote: > On Tue, Jul 14, 2009 at 1:40 PM, Mohan Parthasarathy wrote: > > Hi, > > I am a newbie. I am reading > >http://www.network-theory.co.uk/docs/pytut/KeywordArguments.html > > Defining a function with "N" arguments and calling them in "M" different > > ways. Why does it have to be this complicated ? I like the idea of calling > > the function by explicitly naming the arguments, but there are so many other > > ways here that is very confusing. Do people really use all these features ? > > Perhaps, there is a equivalent book to "Javascript: Good Parts" for Python ? > > Oh $DEITY, don't even compare Python toJavaScript. At least in > Python, when you try to access a non-existent attribute, a proper > NameError exception is thrown rather than silently getting back > "undefined"... (*has traumatic horror story flashback*) yehh, that's what i thought, originally, but after talking it over with the people doing the EMCAScript Harmony spec, they explained that nooo, there _are_ exceptions thrown (two if the browser implements it properly, which IE of course doesn't). you can try it by installing the spidermonkey js compiler, which is the exact same js engine that's in firefox. in the python-to-javascript compiler, http://pyjs.org, however, we've taken to adding a double-check (the equivalent of getattr) when you specify the --strict option, juuust to make sure. and yes, there was a talk at europython 2009, pretty much called "javascript, the good parts, for python programmers", you can look it up, the talk audio is online by now. http://europython.eu l. From joncle at googlemail.com Sat Aug 1 19:32:21 2009 From: joncle at googlemail.com (Jon Clements) Date: Sat, 1 Aug 2009 16:32:21 -0700 (PDT) Subject: Newbie thwarted by sys.path on Vista References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: <105eaa91-e751-4b25-a2c9-94cd075b60c7@s15g2000yqs.googlegroups.com> On 1 Aug, 22:58, "Michael M Mason" wrote: > I'm running Python 3.1 on Vista and I can't figure out how to add my own > directory to ?sys.path. > > The docs suggest that I can either add it to the PYTHONPATH environment > variable or to the PythonPath key in the registry. ?However, PYTHONPATH > doesn't exist, and updating the registry key has no effect (and in any case > the contents aren't the same as sys.path). > > So where does sys.path get its value from, and how do I change it? > > -- > Michael sys.path is just a list. So in your 'main' module where you do most of your imports, just append or prepend the path you desire (the search order is left to right). Although, I believe under Windows creating a system level or user level PYTHONPATH environment variable will enable Windows to pick it up. Not 100% sure as I don't have a Windows machine handy. From piet at cs.uu.nl Sat Aug 1 19:36:18 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 02 Aug 2009 01:36:18 +0200 Subject: Newbie thwarted by sys.path on Vista References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: >>>>> "Michael M Mason" (MMM) wrote: >MMM> I'm running Python 3.1 on Vista and I can't figure out how to add my own >MMM> directory to sys.path. >MMM> The docs suggest that I can either add it to the PYTHONPATH environment >MMM> variable or to the PythonPath key in the registry. However, PYTHONPATH >MMM> doesn't exist, Then create it. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From aahz at pythoncraft.com Sat Aug 1 19:36:58 2009 From: aahz at pythoncraft.com (Aahz) Date: 1 Aug 2009 16:36:58 -0700 Subject: string.Template issue References: Message-ID: In article , Javier Collado wrote: > >In the string.Template documentation >(http://docs.python.org/library/string.html) it's explained that if a >custom regular expression for pattern substitution is needed, it's >possible to override idpattern class attribute (whose default value is >[_a-z][_a-z0-9]*). > >However, if the custom pattern that is needed is just uppercase >letters something like [A-Z]+ won't work because of the following line >in the _TemplateMetaclass class __init__ method: >cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) > >I would say that this is an error (IGNORECASE just shouldn't be there) Good point! I don't have an answer for you, but please file a report at bugs.python.org to make sure it doesn't get lost. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Many customs in this life persist because they ease friction and promote productivity as a result of universal agreement, and whether they are precisely the optimal choices is much less important." --Henry Spencer From david.lyon at preisshare.net Sat Aug 1 20:26:19 2009 From: david.lyon at preisshare.net (David Lyon) Date: Sat, 01 Aug 2009 20:26:19 -0400 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: <7djs50F2bsubuU1@mid.individual.net> References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: <73ddb9b5d0110a42e2831eb6c150d2a8@preisshare.net> On Sat, 1 Aug 2009 22:58:53 +0100, "Michael M Mason" wrote: > I'm running Python 3.1 on Vista and I can't figure out how to add my own > directory to sys.path. > > The docs suggest that I can either add it to the PYTHONPATH environment > variable or to the PythonPath key in the registry. However, PYTHONPATH > doesn't exist, and updating the registry key has no effect > > So where does sys.path get its value from, and how do I change it? The simplest hack (worst - but most direct) is that sys.path is a list and you can use it like any other list. (add, delete, change items in it) It gets loaded from site.py (in the standardard library) at startup. Anything else you'll have to ask somebody else. David From davea at ieee.org Sat Aug 1 20:29:12 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 01 Aug 2009 20:29:12 -0400 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: <7djs50F2bsubuU1@mid.individual.net> References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: <4A74DDD8.7020304@ieee.org> Michael M Mason wrote: >
I'm > running Python 3.1 on Vista and I can't figure out how to add my own > directory to sys.path. > > The docs suggest that I can either add it to the PYTHONPATH > environment variable or to the PythonPath key in the registry. > However, PYTHONPATH doesn't exist, and updating the registry key has > no effect (and in any case the contents aren't the same as sys.path). > > So where does sys.path get its value from, and how do I change it? > sys.path gets its values from several places. The ones I think I know of are: current directory (which uses "" rather than the expected ".") directories listed in PythonPath environment variable Windows-system directory relative to the executable (python.exe or pythonw.exe) that's actually running relative to the user directory (docs&settings/username/Application Data .... If there's no PythonPath variable, it just uses those other items. I have no idea what it gets from the registry entries. Anyway, I'd suggest adding it to PythonPath, and if it's empty, just create it with the directory you need. I'm hoping you know you can also add to sys.path directly during script initialization. It's just a list, and is writeable. From joongkoo.cho at gmail.com Sat Aug 1 20:43:57 2009 From: joongkoo.cho at gmail.com (Joongkoo Cho) Date: Sat, 1 Aug 2009 17:43:57 -0700 Subject: Shortest path code on real map Message-ID: Dear All, I'm trying to calculate shortest paths on US highway map. I understand how shortest path algorithms work in Python but I need helps to do it on real maps. How can I make link-node information? Best, John -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sat Aug 1 21:06:47 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 01:06:47 GMT Subject: Custom namespaces Message-ID: <0284d760$0$20667$c3e8da3@news.astraweb.com> I was playing around with a custom mapping type, and I wanted to use it as a namespace, so I tried to use it as my module __dict__: >>> import __main__ >>> __main__.__dict__ = MyNamespace() Traceback (most recent call last): File "", line 1, in TypeError: readonly attribute Why is __dict__ made read-only? I next thought I could change the type of the namespace to my class: >>> __main__.__dict__.__class__ = MyNamespace Traceback (most recent call last): File "", line 1, in TypeError: __class__ assignment: only for heap types Drat, foiled again!!! Okay, if I can't do this at the module level, can I at least install a custom namespace at the class level? >>> class MyNamespace(dict): ... def __getitem__(self, key): ... print "Looking up key '%s'" % key ... return super(MyNamespace, self).__getitem__(key) ... >>> namespace = MyNamespace(x=1, y=2, z=3) >>> namespace['x'] Looking up key 'x' 1 >>> C = new.classobj("C", (object,), namespace) >>> C.x 1 Apparently not. It looks like the namespace provided to the class constructor gets copied when the class is made. Interestingly enough, the namespace argument gets modified *before* it gets copied, which has an unwanted side-effect: >>> namespace {'y': 2, 'x': 1, '__module__': '__main__', 'z': 3, '__doc__': None} Is there any way to install a custom type as a namespace? -- Steven From redforks at gmail.com Sat Aug 1 21:11:45 2009 From: redforks at gmail.com (Red Forks) Date: Sun, 2 Aug 2009 09:11:45 +0800 Subject: string.Template issue In-Reply-To: References: Message-ID: <3f18b3f10908011811t6947fbf2t335370c676889062@mail.gmail.com> On Thu, Jul 30, 2009 at 4:17 PM, Javier Collado wrote: > Hello, > > In the string.Template documentation > (http://docs.python.org/library/string.html) it's explained that if a > custom regular expression for pattern substitution is needed, it's > possible to override idpattern class attribute (whose default value is > [_a-z][_a-z0-9]*). > > However, if the custom pattern that is needed is just uppercase > letters something like [A-Z]+ won't work because of the following line > in the _TemplateMetaclass class __init__ method: > cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) derive a new class, and replace __init__ method, or replace _TemplateMetaclass.__init__() method. > > > I would say that this is an error (IGNORECASE just shouldn't be there) > and that the line above should be: > cls.pattern = _re.compile(pattern, _re.VERBOSE) > and the default value for idpattern: > [_a-zA-Z][_a-zA-Z0-9]* > > Do you agree on this? Is there any reason for the IGNORECASE option to > be passed to re.compile? > > Best regards, > Javier > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From redforks at gmail.com Sat Aug 1 21:18:58 2009 From: redforks at gmail.com (Red Forks) Date: Sun, 2 Aug 2009 09:18:58 +0800 Subject: Custom namespaces In-Reply-To: <0284d760$0$20667$c3e8da3@news.astraweb.com> References: <0284d760$0$20667$c3e8da3@news.astraweb.com> Message-ID: <3f18b3f10908011818x711e49ccg575eb4eb7363f261@mail.gmail.com> On Sun, Aug 2, 2009 at 9:06 AM, Steven D'Aprano < steve at remove-this-cybersource.com.au> wrote: > I was playing around with a custom mapping type, and I wanted to use it > as a namespace, so I tried to use it as my module __dict__: > > >>> import __main__ > >>> __main__.__dict__ = MyNamespace() > Traceback (most recent call last): > File "", line 1, in > TypeError: readonly attribute > > Why is __dict__ made read-only? to protect module type? Use .update() method: __main.__.__dict__.update(MyNamespace()) You can create your own Module instance: from types import ModuleType m = ModuleType('modulename') and make a sub class of ModuleType is also OK > > > I next thought I could change the type of the namespace to my class: > > >>> __main__.__dict__.__class__ = MyNamespace > Traceback (most recent call last): > File "", line 1, in > TypeError: __class__ assignment: only for heap types > > Drat, foiled again!!! > > Okay, if I can't do this at the module level, can I at least install a > custom namespace at the class level? > > >>> class MyNamespace(dict): > ... def __getitem__(self, key): > ... print "Looking up key '%s'" % key > ... return super(MyNamespace, self).__getitem__(key) > ... > >>> namespace = MyNamespace(x=1, y=2, z=3) > >>> namespace['x'] > Looking up key 'x' > 1 > >>> C = new.classobj("C", (object,), namespace) > >>> C.x > 1 > > Apparently not. It looks like the namespace provided to the class > constructor gets copied when the class is made. > > Interestingly enough, the namespace argument gets modified *before* it > gets copied, which has an unwanted side-effect: > > >>> namespace > {'y': 2, 'x': 1, '__module__': '__main__', 'z': 3, '__doc__': None} > > > Is there any way to install a custom type as a namespace? > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dciphercomputing at gmail.com Sat Aug 1 21:25:10 2009 From: dciphercomputing at gmail.com (Simon) Date: Sat, 1 Aug 2009 18:25:10 -0700 (PDT) Subject: Newbie Question regarding __init__() References: Message-ID: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> Okay I will fix my code and include "self" and see what happens. I know I tried that before and got another error which I suspect was another newbie error. The idea behind the init_Pre is that I can put custom code here to customize the __init__ instead of creating a new subclass. This kind of hook pattern allows you to flatten your inheritance hierarchy. I can choose in the init_Pre method to execute code before the init_exec (which contains the default __init__ code) and still execute the init_Exec method or I can completely customize the entire __init__ by returning False from init_Pre and prevent the init_Exec from being called. I use this type of pattern with almost all my methods. In this way I can create a less complicated inheritance chain but still have have custom code when needed without sub-classing. I am use to Visual FoxPro which where you can do =This.init_Pre().And.This.init_Exec() and the result is discarded so that is why it looks the way it does. In this form init_Exec has to return a value. However, If self.init_Pre(): self.init_Exec() would work the same and then I could avoid returning a value. Thanks, Simon On Aug 1, 5:52?am, Dave Angel wrote: > Nat Williams wrote: > > As MRAB described, ALL instance methods need to accept 'self' as a first > > parameter, as that will be passed to them implicitly when they are called. > > This includes __init__. ?The name 'self' is just a commonly accepted > > convention for the name of the instance object passed to methods. ?You don't > > have to call it that, but you really should. > > > Take a look athttp://docs.python.org/tutorial/classes.html#class-objects > > It might help shed some light on how methods and instances work. > > > One other thing. ?I'm a little confused by the first line of > > dcObject.__init__: > > > self.init_Pre() and self.init_Exec() > > > I suspect this does not do what you think it does. ?init_Pre and init_Exec > > will both be called by this expression (unless init_Pre throws an exception, > > of course). ?You're not getting anything here that you wouldn't by just > > calling each method on a separate line, except just making it harder to > > read. > > Read the doc-string for init_Pre() and for init_Exec(). ?The final > version of init_Pre() will return False in some circumstances, and in > those circumstances Simon doesn't want init_Exec() to be called. ?He's > deliberately using the short-circuit evaluation of ?'and' ?to accomplish > that. > > > > > > > > > On Fri, Jul 31, 2009 at 8:53 PM, Simon wrote: > > >> Hi > > >> So should the dcObject class include the "self" as well since I have > >> not defined an __init__ method in dcCursor? > > >> Simon > > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > Every one of those methods in both of those classes need a "self" first > argument. ?As others have said, all instance methods need a 'self.' From sturlamolden at yahoo.no Sat Aug 1 21:31:15 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 18:31:15 -0700 (PDT) Subject: Help understanding the decisions *behind* python? References: Message-ID: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> On 20 Jul, 18:27, Phillip B Oldham wrote: > We're not looking to start any arguments or religious wars and we're > not asking that python be changed into something its not. We'd simply > like to understand the decision behind the lists and tuple structures. > We feel that in not "getting" the difference between the two types we > may be missing out on using these data structures to their full > potential. A crude simplification would be: - A Python programmer will use a tuple where a C programmer will use a struct. - Python and C programmers use lists and arrays similarly. Tuples are used for passing arguments to and from a function. Common use of tuples include multiple return values and optional arguments (*args). It has already been mentioned that tuples are immutable and can be used as dictionary keys. From skip at pobox.com Sat Aug 1 21:38:46 2009 From: skip at pobox.com (Skip Montanaro) Date: Sun, 2 Aug 2009 01:38:46 +0000 (UTC) Subject: Wrapping prstat on Solaris References: <1bce2ffd-85cb-4860-8b3e-92d8e1619a46@k19g2000yqn.googlegroups.com> Message-ID: > You haven't told us how you are actually reading from prstat's output > pipe, which may be the cause. For instance, if you are doing > > for line in pipe: > print line > ... > > then this could cause your buffering issue. > > Instead try using readline(): > > while True: > line = pipe.readline() > ... Yes, I've been using for line in pipe. Switching to your construct seems to work like a charm. Thanks, Skip From fatkinson at mishmash.com Sat Aug 1 21:50:48 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sat, 01 Aug 2009 18:50:48 -0700 Subject: Get Cliet IP Address Message-ID: What is the function to obtain the client browser's IP address? Fred From fatkinson at mishmash.com Sat Aug 1 21:56:33 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sat, 01 Aug 2009 18:56:33 -0700 Subject: Predefined Variables References: <7cr6siF28oinaU2@mid.uni-berlin.de> Message-ID: <4gs9755f299j7ueitf422hh2vna32f358o@4ax.com> On Thu, 23 Jul 2009 15:28:50 +0200, "Diez B. Roggisch" wrote: >Fred Atkinson wrote: > >> Is there a pre-defined variable that returns the GET line >> (http://www.php.net/index.php?everythingafterthequestionmark) as a >> single variable (rather than individual variables)? > >Variables don't return things. Functions do. And additionally the answer >depends on what and with what you actually do. > >Diez I want to display the client browser's IP address on the Web page. I'd like to create a variable like this: ip = somefunction(). Then I can print the IP address on the Web page and/or log it in an error file. Fred From sturlamolden at yahoo.no Sat Aug 1 22:19:43 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 19:19:43 -0700 (PDT) Subject: Help understanding the decisions *behind* python? References: <86b332b3-2da0-44e0-b29f-d930136635df@u16g2000pru.googlegroups.com> <4677d753-364f-4d29-9091-e55008daec83@12g2000pri.googlegroups.com> Message-ID: <78d2801f-790c-475b-8953-23094482637f@h21g2000yqa.googlegroups.com> On 31 Jul, 23:43, Raymond Hettinger wrote: >?More than one person here has > observed that the time to learn to program Pythonically is inversely > proportional to their experience in Java. I believe it is opposite. The longer the Java experience, the longer it takes to program pythonically. The correlation is not inverse. In particular, programmers accustomed to Java or C++ seem to use for- loops awfully lot. And when they do, they always loop over a sequence of integers, and use these as array indices. They consequently use a class where a tuple would be more appropriate, never return multiple values from functions, etc. Due to their coding style, they produce programs that are notoriously inefficient, and blame this on 'Python being slow'. Unlearning the idioms from Java takes a while. Python is not Java and should not be programmed as such. On the other hand, I found that my experience with MATLAB helped me a lot on picking up a pythonical style quickly. From greg at cosc.canterbury.ac.nz Sat Aug 1 22:19:45 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 02 Aug 2009 14:19:45 +1200 Subject: Python processors? : WAS Re: Does python have the capability for driver development ? In-Reply-To: <2d8298b9-b857-4b3d-ae63-2056d80cdf7f@d4g2000yqa.googlegroups.com> References: <4a7151b2$0$17782$ba4acef3@news.orange.fr> <2d8298b9-b857-4b3d-ae63-2056d80cdf7f@d4g2000yqa.googlegroups.com> Message-ID: <7dkbcqF2c6aqgU1@mid.individual.net> Francesco Bochicchio wrote: > I wonder: has anybody thought of making a python-machine, or at least > a processor able to directly execute high-level bytecode (LLVM-like?). In some of my idle moments I've speculated on what such a machine might be like. One of my ideas for potential future projects is to flesh out the design and maybe even build an FPGA prototype. It would purely be for fun, though. It's unlikely that such a processor would be able to compete speed-wise with a general-purpose CPU running a Python interpreter with critical libraries written in C. That's what killed things like the Lisp machine. Their developers couldn't keep up with the huge resources that people like Intel and Motorola had to throw at CPU development, so eventually a general-purpose CPU could run Lisp faster than a Lisp machine. -- Greg From sturlamolden at yahoo.no Sat Aug 1 22:44:17 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 19:44:17 -0700 (PDT) Subject: fast video encoding References: <570097d0-2b2a-4705-892f-0d0154d69d63@b14g2000yqd.googlegroups.com> Message-ID: <0c8cfac7-0a70-4e1f-90ec-19e9c45cae89@h21g2000yqa.googlegroups.com> On 29 Jul, 10:14, gregorth wrote: > for a scientific application I need to save a video stream to disc for > further post processing. I have worked a bit on this as well. There are two things that make scientific applications different form common video encoding: First, a scientific video stream is often very different from a 'movie': There are usually very little 'movement'. For example, when I have filmed a mouse swimming in a water maze (a pool of milky white water), the only thing that moves is the rat. So I could achieve excellent compression just by saving the pixels that changed. Second, scientific data should be stored with lossless compression if possible. Common video codecs are aimed at films and home video, not scientific video streams. I don't know how your data are, but I would be very picky about the codec. And chances are you will be better off home-brewing your own domain specific compression. If you need to store large amounts of scientific data, consider using something like a HDF5 database for storage. There are two Python wrappers for HDF5 that I know of (h5py and PyTables). From nobody at nowhere.com Sat Aug 1 22:47:59 2009 From: nobody at nowhere.com (Nobody) Date: Sun, 02 Aug 2009 03:47:59 +0100 Subject: Help understanding the decisions *behind* python? References: <86b332b3-2da0-44e0-b29f-d930136635df@u16g2000pru.googlegroups.com> <4677d753-364f-4d29-9091-e55008daec83@12g2000pri.googlegroups.com> <78d2801f-790c-475b-8953-23094482637f@h21g2000yqa.googlegroups.com> Message-ID: On Sat, 01 Aug 2009 19:19:43 -0700, sturlamolden wrote: >>?More than one person here has >> observed that the time to learn to program Pythonically is inversely >> proportional to their experience in Java. > > I believe it is opposite. The longer the Java experience, the longer > it takes to program pythonically. The correlation is not inverse. In > particular, programmers accustomed to Java or C++ seem to use for- > loops awfully lot. And when they do, they always loop over a sequence > of integers, and use these as array indices. It would be more accurate to say that of programmers who are *only* accustomed to Java or C++. I've been using C for 80-90% of my code for 25 years, and I wouldn't normally loop over the indices. But then the other 10-20% is Lisp, Tcl, Haskell, PostScript and, more recently, Python. OTOH, using a "for" loop when you could use a generator means less work when you need to make a minor change and a generator is no longer sufficient. From sturlamolden at yahoo.no Sat Aug 1 23:00:32 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 20:00:32 -0700 (PDT) Subject: Does python have the capability for driver development ? References: <87skgf83ua.fsf@rsw.digi.com.br> <94abbddc-dac7-4215-84d1-d4eb3f82724d@h21g2000yqa.googlegroups.com> Message-ID: On 30 Jul, 02:19, MalC0de wrote: > actually I mean driver programming under Windows operating system, if > you know, there's A kit name DDK available at microsoft's website for > developing device drivers under C / C++ environment, Actually, Microsoft has replaced DDK with a new kit called WDK for Vista. The funny thing about WDK is that there are a lot of illegal C and C++ in the headers, which even Microsoft's own compiler refuse to accept. So good luck on getting anything to compile. From darkneter at gmail.com Sat Aug 1 23:04:05 2009 From: darkneter at gmail.com (NighterNet) Date: Sat, 1 Aug 2009 20:04:05 -0700 (PDT) Subject: socket policy flash help References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> <8bede581-f260-4c69-abf0-1e8071380b76@z4g2000prh.googlegroups.com> Message-ID: <7e6cdc26-bcc0-4503-b7b4-9ad80b1041f6@v37g2000prg.googlegroups.com> Here the full code. flashpolicy.xml [[[ ]]] flashpolicytest_server3x.py [[[ #!/usr/local/bin/python ''' Still under testing... python version 3.x.x ''' import socket import threading import sys import os file_name = 'flashpolicy.xml' fh = open(file_name, "r") policy = fh.read(10001) host = ''; #out side network port = 5555; print ("# ------------- Init... ------------- #"); class ClientThread (threading.Thread): global policy; allClients = []; vlock = threading.Lock(); id = 0 # next available thread number def __init__(self,clientSocket): threading.Thread.__init__(self) self.sockfd = clientSocket; #socket client self.name = ''; ClientThread.id += 1 self.id = ClientThread.id self.nickName = ''; self.allClients.append(self.sockfd); def sendAll(self,buff): for index,clientSock in enumerate(self.allClients): try: clientSock.send(buff); except (socket.error): print ('error socket %s\n',index,"| clean"); clientSock.close() del self.allClients[index] def run(self): while True: buff = self.sockfd.recv(1028); if not buff: print ("connect close...(client side)"); self.sockfd.close(); break #incase it loop infinite if str(buff) == str("b\'\\x00\'"): print ('policy FOUND >>> sending...') print(buff) b = b'' print (b) self.sockfd.send(b); self.sockfd.sendall(b); print(buff); self.sendAll(buff) self.sockfd.close() print ("# ------------- Init... Listen Client ------------- #\n"); try: server = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) except AttributeError: # AttributeError catches Python built without IPv6 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: # socket.error catches OS with IPv6 disabled server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind((host,port)) server.listen(5) print ("Server Up Listen!",host,":",port," Bind!"); while True: (clientSocket, address) = server.accept(); print("client connect from :",address); ct = ClientThread(clientSocket); print(ct.id); ct.start(); ]]] Some odd reason I can't send flash policy from python to flash socket to agrees with the connection. From fatkinson at mishmash.com Sat Aug 1 23:07:21 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sat, 01 Aug 2009 20:07:21 -0700 Subject: Predefined Variables References: <7cr6siF28oinaU2@mid.uni-berlin.de> <4gs9755f299j7ueitf422hh2vna32f358o@4ax.com> Message-ID: On Sat, 01 Aug 2009 18:56:33 -0700, Fred Atkinson wrote: >On Thu, 23 Jul 2009 15:28:50 +0200, "Diez B. Roggisch" > wrote: > >>Fred Atkinson wrote: >> >>> Is there a pre-defined variable that returns the GET line >>> (http://www.php.net/index.php?everythingafterthequestionmark) as a >>> single variable (rather than individual variables)? >> >>Variables don't return things. Functions do. And additionally the answer >>depends on what and with what you actually do. >> >>Diez > > I want to display the client browser's IP address on the Web >page. > > I'd like to create a variable like this: ip = somefunction(). > Then I can print the IP address on the Web page and/or log it >in an error file. > > > > Fred I replied to the wrong post. Sorry. I want to do something like this: string = os.environment('QUERY_STRING') If this is the string in the URL: http://www.someurl.com/cgi-bin/somescript.cgi?anythingafterthequestionmark 'string' should now contain the value 'everythingafterthequestionmark' When I use the os.environment('QUERY_STRING'), it doesn't work. Is there something I should import to make this function work? Or what else is wrong? Fred From sturlamolden at yahoo.no Sat Aug 1 23:10:00 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 20:10:00 -0700 (PDT) Subject: Help understanding the decisions *behind* python? References: <86b332b3-2da0-44e0-b29f-d930136635df@u16g2000pru.googlegroups.com> <4677d753-364f-4d29-9091-e55008daec83@12g2000pri.googlegroups.com> <78d2801f-790c-475b-8953-23094482637f@h21g2000yqa.googlegroups.com> Message-ID: <8a15492e-c9ab-47be-afea-cde3065413b1@e27g2000yqm.googlegroups.com> On 2 Aug, 04:47, Nobody wrote: > OTOH, using a "for" loop when you could use a generator means less work > when you need to make a minor change and a generator is no longer > sufficient. It's not just that. It is e.g. using a for loop and indexes instead of a slice. E.g. for i in range(10): # Java idiom a[i] = b[i+1] instead of a[:10] = b[1:11] # Pythonic From sturlamolden at yahoo.no Sat Aug 1 23:24:11 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 20:24:11 -0700 (PDT) Subject: Help understanding the decisions *behind* python? References: <86b332b3-2da0-44e0-b29f-d930136635df@u16g2000pru.googlegroups.com> <200907312048.03922.emmanuel.surleau@gmail.com> Message-ID: <2ff11bfc-9101-4b29-8b71-1627d85f799e@18g2000yqa.googlegroups.com> On 31 Jul, 21:31, Masklinn wrote: > It's intuitive if you come to Python knowing other languages with ? > tuples (which are mostly functional, and in which tuples are *never* ? > sequences/iterables). At the end of the day, and if Guido's intention ? > truly was what Raymond says, implementing tuples as immutable sequence ? > was a mistake. And the documentation is to blame as well: in it, ? > tuples are clearly described as a *sequence* type, not a *structure* ? > type. That depends on the readers' preconceptions: Only when the reader have knowledge of C structs, Pascal records, or Java classes should this matter. The na?ve reader will not have preconceptions about a difference between "structure types" and "sequence types". A more advanced C programmer will also know that a struct is a form of a sequence in C: you can e.g. memcpy any struct to a char array. From zooko at zooko.com Sun Aug 2 00:14:49 2009 From: zooko at zooko.com (Zooko Wilcox-O'Hearn) Date: Sat, 1 Aug 2009 22:14:49 -0600 Subject: ANNOUNCING Tahoe, the Lofty-Atmospheric Filesystem, v1.5 Message-ID: <9CE7ACE7-219C-4097-8543-928E05651387@zooko.com> Dear people of python-list: Python is our preferred programming language for the Tahoe-LAFS project. We use C/C++ extension modules for the CPU-intensive parts, and we interoperate with many languages through the RESTful web API, but the core code is 100% Python. Regards, Zooko --- The Tahoe-LAFS team is pleased to announce the immediate availability of version 1.5 of Tahoe, the Lofty Atmospheric File System. Tahoe-LAFS is the first cloud storage technology which offers security and privacy in the sense that the cloud storage service provider itself can't read or alter your data. Here is the one-page explanation of its unique security and fault-tolerance properties: http://allmydata.org/source/tahoe/trunk/docs/about.html This release is the successor to v1.4.1, which was released April 13, 2009 [1]. This is a major new release, improving the user interface and performance and fixing a few bugs, and adding ports to OpenBSD, NetBSD, ArchLinux, NixOS, and embedded systems built on ARM CPUs. See the NEWS file [2] for more information. In addition to the functionality of Tahoe-LAFS itself, a crop of related projects have sprung up to extend it and to integrate it into operating systems and applications. These include frontends for Windows, Macintosh, JavaScript, and iPhone, and plugins for duplicity, bzr, Hadoop, and TiddlyWiki, and more. See the Related Projects page on the wiki [3]. COMPATIBILITY Version 1.5 is fully compatible with the version 1 series of Tahoe-LAFS. Files written by v1.5 clients can be read by clients of all versions back to v1.0. v1.5 clients can read files produced by clients of all versions since v1.0. v1.5 servers can serve clients of all versions back to v1.0 and v1.5 clients can use servers of all versions back to v1.0. This is the sixth release in the version 1 series. The version 1 series of Tahoe-LAFS will be actively supported and maintained for the forseeable future, and future versions of Tahoe-LAFS will retain the ability to read and write files compatible with Tahoe-LAFS v1. The version 1 series of Tahoe-LAFS is the basis of the consumer backup product from Allmydata, Inc. -- http://allmydata.com . WHAT IS IT GOOD FOR? With Tahoe-LAFS, you can distribute your filesystem across a set of servers, such that if some of them fail or even turn out to be malicious, the entire filesystem continues to be available. You can share your files with other users, using a simple and flexible access control scheme. We believe that the combination of erasure coding, strong encryption, Free/Open Source Software and careful engineering make Tahoe-LAFS safer than RAID, removable drive, tape, on-line backup or other Cloud storage systems. This software comes with extensive tests, and there are no known security flaws which would compromise confidentiality or data integrity in typical use. (For all currently known issues please see the known_issues.txt file [4].) LICENCE You may use this package under the GNU General Public License, version 2 or, at your option, any later version. See the file "COPYING.GPL" [5] for the terms of the GNU General Public License, version 2. You may use this package under the Transitive Grace Period Public Licence, version 1 or, at your option, any later version. (The Transitive Grace Period Public Licence has requirements similar to the GPL except that it allows you to wait for up to twelve months after you redistribute a derived work before releasing the source code of your derived work.) See the file "COPYING.TGPPL.html" [6] for the terms of the Transitive Grace Period Public Licence, version 1. (You may choose to use this package under the terms of either licence, at your option.) INSTALLATION Tahoe-LAFS works on Linux, Mac OS X, Windows, Cygwin, Solaris, *BSD, and probably most other systems. Start with "docs/install.html" [7]. HACKING AND COMMUNITY Please join us on the mailing list [8]. Patches are gratefully accepted -- the RoadMap page [9] shows the next improvements that we plan to make and CREDITS [10] lists the names of people who've contributed to the project. The Dev page [11] contains resources for hackers. SPONSORSHIP Tahoe-LAFS was originally developed thanks to the sponsorship of Allmydata, Inc. [12], a provider of commercial backup services. Allmydata, Inc. created the Tahoe-LAFS project and contributed hardware, software, ideas, bug reports, suggestions, demands, and money (employing several Tahoe-LAFS hackers and instructing them to spend part of their work time on this Free Software project). Also they awarded customized t-shirts to hackers who found security flaws in Tahoe-LAFS (see http://hacktahoe.org ). After discontinuing funding of Tahoe-LAFS R&D in early 2009, Allmydata, Inc. has continued to provide servers, co-lo space and bandwidth to the open source project. Thank you to Allmydata, Inc. for their generous and public-spirited support. This is the second release of Tahoe-LAFS which was created solely as a labor of love by volunteers; developer time is no longer funded by allmydata.com (see [13] for details). Zooko Wilcox-O'Hearn on behalf of the Tahoe-LAFS team Special acknowledgment goes to Brian Warner, whose superb engineering skills and dedication are primarily responsible for the Tahoe implementation, and significantly responsible for the Tahoe design as well, not to mention most of the docs and tests. Tahoe-LAFS wouldn't exist without him. August 1, 2009 Boulder, Colorado, USA P.S. Just kidding about that acronym. "LAFS" actually stands for "Lightweight Authorization File System". Or possibly for "Least-Authority File System". There is no truth to the rumour that it actually stands for "Long-lived Axe-tolerant File System". [1] http://allmydata.org/trac/tahoe/browser/relnotes.txt?rev=3853 [2] http://allmydata.org/trac/tahoe/browser/NEWS?rev=4033 [3] http://allmydata.org/trac/tahoe/wiki/RelatedProjects [4] http://allmydata.org/trac/tahoe/browser/docs/known_issues.txt [5] http://allmydata.org/trac/tahoe/browser/COPYING.GPL [6] http://allmydata.org/source/tahoe/trunk/COPYING.TGPPL.html [7] http://allmydata.org/source/tahoe/trunk/docs/install.html [8] http://allmydata.org/cgi-bin/mailman/listinfo/tahoe-dev [9] http://allmydata.org/trac/tahoe/roadmap [10] http://allmydata.org/trac/tahoe/browser/CREDITS?rev=4035 [11] http://allmydata.org/trac/tahoe/wiki/Dev [12] http://allmydata.com [13] http://allmydata.org/pipermail/tahoe-dev/2009-March/001461.html From clp2 at rebertia.com Sun Aug 2 00:46:35 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 1 Aug 2009 21:46:35 -0700 Subject: Custom namespaces In-Reply-To: <0284d760$0$20667$c3e8da3@news.astraweb.com> References: <0284d760$0$20667$c3e8da3@news.astraweb.com> Message-ID: <50697b2c0908012146p11c58419s7d33aa9a2a048f46@mail.gmail.com> On Sat, Aug 1, 2009 at 6:06 PM, Steven D'Aprano wrote: > I was playing around with a custom mapping type, and I wanted to use it > as a namespace, so I tried to use it as my module __dict__: > >>>> import __main__ >>>> __main__.__dict__ = MyNamespace() > Traceback (most recent call last): > ?File "", line 1, in > TypeError: readonly attribute > > Why is __dict__ made read-only? > > I next thought I could change the type of the namespace to my class: > >>>> __main__.__dict__.__class__ = MyNamespace > Traceback (most recent call last): > ?File "", line 1, in > TypeError: __class__ assignment: only for heap types > > Drat, foiled again!!! > > Okay, if I can't do this at the module level, can I at least install a > custom namespace at the class level? > Apparently not. It looks like the namespace provided to the class > constructor gets copied when the class is made. > Is there any way to install a custom type as a namespace? For classes/objects, yes, using metaclasses. See the __prepare__() method in PEP 3115: http://www.python.org/dev/peps/pep-3115/ Cheers, Chris -- http://blog.rebertia.com From bhardwajjayesh7 at gmail.com Sun Aug 2 02:11:43 2009 From: bhardwajjayesh7 at gmail.com (golu) Date: Sat, 1 Aug 2009 23:11:43 -0700 (PDT) Subject: cgi script Message-ID: Hi, i started learning cgi few days ago in python and everything went fine until i started getting the follwing error " The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script. If you think this is a server error, please contact the webmaster. " i am using apache on xampp. plz help From michael at altra-optics.co.uk Sun Aug 2 02:34:56 2009 From: michael at altra-optics.co.uk (Michael M Mason) Date: Sun, 2 Aug 2009 07:34:56 +0100 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: <7dks7jF2ccjstU1@mid.individual.net> "Dave Angel" wrote in message news:mailman.4120.1249172970.8015.python-list at python.org... > Michael M Mason wrote: >>
I'm running >> Python 3.1 on Vista and I can't figure out how to add my own directory to >> sys.path. Thanks to Jon, Piet, David and Dave for the responses. > sys.path gets its values from several places. Ah, I'd misunderstood the docs: I thought it came from just one place (which I couldn't find). > Anyway, I'd suggest adding it to PythonPath, and if it's empty, just > create it with the directory you need. Thanks--that worked! > I'm hoping you know you can also add to sys.path directly during script > initialization. It's just a list, and is writeable. Yes, but I'm mainly playing in IDLE and I was getting a bit fed up of repeatedly typing import sys sys.path.append('C:/Users/Michael/Code/Python') import mystuff -- Michael From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 02:47:41 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 06:47:41 GMT Subject: Python processors? : WAS Re: Does python have the capability for driver development ? References: <4a7151b2$0$17782$ba4acef3@news.orange.fr> <2d8298b9-b857-4b3d-ae63-2056d80cdf7f@d4g2000yqa.googlegroups.com> <7dkbcqF2c6aqgU1@mid.individual.net> Message-ID: <02852746$0$20667$c3e8da3@news.astraweb.com> On Sun, 02 Aug 2009 14:19:45 +1200, greg wrote: > That's what killed things like the Lisp machine. Their developers > couldn't keep up with the huge resources that people like Intel and > Motorola had to throw at CPU development, so eventually a > general-purpose CPU could run Lisp faster than a Lisp machine. When you say "eventually", I think you mean "decades ago". I recall a collaboration between Apple and Texas Instruments to build a Macintosh with a Lisp Machine in the late 1980s. From the one box, you could run two computers simultaneously, with two operating systems, one running the Motorola 68020 and the other a Lisp Machine processor. I don't think it sold very well -- by memory, benchmarks showed that for half (or less) of the price, you could run Lisp in software on a vanilla Mac and the software would be faster than running it on the Lisp Machine. TI also had at least one Nubus card for the Mac running a Lisp Machine: http://en.wikipedia.org/wiki/TI_Explorer On a similar note, there were Forth machines also available for the Apple Macintosh. Unlike Lisp, I think they suffered from the general lack of popularity of Forth rather than lack of speed. -- Steven From efotinis at oohay.com Sun Aug 2 02:59:41 2009 From: efotinis at oohay.com (eliasf) Date: Sun, 2 Aug 2009 09:59:41 +0300 Subject: Get Cliet IP Address In-Reply-To: References: Message-ID: <1249196395.629238@athprx04> "Fred Atkinson" wrote: > What is the function to obtain the client browser's IP > address? Do you mean the external public IP to the Internet? When I wanted to log the dynamic IP that my ADSL connection gets, I used whatismyip.com like this: import urllib2 QUERY_URL = 'http://www.whatismyip.com/automation/n09230945.asp' def query(): """Get IP as a string. As per the whatismyip.com automation rules, this function should not be called more ofter than every 5 minutes. """ return urllib2.urlopen(QUERY_URL).read() There's probably a better way, but I'm not very good with networking. :o) From pavlovevidence at gmail.com Sun Aug 2 03:14:41 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 Aug 2009 00:14:41 -0700 (PDT) Subject: cgi script References: Message-ID: <007247ae-53b8-4ce7-ad85-eb332b455f41@2g2000prl.googlegroups.com> On Aug 1, 11:11?pm, golu wrote: > Hi, > i started learning cgi few days ago in python and everything went > fine ?until i started getting the follwing error > " > The server encountered an internal error and was unable to complete > your request. Either the server is overloaded or there was an error in > a CGI script. Your script has a syntax error. (You forgot a colon or something like that.) If you can, try to run the file directly from a Python interpreter to see where the error is. Carl Banks From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 03:18:53 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 07:18:53 GMT Subject: Custom namespaces References: <0284d760$0$20667$c3e8da3@news.astraweb.com> Message-ID: <02852e95$0$20667$c3e8da3@news.astraweb.com> On Sat, 01 Aug 2009 21:46:35 -0700, Chris Rebert wrote: >> Is there any way to install a custom type as a namespace? > > For classes/objects, yes, using metaclasses. See the __prepare__() > method in PEP 3115: http://www.python.org/dev/peps/pep-3115/ Looks good, but that's Python 3 only, yes? At least, I can't get the metaclass to change the __dict__ in Python 2.6. There's obviously no __prepare__ before 3.0, but I tried the following, and still __dict__ ends up as a regular dict. Am I missing something? class VerboseDict(dict): def __getitem__(self, item): print ("Looking up key '%s'..." % item) return super(VerboseDict, self).__getitem__(item) class Meta(type): def __new__(cls, name, bases, namespace): namespace = VerboseDict(namespace) obj = super(Meta, cls).__new__(cls, name, bases, namespace) return obj MyClass = Meta('MyClass', (object,), dict(x=1, y=2)) -- Steven From clp2 at rebertia.com Sun Aug 2 03:31:05 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 Aug 2009 00:31:05 -0700 Subject: Custom namespaces In-Reply-To: <02852e95$0$20667$c3e8da3@news.astraweb.com> References: <0284d760$0$20667$c3e8da3@news.astraweb.com> <02852e95$0$20667$c3e8da3@news.astraweb.com> Message-ID: <50697b2c0908020031h32fadb65ye7e306138205a751@mail.gmail.com> On Sun, Aug 2, 2009 at 12:18 AM, Steven D'Aprano wrote: > On Sat, 01 Aug 2009 21:46:35 -0700, Chris Rebert wrote: > >>> Is there any way to install a custom type as a namespace? >> >> For classes/objects, yes, using metaclasses. See the __prepare__() >> method in PEP 3115: http://www.python.org/dev/peps/pep-3115/ > > Looks good, but that's Python 3 only, yes? Correct. > At least, I can't get the metaclass to change the __dict__ in Python 2.6. > There's obviously no __prepare__ before 3.0, but I tried the following, > and still __dict__ ends up as a regular dict. Am I missing something? > > > class VerboseDict(dict): > ? ?def __getitem__(self, item): > ? ? ? ?print ("Looking up key '%s'..." % item) > ? ? ? ?return super(VerboseDict, self).__getitem__(item) > > class Meta(type): > ? ?def __new__(cls, name, bases, namespace): > ? ? ? ?namespace = VerboseDict(namespace) > ? ? ? ?obj = super(Meta, cls).__new__(cls, name, bases, namespace) > ? ? ? ?return obj I would /guess/ that type.__new__() is internally doing the equivalent of dict(namespace). Hence why the addition of __prepare__() was necessary; it's probably impossible to accomplish what you want in earlier Python versions. Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 03:35:08 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 07:35:08 GMT Subject: Generate a new object each time a name is imported Message-ID: <02853264$0$20667$c3e8da3@news.astraweb.com> I would like to generate a new object each time I import a name from a module, rather than getting the same object each time. For example, currently I might do something like this: # Module count = 0 def factory(): # Generate a unique object each time this is called global count count += 1 return "Object #%d" % count # Calling module from Module import factory a = factory() # a == "Object #1" b = factory() # b == "Object #2" del factory I'm looking for a way to hide the generation of objects from the caller, so I could do something like this: from Module import factory() as a # a == "Object #1" from Module import factory() as b # b == "Object #2" except of course that syntax is illegal. -- Steven From jgardner at jonathangardner.net Sun Aug 2 03:38:22 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Sun, 2 Aug 2009 00:38:22 -0700 (PDT) Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: On Aug 2, 12:35?am, Steven D'Aprano wrote: > > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a ?# a == "Object #1" > from Module import factory() as b ?# b == "Object #2" > Explicit is better than implicit. In other words, I don't see why you need to hide this. Just import the factory function and call it. from Module import factory a = factory() From hniksic at xemacs.org Sun Aug 2 04:23:51 2009 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 02 Aug 2009 10:23:51 +0200 Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: <87tz0qei94.fsf@busola.homelinux.net> Steven D'Aprano writes: > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a # a == "Object #1" > from Module import factory() as b # b == "Object #2" > > except of course that syntax is illegal. That sounds reasonable (zen quotes aside), but it's just not possible in current Python. It would require for any use of "a" in subsequent code to not only refer to an object, but also to automagically call it. I know of no mechanism to do that. While Python allows intricate customization of access to objects, simply referring to a name remains fixed in meaning, probably intentionally. (The "cell" mechanism used to implement closures sounds like it could help, but a cell only stores a single value, not a factory, and it doesn't apply to global variables anyway.) From Ron.Barak at lsi.com Sun Aug 2 04:45:09 2009 From: Ron.Barak at lsi.com (Barak, Ron) Date: Sun, 2 Aug 2009 09:45:09 +0100 Subject: Run pyc file without specifying python path ? In-Reply-To: <4A71D35F.3090800@dejaviewphoto.com> References: <7F0503CD69378F49BE0DC30661C6CCF6701A26C4@enbmail01.lsi.com> <4A708F68.1010505@ieee.org> <7F0503CD69378F49BE0DC30661C6CCF6701A26C7@enbmail01.lsi.com> <4A7199FF.8010202@dejaviewphoto.com> <7F0503CD69378F49BE0DC30661C6CCF6701A26D2@enbmail01.lsi.com> <4A71D35F.3090800@dejaviewphoto.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF67D49D30E@enbmail01.lsi.com> > -----Original Message----- > From: Dave Angel [mailto:davea at dejaviewphoto.com] > Sent: Thursday, July 30, 2009 20:08 > To: Barak, Ron > Cc: 'python-list at python.org' > Subject: Re: Run pyc file without specifying python path ? > > Barak, Ron wrote: > > Hi Dave, > > > > On second thoughts, I may have a problem implementing the > wrapper solution, because my actual test_pyc.pyc, needs to > parse its command line. > > Namely, the actual call to test_pyc.pyc looks something like this: > > > > $ python test_pyc.py -U dave -PpasswoRD -C CreateMcGroupOnVolume > > --SVMs_IPs '10.1.1.1 , 10.1.1.2' -n "host1,host2" -g gn -j > jn -s svn > > -t tvn -p pool1 -l -c > > > > And I don't know of a way to add these parameters to the "import > > test_pyc" in wrapper > > > > Is there a way to pass information to an imported module ? > (Sorry if there's an obvious answer, I just cannot figure it out). > > > > Bye, > > Ron. > > > > > >> -----Original Message----- > >> From: Dave Angel [mailto:davea at dejaviewphoto.com] > >> Sent: Thursday, July 30, 2009 16:03 > >> To: Barak, Ron > >> Cc: 'Dave Angel'; 'python-list at python.org' > >> Subject: RE: Run pyc file without specifying python path ? > >> > >> Barak, Ron wrote: > >> > >>>> -----Original Message----- > >>>> From: Dave Angel [mailto:davea at ieee.org] > >>>> Sent: Wednesday, July 29, 2009 21:05 > >>>> To: Barak, Ron > >>>> Cc: 'python-list at python.org' > >>>> Subject: Re: Run pyc file without specifying python path ? > >>>> > >>>> Barak, Ron wrote: > >>>> > >>>> > >>>>> Hi, > >>>>> > >>>>> I wanted to make a python byte-code file executable, > >>>>> > >>>>> > >>>> expecting to be able to run it without specifying > "python" on the > >>>> (Linux bash) command line. > >>>> > >>>> > >>>>> So, I wrote the following: > >>>>> > >>>>> [root at VMLinux1 python]# cat test_pyc.py #!/usr/bin/env python > >>>>> > >>>>> print "hello" > >>>>> [root at VMLinux1 python]# > >>>>> > >>>>> and made its pyc file executable: > >>>>> > >>>>> [root at VMLinux1 python]# ls -ls test_pyc.pyc > >>>>> 4 -rwxr-xr-x 1 root root 106 Jul 29 14:22 test_pyc.pyc > >>>>> [root at VMLinux1 python]# > >>>>> > >>>>> So, I see: > >>>>> > >>>>> [root at VMLinux1 python]# file test_pyc.py* > >>>>> test_pyc.py: a python script text executable > >>>>> test_pyc.pyc: python 2.3 byte-compiled > >>>>> [root at VMLinux1 python]# > >>>>> > >>>>> If I try to do the following, no problem: > >>>>> > >>>>> [root at VMLinux1 python]# python test_pyc.pyc hello > >>>>> [root at VMLinux1 python]# > >>>>> > >>>>> However, the following fails: > >>>>> > >>>>> [root at VMLinux1 python]# ./test_pyc.pyc > >>>>> -bash: ./test_pyc.pyc: cannot execute binary file > >>>>> [root at VMLinux1 python]# > >>>>> > >>>>> Is there a way to run a pyc file without specifying the > >>>>> > >>>>> > >>>> python path ? > >>>> > >>>> > >>>>> Bye, > >>>>> Ron. > >>>>> > >>>>> > >>>>> > >>>>> > >>>> I don't currently run Unix, but I think I know the problem. > >>>> > >>>> In a text file, the shell examines the first line, and if > >>>> > >> it begins > >> > >>>> #! > >>>> it's assumed to point to the executable of an > interpreter for that > >>>> text file. Presumably the same trick doesn't work for a > .pyc file. > >>>> > >>>> Why not write a trivial wrapper.py file, don't compile > it, and let > >>>> that invoke the main code in the .pyc file? > >>>> > >>>> Then make wrapper.py executable, and you're ready to go. > >>>> > >>>> DaveA > >>>> > >>>> > >>>> > >>>> > >>> Hi Dave, > >>> Your solution sort of defeats my intended purpose (sorry > >>> > >> for not divulging my 'hidden agenda'). > >> > >>> I wanted my application to "hide" the fact that it's a > >>> > >> python script, and look as much as possible like it's a compiled > >> program. > >> > >>> The reason I don't just give my user a py file, is that I > >>> > >> don't want a cleaver user to change the innards of the script. > >> > >>> On the other hand, I don't want to make a compiled > >>> > >> (freezed?) version of the application, because it'll grow the > >> resulting file significantly, and I don't have the > experience to know > >> how it will run on different Linuxes. > >> > >>> Bye, > >>> Ron. > >>> > >>> > >> Most of the other answers basically paraphrased my suggestion of > >> making a wrapper file, not compiling it, and making it > executable. > >> With that > >> approach, the user just types "wrapper.py" on his command line. > >> > >> And wrapper.py only needs two lines, a shebang, and an > import, no big > >> deal if the user modifies it. The rest of your code can be .pyc > >> files. > >> > >> Steven makes some good points. You have to define what level of > >> clever you're protecting from. A determined hacker will get in no > >> matter what you do, unless you want to ship the program in a > >> proprietary embedded system, encased in epoxy. > >> Further, if you have an extension of .py or .pyc, a knowledgeable > >> hacker will know it's probably python. > >> > >> You imply you want it to run unmodifed on multiple unknown Linux > >> versions. I think that lets out binfmt solutions. > >> That means you need to test and support not only multiple Linux > >> implementations, but multiple Python versions, because who > knows what > >> the user may have installed. I think you need to rethink your > >> support strategy. And maybe concentrate on being able to detect > >> change, rather than prevent it. > >> > >> DaveA > >> > >> > >> > >> > (Please don't top-post. It puts responses out of order) > > You don't have to do anything special. Any module can import > sys, and parse sys.argv, as long as it wasn't yet modified. > > DaveA > Hi Dave, It seems like I don't understand your solution. I use the (appatched) soapAPI.py as the wrapper to parsing.pyc. However, if I do (for instance): $ python -u parsing.pyc -U aaa The last line of the output is (as expected): return_code: 12 ; params: {'username': 'aaa'} But, if I try the following: $ soapAPI.py -U aaa I don't get this line. Only the output to stderr gets printed to the screen. Bye, Ron. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: soapAPI.py Type: application/octet-stream Size: 65 bytes Desc: soapAPI.py URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: parsing.py Type: application/octet-stream Size: 9542 bytes Desc: parsing.py URL: From breamoreboy at yahoo.co.uk Sun Aug 2 04:55:04 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 02 Aug 2009 09:55:04 +0100 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: <7dks7jF2ccjstU1@mid.individual.net> References: <7djs50F2bsubuU1@mid.individual.net> <7dks7jF2ccjstU1@mid.individual.net> Message-ID: Michael M Mason wrote: > > "Dave Angel" wrote in message > news:mailman.4120.1249172970.8015.python-list at python.org... >> Michael M Mason wrote: >>>
I'm >>> running Python 3.1 on Vista and I can't figure out how to add my own >>> directory to sys.path. > > Thanks to Jon, Piet, David and Dave for the responses. > >> sys.path gets its values from several places. > > Ah, I'd misunderstood the docs: I thought it came from just one place > (which I couldn't find). > >> Anyway, I'd suggest adding it to PythonPath, and if it's empty, just >> create it with the directory you need. > > Thanks--that worked! Be careful, I'm screwed things up on several occasions by placing a file on PYTHONPATH that overrides a file in the standard library, test.py being my favourite! > >> I'm hoping you know you can also add to sys.path directly during >> script initialization. It's just a list, and is writeable. > > Yes, but I'm mainly playing in IDLE and I was getting a bit fed up of > repeatedly typing > import sys > sys.path.append('C:/Users/Michael/Code/Python') > import mystuff > -- Kindest regards. Mark Lawrence. From michael at altra-optics.co.uk Sun Aug 2 05:15:25 2009 From: michael at altra-optics.co.uk (Michael M Mason) Date: Sun, 2 Aug 2009 10:15:25 +0100 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: References: <7djs50F2bsubuU1@mid.individual.net> <7dks7jF2ccjstU1@mid.individual.net> Message-ID: <7dl3pkF2cnqf5U1@mid.individual.net> "Mark Lawrence" wrote in message news:mailman.4130.1249203322.8015.python-list at python.org... > Be careful, I'm screwed things up on several occasions by placing a file > on PYTHONPATH that overrides a file in the standard library, test.py being > my favourite! Thanks. Sure enough, I've already got my own test.py but I hadn't discovered it was a problem yet... -- Michael From davea at ieee.org Sun Aug 2 05:35:34 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 02 Aug 2009 05:35:34 -0400 Subject: Run pyc file without specifying python path ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF67D49D30E@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6701A26C4@enbmail01.lsi.com> <4A708F68.1010505@ieee.org> <7F0503CD69378F49BE0DC30661C6CCF6701A26C7@enbmail01.lsi.com> <4A7199FF.8010202@dejaviewphoto.com> <7F0503CD69378F49BE0DC30661C6CCF6701A26D2@enbmail01.lsi.com> <4A71D35F.3090800@dejaviewphoto.com> <7F0503CD69378F49BE0DC30661C6CCF67D49D30E@enbmail01.lsi.com> Message-ID: <4A755DE6.1000906@ieee.org> Barak, Ron wrote: > Hi Dave, > > It seems like I don't understand your solution. > I use the (appatched) soapAPI.py as the wrapper to parsing.pyc. > However, if I do (for instance): > > $ python -u parsing.pyc -U aaa > > The last line of the output is (as expected): > > return_code: 12 ; params: {'username': 'aaa'} > > But, if I try the following: > > $ soapAPI.py -U aaa > > I don't get this line. Only the output to stderr gets printed to the screen. > > Bye, > Ron. > > Hi Ron, To make it easier for anybody following this thread, let me post the minimum equivalent source files, inline. parsing.py: ------------------------------ #!/usr/bin/env python import sys def main(): print >> sys.stderr, "This is stderr output" return 5, sys.argv if __name__ == "__main__": return_code, params = main() print "return_code:",return_code,"; params:",params sys.exit(return_code) ------------------------------- soapapi.py: ------------------------------- #!/usr/bin/env python import sys import parsing parsing.main() ------------------------------ When I run soapapi.;py, it indeed prints only the stderr output. The solution is to move (most or all) of the top-level code of parsing.py into a main() function. Since you already have a main(), I'll rename that, and make a new one that calls it. new parsing.py: ------------------------------- #!/usr/bin/env python import sys def innermain(): print >> sys.stderr, "This is stderr output" return 5, sys.argv def main(): return_code, params = innermain() print "return_code:",return_code,"; params:",params sys.exit(return_code) if __name__ == "__main__": main() ------------------------------- The output is now two lines, one from innermain(), and one from main(). And it's the same whether the user runs parsing.py or soapAPI.py To clarify what happened, realize that when the user invokes parsing.py, the module is considered a script, and gets a pseudo-name of "__main__" When that same module is imported by another one, it is considered a library module, and gets its own name "parsing" So any logic that explicitly checks for "__main__" has to change, because we want identical behavior in the two cases. DaveA From davea at ieee.org Sun Aug 2 05:51:45 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 02 Aug 2009 05:51:45 -0400 Subject: Newbie Question regarding __init__() In-Reply-To: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> References: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> Message-ID: <4A7561B1.9060808@ieee.org> Simon wrote: > Okay I will fix my code and include "self" and see what happens. I > know I tried that before and got another error which I suspect was > another newbie error. > > The idea behind the init_Pre is that I can put custom code here to > customize the __init__ instead of creating a new subclass. This kind > of hook pattern allows you to flatten your inheritance hierarchy. I > can choose in the init_Pre method to execute code before the init_exec > (which contains the default __init__ code) and still execute the > init_Exec method or I can completely customize the entire __init__ by > returning False from init_Pre and prevent the init_Exec from being > called. I use this type of pattern with almost all my methods. In > this way I can create a less complicated inheritance chain but still > have have custom code when needed without sub-classing. > > I am use to Visual FoxPro which where you can do > > =is.init_Pre().And.This.init_Exec() and the result is discarded so > that is why it looks the way it does. In this form init_Exec has to > return a value. However, If self.init_Pre(): self.init_Exec() would > work the same and then I could avoid returning a value. > > Thanks, > Simon > > > On Aug 1, 5:52 am, Dave Angel wrote: > >> Nat Williams wrote: >> >>> As MRAB described, ALL instance methods need to accept 'self' as a first >>> parameter, as that will be passed to them implicitly when they are called. >>> This includes __init__. The name 'self' is just a commonly accepted >>> convention for the name of the instance object passed to methods. You don't >>> have to call it that, but you really should. >>> >>> Take a look athttp://docs.python.org/tutorial/classes.html#class-objects >>> It might help shed some light on how methods and instances work. >>> >>> One other thing. I'm a little confused by the first line of >>> dcObject.__init__: >>> >>> self.init_Pre() and self.init_Exec() >>> >>> I suspect this does not do what you think it does. init_Pre and init_Exec >>> will both be called by this expression (unless init_Pre throws an exception, >>> of course). You're not getting anything here that you wouldn't by just >>> calling each method on a separate line, except just making it harder to >>> read. >>> >> Read the doc-string for init_Pre() and for init_Exec(). The final >> version of init_Pre() will return False in some circumstances, and in >> those circumstances Simon doesn't want init_Exec() to be called. He's >> deliberately using the short-circuit evaluation of 'and' to accomplish >> that. >> >> >> >> >> >> >> >> >>> On Fri, Jul 31, 2009 at 8:53 PM, Simon wrote: >>> >>>> Hi >>>> >>>> So should the dcObject class include the "self" as well since I have >>>> not defined an __init__ method in dcCursor? >>>> >>>> Simon >>>> >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>>> >> Every one of those methods in both of those classes need a "self" first >> argument. As others have said, all instance methods need a 'self.' >> > > (Please don't top-post. You should put new responses at the end of quoted text, or sometimes inline if that's clearer.) I don't understand your comparison to Foxpro. read on. As your code was last posted, you don't need a return value from init_Exec() Every function that doesn't have an explicit return will return None. And None is interpreted as False in an "and" expression. If you had an "if" around the whole thing, then you'd care. DaveA From davea at ieee.org Sun Aug 2 06:00:28 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 02 Aug 2009 06:00:28 -0400 Subject: Help understanding the decisions *behind* python? In-Reply-To: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> Message-ID: <4A7563BC.2040406@ieee.org> sturlamolden wrote: > On 20 Jul, 18:27, Phillip B Oldham wrote: > > >> We're not looking to start any arguments or religious wars and we're >> not asking that python be changed into something its not. We'd simply >> like to understand the decision behind the lists and tuple structures. >> We feel that in not "getting" the difference between the two types we >> may be missing out on using these data structures to their full >> potential. >> > > A crude simplification would be: > > - A Python programmer will use a tuple where a C programmer will use a > struct. > > - Python and C programmers use lists and arrays similarly. > > Tuples are used for passing arguments to and from a function. Common > use of tuples include multiple return values and optional arguments > (*args). > > It has already been mentioned that tuples are immutable and can be > used as dictionary keys. > > > I think collections.namedtuple, introduced in Python 2.6, might help bridge the gap between a traditional tuple and a C struct. From __peter__ at web.de Sun Aug 2 06:33:03 2009 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Aug 2009 12:33:03 +0200 Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I would like to generate a new object each time I import a name from a > module, rather than getting the same object each time. For example, > currently I might do something like this: > > # Module > count = 0 > def factory(): > # Generate a unique object each time this is called > global count > count += 1 > return "Object #%d" % count > > > # Calling module > from Module import factory > a = factory() # a == "Object #1" > b = factory() # b == "Object #2" > del factory > > > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a # a == "Object #1" > from Module import factory() as b # b == "Object #2" > > except of course that syntax is illegal. How about >>> class A(object): ... def __init__(self): ... self._n = 0 ... @property ... def a(self): ... try: ... return self._n ... finally: ... self._n += 1 ... >>> import sys >>> sys.modules["yadda"] = A() >>> from yadda import a >>> from yadda import a as b >>> a, b (0, 1) Peter From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 06:49:33 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 10:49:33 GMT Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: <02855ff5$0$20667$c3e8da3@news.astraweb.com> On Sun, 02 Aug 2009 12:33:03 +0200, Peter Otten wrote: > How about [snip] >>>> import sys >>>> sys.modules["yadda"] = A() Perfect! That's exactly the sort of thing I'm looking for. Thanks for everyone who answered. -- Steven From breamoreboy at yahoo.co.uk Sun Aug 2 07:04:25 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 02 Aug 2009 12:04:25 +0100 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: <7dl3pkF2cnqf5U1@mid.individual.net> References: <7djs50F2bsubuU1@mid.individual.net> <7dks7jF2ccjstU1@mid.individual.net> <7dl3pkF2cnqf5U1@mid.individual.net> Message-ID: Michael M Mason wrote: > "Mark Lawrence" wrote in message > news:mailman.4130.1249203322.8015.python-list at python.org... >> Be careful, I'm screwed things up on several occasions by placing a >> file on PYTHONPATH that overrides a file in the standard library, >> test.py being my favourite! > > Thanks. Sure enough, I've already got my own test.py but I hadn't > discovered it was a problem yet... > Typical, tried to reproduce it and can't! Still at least you've been warned. -- Kindest regards. Mark Lawrence. From http Sun Aug 2 07:18:34 2009 From: http (Paul Rubin) Date: 02 Aug 2009 04:18:34 -0700 Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: <7x63d631md.fsf@ruckus.brouhaha.com> Peter Otten <__peter__ at web.de> writes: > >>> import sys > >>> sys.modules["yadda"] = A() OMG.... wow. I bow to you. But I'm not sure whether that's bowing in awe or in terror. From marcusw at cox.net Sun Aug 2 08:08:34 2009 From: marcusw at cox.net (Marcus Wanner) Date: Sun, 02 Aug 2009 08:08:34 -0400 Subject: Help understanding the decisions *behind* python? In-Reply-To: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> Message-ID: On 8/1/2009 9:31 PM, sturlamolden wrote: > - Python and C programmers use lists and arrays similarly. I'm guessing that's because of the brackets... Marcus From __peter__ at web.de Sun Aug 2 08:19:01 2009 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Aug 2009 14:19:01 +0200 Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> <7x63d631md.fsf@ruckus.brouhaha.com> Message-ID: wrote: KNode cannot parse your From-string correctly. Strange. > Peter Otten <__peter__ at web.de> writes: >> >>> import sys >> >>> sys.modules["yadda"] = A() > > OMG.... wow. I bow to you. But I'm not sure whether that's bowing in > awe or in terror. I don't know who invented it, but it's an old trick. It even made it into the standard library (email.LazyImporter). For the record: I don't recommend it. Peter From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 08:36:41 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 12:36:41 GMT Subject: Skipping a superclass Message-ID: <02857910$0$20667$c3e8da3@news.astraweb.com> I have a series of subclasses like this: class A(object): def method(self, *args): print "Lots of work gets done here in the base class" class B(A): def method(self, *args): print "A little bit of work gets done in B" super(B, self).method(*args) class C(B): def method(self, *args): print "A little bit of work gets done in C" super(C, self).method(*args) However, the work done in C.method() makes the work done in B.method() obsolete: I want one to run, or the other, but not both. C does need to inherit from B, for the sake of the other methods, so I want C.method() *only* to skip B while still inheriting from A. (All other methods have to inherit from B as normal.) So what I have done is change the call to super in C to super(B, self) instead of super(C, self). It seems to work, but is this safe to do? Or are there strange side-effects I haven't seen yet? -- Steven From clp2 at rebertia.com Sun Aug 2 09:02:10 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 Aug 2009 06:02:10 -0700 Subject: Skipping a superclass In-Reply-To: <02857910$0$20667$c3e8da3@news.astraweb.com> References: <02857910$0$20667$c3e8da3@news.astraweb.com> Message-ID: <50697b2c0908020602u37fee362i35019d16b857f755@mail.gmail.com> On Sun, Aug 2, 2009 at 5:36 AM, Steven D'Aprano wrote: > I have a series of subclasses like this: > > class A(object): > ? ?def method(self, *args): > ? ? ? ?print "Lots of work gets done here in the base class" > > class B(A): > ? ?def method(self, *args): > ? ? ? ?print "A little bit of work gets done in B" > ? ? ? ?super(B, self).method(*args) > > class C(B): > ? ?def method(self, *args): > ? ? ? ?print "A little bit of work gets done in C" > ? ? ? ?super(C, self).method(*args) > > > However, the work done in C.method() makes the work done in B.method() > obsolete: I want one to run, or the other, but not both. C does need to > inherit from B, for the sake of the other methods, so I want C.method() > *only* to skip B while still inheriting from A. (All other methods have > to inherit from B as normal.) > > So what I have done is change the call to super in C to super(B, self) > instead of super(C, self). It seems to work, but is this safe to do? Or > are there strange side-effects I haven't seen yet? Barring some true weirdness in super(), I don't /think/ so. It obviously works fine in the single-inheritance case, and (after some brute-force testing) the only permitted multiple inheritances involving C and (A or B) always have C ahead of B in the MRO (method resolution order). The fact that you're wanting to bypass a superclass method might suggest however, that your hierarchy could be structured better. Have you considered moving B.method() into another, new class (e.g. newB) which subclasses B? Then C can inherit from B without inheriting the unwanted method, while B's functionality still exists, just under a new name (newB). Cheers, Chris -- http://blog.rebertia.com From lists at cheimes.de Sun Aug 2 09:08:25 2009 From: lists at cheimes.de (Christian Heimes) Date: Sun, 02 Aug 2009 15:08:25 +0200 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: <7djs50F2bsubuU1@mid.individual.net> References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: Michael M Mason wrote: > I'm running Python 3.1 on Vista and I can't figure out how to add my own > directory to sys.path. > > The docs suggest that I can either add it to the PYTHONPATH environment > variable or to the PythonPath key in the registry. However, PYTHONPATH > doesn't exist, and updating the registry key has no effect (and in any case > the contents aren't the same as sys.path). > > So where does sys.path get its value from, and how do I change it? You can use my PEP 370 (http://python.org/dev/peps/pep-0370/) and a .pth file to extend the search path for modules. >>> import os >>> import site >>> site.USER_SITE '/home/heimes/.local/lib/python2.6/site-packages' >>> if not os.path.isdir(site.USER_SITE): ... os.makedirs(site.USER_SITE) ... >>> pth = open(os.path.join(site.USER_SITE, "michal.pth"), "w") >>> pth.write("C:/Users/Michael/Code/Python\n") >>> pth.close() Restart Python, your custom search path should be in sys.path. Christian From ifl2009 at shu.edu Sun Aug 2 09:34:37 2009 From: ifl2009 at shu.edu (IFL 2009) Date: Sun, 2 Aug 2009 09:34:37 -0400 Subject: IFL 2009: Call for Papers and Participation Message-ID: An HTML attachment was scrubbed... URL: From fatkinson at mishmash.com Sun Aug 2 09:42:52 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sun, 02 Aug 2009 06:42:52 -0700 Subject: Seeding the rand() Generator Message-ID: How does one seed the rand() generator when retrieving random recordings in MySQL? Regards, Fred From jizzai at gmail.com Sun Aug 2 09:50:14 2009 From: jizzai at gmail.com (Jizzai) Date: Sun, 02 Aug 2009 13:50:14 GMT Subject: Is python buffer overflow proof? Message-ID: Is a _pure_ python program buffer overflow proof? For example in C++ you can declare a char[9] to hold user input. If the user inputs 10+ chars a buffer overflow occurs. In python, I cannot seem to find a way to define/restrict a string length. This is probably by design and raises the topic in question. Am curious to see the opinions of people who know. TIA. From albert at spenarnc.xs4all.nl Sun Aug 2 09:54:04 2009 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 02 Aug 2009 13:54:04 GMT Subject: Colour of output text References: <03c4ceed-c49b-4dd0-a585-e6169b02e0eb@26g2000yqk.googlegroups.com> Message-ID: In article , Jean-Michel Pichavant wrote: >Nobody wrote: >> On Fri, 10 Jul 2009 09:23:54 +0000, garabik-news-2005-05 wrote: >> >> >>>>> I would like to learn a way of changing the colour of a particular >>>>> part of the output text. I've tried the following >>>>> >>>> On Unix operating systems this would be done through the curses interface: >>>> >>>> http://docs.python.org/library/curses.html >>>> >>> Or using ANSI colour codes: >>> >>> colours = { >>> 'none' : "", >>> 'default' : "\033[0m", >>> 'bold' : "\033[1m", >>> >> >> [snip] >> >> >>> # non-standard attributes, supported by some terminals >>> >> >> This comment should have appeared immediately after "none" ;) >> >> Hard-coding control/escape sequences is just lame. Use the curses modules >> to obtain the correct sequences for the terminal. >> >> >As the OP I'm really interested in doing so. I currently have all my >colors hard-coded. >Now It may be lame but as soon as I call curses.initscr(), it's just >messing up with my terminal, moreover I didn't figure out how to "print >'hello'" using curses color codes. >Anyone has an example ? I'm pretty sure it may fit in one line. In general initscr() ought to work. It fails if it has no/a wrong idea of what your terminal is. In the same shell as you run run your program type set | grep -i term Now some entry should show up, e.g. TERM=xterm infocmp $TERM should fetch information about your terminal, from the same source as curses does. Possible problems are: - your operating system/configurations lies to curses about the terminal or your terminal is not specified at all - curses has not been properly installed and cannot find the database Groetjes Albert > >JM > > -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From lob8682 at gmail.com Sun Aug 2 09:58:47 2009 From: lob8682 at gmail.com (Kamal Kamal) Date: Sun, 2 Aug 2009 06:58:47 -0700 (PDT) Subject: "PAK WEB" "PAK WEB TV" "PAK WEBSITES" "PAK WEB DIRECTORY" "PAK WEB HOSTING" "PAK WEB HOST" "PAK WEB HOSTING" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" on www.pak-web-pages.blogspot.com Message-ID: "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB TV" www.pak-web-pages.blogspot.com "PAK WEBSITES" www.pak-web-pages.blogspot.com "PAK WEB DIRECTORY" www.pak-web-pages.blogspot.com "PAK WEB HOSTING" www.pak-web-pages.blogspot.com "PAK WEB HOST" www.pak-web-pages.blogspot.com "PAK WEB HOSTING" www.pak-web-pages.blogspot.com "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" "PAK WEB" "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" on www.pak-web-pages.blogspot.com From albert at spenarnc.xs4all.nl Sun Aug 2 10:14:53 2009 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 02 Aug 2009 14:14:53 GMT Subject: A Bug By Any Other Name ... References: Message-ID: In article , J. Cliff Dyer wrote: >On Fri, 2009-07-17 at 20:53 +0000, Albert van der Horst wrote: >> Because unlike in algol 68 in python whitespace is relevant, >> we could get by with requiring whitespace: >> x= -q # okay >> a> 8 ** -2 # okay > >This is actually quite thoroughly untrue. In python, *indentation* is >significant. Whitespace (internal to a line) is not. You can even call >methods like this if you want: You totally don't get it. You describe how python is now. I propose a change to be made to python. Small wonder that that is different from what it is now. > >>>> s = 'abc' >>>> s . upper() >ABC You prove nothing by giving examples. You can disprove by giving one counter example, here it goes. Whitespace (internal to a line) is significant. In Python you cannot change xleftgoing = 123000000 to x left going = 123 000 000 (You can in Algol68) >Obviously, that's A Bad Idea(tm), but python's parser won't stop you. What is a bad idea? Apparently you are not talking about my idea of changing the parser. ("Pythons parser won't stop you from changing the parser" doesn't make sense.) >The ++ operator gotcha is so minor that I can't remember anyone actually >asking about it on the list (who was actually facing it as a >problem--this thread was started by idle speculation). Can we not >change the language syntax to address non-issues? As other languages have an Eleventh Commandment against concatenating operators, the larger issue is hardly futile. > >Practicality beats purity, a.k.a. don't you have something better to do? I'm having a great time, thank you! >Cheers, >Cliff Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From marcusw at cox.net Sun Aug 2 10:32:39 2009 From: marcusw at cox.net (Marcus Wanner) Date: Sun, 02 Aug 2009 10:32:39 -0400 Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: On 8/2/2009 9:50 AM, Jizzai wrote: > Is a _pure_ python program buffer overflow proof? > > For example in C++ you can declare a char[9] to hold user input. > If the user inputs 10+ chars a buffer overflow occurs. > > In python, I cannot seem to find a way to define/restrict a string length. > This is probably by design and raises the topic in question. > > Am curious to see the opinions of people who know. > > TIA. I believe that python is buffer overflow proof. In fact, I think that even ctypes is overflow proof... Marcus From marcusw at cox.net Sun Aug 2 10:36:18 2009 From: marcusw at cox.net (Marcus Wanner) Date: Sun, 02 Aug 2009 10:36:18 -0400 Subject: Seeding the rand() Generator In-Reply-To: References: Message-ID: On 8/2/2009 9:42 AM, Fred Atkinson wrote: > How does one seed the rand() generator when retrieving random > recordings in MySQL? > > Regards, > > > > Fred something like: import random, time random.seed(time.time()) #not actual record access code: sqlite3.recordaccessfuction(recordid = random.rand()) Marcus From lists at cheimes.de Sun Aug 2 10:43:25 2009 From: lists at cheimes.de (Christian Heimes) Date: Sun, 02 Aug 2009 16:43:25 +0200 Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: Marcus Wanner wrote: > I believe that python is buffer overflow proof. In fact, I think that > even ctypes is overflow proof... No, ctypes isn't buffer overflow proof. ctypes can break and crash a Python interpreter easily. Christian From matt.urry at googlemail.com Sun Aug 2 10:45:39 2009 From: matt.urry at googlemail.com (ma3mju) Date: Sun, 2 Aug 2009 07:45:39 -0700 (PDT) Subject: Processes not exiting References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> Message-ID: <206a63e2-9159-44f0-ac5c-a14055448b47@h21g2000yqa.googlegroups.com> On 31 July, 11:27, Piet van Oostrum wrote: > >>>>> ma3mju (m) wrote: > >m> Hi all, > >m> I'm having trouble with multiprocessing I'm using it to speed up some > >m> simulations, I find for large queues when the process reaches the > >m> poison pill it does not exit whereas for smaller queues it works > >m> without any problems. Has anyone else had this trouble? Can anyone > >m> tell me a way around it? The code is in two files below. > > How do you know it doesn't exit. You haven't shown any of your output. > > I did discover a problem in your code, but it should cause an exception: > > >m> #set off some of the easy workers on the hard work (maybe double > >m> number of hard) > >m> for i in range(0,num_hard_workers): > >m> ? ? hard_work_queue.put(None) > >m> ? ? hard_workers.append(multiprocessing.Process > >m> (target=GP.RandomWalkGeneralizationErrorParallel,args= > >m> (hard_work_queue,result_queue,))) > >m> #wait for all hard workers to finish > >m> for worker in hard_workers: > >m> ? ? worker.join() > > Here you create new hard workers, but you never start them. The join > should then give an exception when it reaches these. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org Ok thanks I'll change that In a sec, It never reaches that bit of code because the easy_workers don't exit so it never gets past the join(). As far as running it goes I get the datapt and number of points printed to the list for everything in both queues. When it reaches the end of either queue I get "Poison" on the screen then "here" for each process but I don't get "worker joined" and as expected don't get "this should not appear". If I have a look at the processes running after all queues are supposed to have finished I see all of them running taking little or no resources. This is running on Ubuntu Jaunty at home and the same happens on the Debian machine at uni. The weird thing is that if I run them with less points the processes do manage to exit. Thanks Matt From matt.urry at googlemail.com Sun Aug 2 10:48:44 2009 From: matt.urry at googlemail.com (ma3mju) Date: Sun, 2 Aug 2009 07:48:44 -0700 (PDT) Subject: Processes not exiting References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> Message-ID: <61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com> On 31 July, 11:34, MRAB wrote: > ma3mju wrote: > > Hi all, > > > I'm having trouble with multiprocessing I'm using it to speed up some > > simulations, I find for large queues when the process reaches the > > poison pill it does not exit whereas for smaller queues it works > > without any problems. Has anyone else had this trouble? Can anyone > > tell me a way around it? The code is in two files below. > > [snip] > > > #get number of cores and set the number on concurrent processes > > num_hard_workers = 2 > > num_workers = multiprocessing.cpu_count()*1.5 > > easy_workers = [] > > hard_workers = [] > > #add poison pill for each worker and create the worker > > for i in range(0,num_workers-num_hard_workers): > > ? ? easy_work_queue.put(None) > > ? ? easy_workers.append(multiprocessing.Process > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > (easy_work_queue,result_queue,))) > > for i in range(0,num_hard_workers): > > ? ? hard_work_queue.put(None) > > ? ? hard_workers.append(multiprocessing.Process > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > (hard_work_queue,result_queue,))) > > You have 2 hard workers and ceil(CPU_count * 1.5) - 2 easy workers. > What if the number of CPUs was 1? That would give 2 hard and 0 easy! > > Also, I recommend that you put only 1 'poison pill' in each queue and > have the workers put it back when they see it. I'll give that a go in a sec and see if it helps. The processes quit out for smaller queues though so it should in theory be alright. I'm not too fussed about the CPU's it's only there because I change between a uni PC and home one with a different number of cores in each but both greater than one. From Scott.Daniels at Acm.Org Sun Aug 2 11:11:22 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 02 Aug 2009 08:11:22 -0700 Subject: Predefined Variables In-Reply-To: References: Message-ID: Piet van Oostrum wrote: >>>>>> Scott David Daniels (SDD) wrote: >> SDD> Stephen Cuppett (should have written in this order): >>>> "Fred Atkinson" wrote ... >>>>> Is there a pre-defined variable that returns the GET line... >>>> os.environment('QUERY_STRING') >> SDD> Maybe you mean: >> SDD> os.environ['USER'] > Let's take the best of both: > os.environ['QUERY_STRING'] Sorry about that. I was testing expression before posting, and I don't do that much cgi stuff. I forgot to restore the variable name. --Scott David Daniels Scott.Daniels at Acm.Org From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 11:18:27 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 15:18:27 GMT Subject: Is python buffer overflow proof? References: Message-ID: <02859ef9$0$20667$c3e8da3@news.astraweb.com> On Sun, 02 Aug 2009 13:50:14 +0000, Jizzai wrote: > Is a _pure_ python program buffer overflow proof? It's supposed to be. > For example in C++ you can declare a char[9] to hold user input. If the > user inputs 10+ chars a buffer overflow occurs. > > In python, I cannot seem to find a way to define/restrict a string > length. This is probably by design and raises the topic in question. That's a separate issue from being buffer overflow proof. You can't specify that a string have a maximum of N characters except by slicing the string after it's formed: s = "x"*10000 # Make a big string. s = s[:100] # Limit it to 100 characters. But Python won't overflow any buffers even if you try to create a truly huge string: s = "x"*(1024**4) # Try to create a 1 TB string. Your PC will run slow while Python and the OS tries to allocate 1TB of memory, then it will safely raise MemoryError. Pure Python should never dump core. -- Steven From Scott.Daniels at Acm.Org Sun Aug 2 11:53:50 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 02 Aug 2009 08:53:50 -0700 Subject: Seeding the rand() Generator In-Reply-To: References: Message-ID: Fred Atkinson wrote: > How does one seed the rand() generator when retrieving random > recordings in MySQL? It is not entirely clear what you are asking. If you are talking about MySQL's random number generator, you are talking in the wrong newsgroup. If you are talking about Python's, does this work? import random random.seed(123542552) I'm not quite sure how you came to believe that Python controls MySQL, as opposed to using its services. --Scott David Daniels Scott.Daniels at Acm.Org From matt.urry at googlemail.com Sun Aug 2 12:57:44 2009 From: matt.urry at googlemail.com (ma3mju) Date: Sun, 2 Aug 2009 09:57:44 -0700 (PDT) Subject: Processes not exiting References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> <61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com> Message-ID: <01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> On 2 Aug, 15:48, ma3mju wrote: > On 31 July, 11:34, MRAB wrote: > > > > > ma3mju wrote: > > > Hi all, > > > > I'm having trouble with multiprocessing I'm using it to speed up some > > > simulations, I find for large queues when the process reaches the > > > poison pill it does not exit whereas for smaller queues it works > > > without any problems. Has anyone else had this trouble? Can anyone > > > tell me a way around it? The code is in two files below. > > > [snip] > > > > #get number of cores and set the number on concurrent processes > > > num_hard_workers = 2 > > > num_workers = multiprocessing.cpu_count()*1.5 > > > easy_workers = [] > > > hard_workers = [] > > > #add poison pill for each worker and create the worker > > > for i in range(0,num_workers-num_hard_workers): > > > ? ? easy_work_queue.put(None) > > > ? ? easy_workers.append(multiprocessing.Process > > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > > (easy_work_queue,result_queue,))) > > > for i in range(0,num_hard_workers): > > > ? ? hard_work_queue.put(None) > > > ? ? hard_workers.append(multiprocessing.Process > > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > > (hard_work_queue,result_queue,))) > > > You have 2 hard workers and ceil(CPU_count * 1.5) - 2 easy workers. > > What if the number of CPUs was 1? That would give 2 hard and 0 easy! > > > Also, I recommend that you put only 1 'poison pill' in each queue and > > have the workers put it back when they see it. > > I'll give that a go in a sec and see if it helps. The processes quit > out for smaller queues though so it should in theory be alright. I'm > not too fussed about the CPU's it's only there because I change > between a uni PC and home one with a different number of cores in each > but both greater than one. Just tried changing the poison pill part to no avail sadly From tjreedy at udel.edu Sun Aug 2 14:07:44 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 02 Aug 2009 14:07:44 -0400 Subject: Generate a new object each time a name is imported In-Reply-To: References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: Peter Otten wrote: > Steven D'Aprano wrote: >> I'm looking for a way to hide the generation of objects from the caller, >> so I could do something like this: >> >> from Module import factory() as a # a == "Object #1" >> from Module import factory() as b # b == "Object #2" >> >> except of course that syntax is illegal. > > How about For newbies who do not get how the following works, but would like to know, I am adding some explanation. >>>> class A(object): > ... def __init__(self): > ... self._n = 0 > ... @property > ... def a(self): > ... try: > ... return self._n > ... finally: > ... self._n += 1 The @property decorator turns the 'a' function into the hidden getter function for what looks to the outside world like a simple instance attribute named 'a'. >>>> import sys >>>> sys.modules["yadda"] = A() sys.modules is a system namespace that normally associates names with modules. It is used by import statements to find existing modules. However, there is no requirement that the associated object actually be a module. A module is simply a collection of objects accessed as attributes. One can get and set attributes of a module, and but hardly anyhing else. Other attribute collection objects will do as well as far as imports are concerned. 'If it quack like a duck (module in this case)...' The above sets the 'module' to an *instance* of class A. >>>> from yadda import a This looks for the 'module' named 'yadda'. It finds one - the instance of A. It then requests attribute 'a' (of that instance). That request is routed to the getter function. This import statement could be in any module, not just the one that set A() as a module surrogate. >>>> from yadda import a as b >>>> a, b > (0, 1) As Peter mentioned in his followup, module surrogates were intended for lazy imports of expensive-to-compute attributes that might never be needed, so their creation could be delayed to whenever needed, if ever. Tricks like the above are not recommended for normal usage, but do illstrate some aspects of the language. Terry Jan Reedy From catalinfest at gmail.com Sun Aug 2 14:13:13 2009 From: catalinfest at gmail.com (catafest) Date: Sun, 2 Aug 2009 11:13:13 -0700 (PDT) Subject: How to read webpage References: Message-ID: <44c17767-e08e-4c8c-ae1f-0e11e54d3485@o6g2000yqj.googlegroups.com> Maybe your python2.5 not working good!? But, I use python 2.6 , and i use this for your problem: import urllib html = urllib.urlopen("http://www.rediff.com/").read() print html If you want use authenticate then... You make working urllib2 and use this >>>auth = urllib2.Request(auth_uri, authreq_data) On Aug 1, 4:52?pm, MRAB wrote: > tarun wrote: > > Dear All, > > I want to read a webpage and copy the contents of it in word file. I > > tried to write following code: > > > import urllib2 > > urllib2.urlopen("http://www.rediff.com/") > > > *Error:-* > > > ? ? urllib2.urlopen("http://www.icicibank.com/") > > ? File "C:\Python25\lib\urllib2.py", line 121, in urlopen > > ? ? return _opener.open(url, data) > > ? File "C:\Python25\lib\urllib2.py", line 374, in open > > ? ? response = self._open(req, data) > > ? File "C:\Python25\lib\urllib2.py", line 392, in _open > > ? ? '_open', req) > > ? File "C:\Python25\lib\urllib2.py", line 353, in _call_chain > > ? ? result = func(*args) > > ? File "C:\Python25\lib\urllib2.py", line 1100, in http_open > > ? ? return self.do_open(httplib.HTTPConnection, req) > > ? File "C:\Python25\lib\urllib2.py", line 1075, in do_open > > ? ? raise URLError(err) > > urllib2.URLError: > > I've just tried it. I didn't get an exception, so your problem must be > elsewhere. From python at mrabarnett.plus.com Sun Aug 2 14:25:36 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 02 Aug 2009 19:25:36 +0100 Subject: Processes not exiting In-Reply-To: <01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> <61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com> <01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> Message-ID: <4A75DA20.7050209@mrabarnett.plus.com> ma3mju wrote: > On 2 Aug, 15:48, ma3mju wrote: >> On 31 July, 11:34, MRAB wrote: >> >> >> >>> ma3mju wrote: >>>> Hi all, >>>> I'm having trouble with multiprocessing I'm using it to speed up some >>>> simulations, I find for large queues when the process reaches the >>>> poison pill it does not exit whereas for smaller queues it works >>>> without any problems. Has anyone else had this trouble? Can anyone >>>> tell me a way around it? The code is in two files below. >>> [snip] >>>> #get number of cores and set the number on concurrent processes >>>> num_hard_workers = 2 >>>> num_workers = multiprocessing.cpu_count()*1.5 >>>> easy_workers = [] >>>> hard_workers = [] >>>> #add poison pill for each worker and create the worker >>>> for i in range(0,num_workers-num_hard_workers): >>>> easy_work_queue.put(None) >>>> easy_workers.append(multiprocessing.Process >>>> (target=GP.RandomWalkGeneralizationErrorParallel,args= >>>> (easy_work_queue,result_queue,))) >>>> for i in range(0,num_hard_workers): >>>> hard_work_queue.put(None) >>>> hard_workers.append(multiprocessing.Process >>>> (target=GP.RandomWalkGeneralizationErrorParallel,args= >>>> (hard_work_queue,result_queue,))) >>> You have 2 hard workers and ceil(CPU_count * 1.5) - 2 easy workers. >>> What if the number of CPUs was 1? That would give 2 hard and 0 easy! >>> Also, I recommend that you put only 1 'poison pill' in each queue and >>> have the workers put it back when they see it. >> I'll give that a go in a sec and see if it helps. The processes quit >> out for smaller queues though so it should in theory be alright. I'm >> not too fussed about the CPU's it's only there because I change >> between a uni PC and home one with a different number of cores in each >> but both greater than one. > > Just tried changing the poison pill part to no avail sadly I wonder whether one of the workers is raising an exception, perhaps due to lack of memory, when there are large number of jobs to process. Another question: why are you distinguishing between easy and hard jobs? Do you actually get a measurable improvement in performance from doing it this way instead of having just a single queue of jobs and a single pool of workers? From piet at cs.uu.nl Sun Aug 2 14:26:55 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 02 Aug 2009 20:26:55 +0200 Subject: Get Cliet IP Address References: Message-ID: >>>>> Fred Atkinson (FA) wrote: >FA> What is the function to obtain the client browser's IP >FA> address? You mean in a web server? The following should work (and was posted by me not long ago): from os import getenv ip = (getenv("HTTP_CLIENT_IP") or getenv("HTTP_X_FORWARDED_FOR") or getenv("HTTP_X_FORWARDED_FOR") or getenv("REMOTE_ADDR") or "UNKNOWN") I use getenv() rather than environ[] to avoid exceptions. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From piet at cs.uu.nl Sun Aug 2 14:31:07 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 02 Aug 2009 20:31:07 +0200 Subject: cgi script References: Message-ID: >>>>> golu (g) wrote: >g> Hi, >g> i started learning cgi few days ago in python and everything went >g> fine until i started getting the follwing error >g> " >g> The server encountered an internal error and was unable to complete >g> your request. Either the server is overloaded or there was an error in >g> a CGI script. >g> If you think this is a server error, please contact the webmaster. " >g> i am using apache on xampp. plz help Putting the following in your script might help as it will show the exception trace in your browser (if it gets that far, that is). import cgitb cgitb.enable() -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From REMpeteOVE at petezilla.co.uk Sun Aug 2 15:21:06 2009 From: REMpeteOVE at petezilla.co.uk (Peter Chant) Date: Sun, 02 Aug 2009 20:21:06 +0100 Subject: Building / making an application Message-ID: <2i5hk6-8gh.ln1@phoenix.fire> What is a good way to do this? There are instructions on making modules at: http://docs.python.org/distutils/setupscript.html however, what do you do if you don't want a module? I'm thinking of where I'd like to split the code into several files and have a build / setup script put it together and install it somewhere such as /usr/local/bin. I'm interested in what the standard way of doing this is. Thanks, Pete -- http://www.petezilla.co.uk From piet at cs.uu.nl Sun Aug 2 15:25:02 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 02 Aug 2009 21:25:02 +0200 Subject: socket policy flash help References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> <8bede581-f260-4c69-abf0-1e8071380b76@z4g2000prh.googlegroups.com> <7e6cdc26-bcc0-4503-b7b4-9ad80b1041f6@v37g2000prg.googlegroups.com> Message-ID: >>>>> NighterNet (N) wrote: >N> Here the full code. >N> flashpolicy.xml >N> [[[ >N> >N> >N> >N> >N> ]]] >N> flashpolicytest_server3x.py >N> [[[ >N> #!/usr/local/bin/python >N> ''' >N> Still under testing... >N> python version 3.x.x >N> ''' >N> import socket >N> import threading >N> import sys >N> import os >N> file_name = 'flashpolicy.xml' >N> fh = open(file_name, "r") >N> policy = fh.read(10001) You never use that variable. >N> host = ''; #out side network >N> port = 5555; >N> print ("# ------------- Init... ------------- #"); >N> class ClientThread (threading.Thread): >N> global policy; >N> allClients = []; >N> vlock = threading.Lock(); >N> id = 0 # next available thread number >N> def __init__(self,clientSocket): >N> threading.Thread.__init__(self) >N> self.sockfd = clientSocket; #socket client >N> self.name = ''; >N> ClientThread.id += 1 >N> self.id = ClientThread.id >N> self.nickName = ''; >N> self.allClients.append(self.sockfd); >N> def sendAll(self,buff): >N> for index,clientSock in enumerate(self.allClients): >N> try: >N> clientSock.send(buff); There is no guarantee that send will indeed transmit all of buff. It is better to use clientSock.sendall(buff). Or you should check the return value of send and check if it is equal to the length of buff. And repeat if not. (But sendall is easier). Also don't use ; at the end of the statement. It's not pythonic. >N> except (socket.error): >N> print ('error socket %s\n',index,"| clean"); >N> clientSock.close() >N> del self.allClients[index] >N> def run(self): >N> while True: >N> buff = self.sockfd.recv(1028); There is no guarantee that recv will get the whole message. It may even get as little as 1 byte. So you should check the return value of recv. The official way is to keep reading until you have enough input or until you hit end of file. >N> if not buff: >N> print ("connect close...(client side)"); >N> self.sockfd.close(); >N> break #incase it loop infinite >N> if str(buff) == str("b\'\\x00\'"): What you check here is whether buff contains the byte sequence that starts with a b, then a ' ... and ending with the 5 bytes \ x 0 0 ' which is wrong. Actually it should be: if buff == b\'\x00': or if buff == b\'\0': >N> print ('policy FOUND >>> sending...') >N> print(buff) >N> b = b'N> from domain=\"*\" to-ports=\"*\" />' >N> print (b) >N> self.sockfd.send(b); >N> self.sockfd.sendall(b); Only self.sockfd.sendall; delete the line with self.sockfd.send(b). And remove the semicolons for esthetical reasons. >N> Some odd reason I can't send flash policy from python to flash socket >N> to agrees with the connection. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From hackingkk at gmail.com Sun Aug 2 15:32:10 2009 From: hackingkk at gmail.com (Krishnakant) Date: Mon, 03 Aug 2009 01:02:10 +0530 Subject: Building / making an application In-Reply-To: <2i5hk6-8gh.ln1@phoenix.fire> References: <2i5hk6-8gh.ln1@phoenix.fire> Message-ID: <1249241530.4541.12.camel@krishna-laptop> On Sun, 2009-08-02 at 20:21 +0100, Peter Chant wrote: > What is a good way to do this? There are instructions on making modules at: > > http://docs.python.org/distutils/setupscript.html > > however, what do you do if you don't want a module? I'm thinking of where > I'd like to split the code into several files and have a build / setup > script put it together and install it somewhere such as /usr/local/bin. > I'm interested in what the standard way of doing this is. > Have you considered creating a deb or rpm package for your application? Most of the documentation for deb or rpm will talk about make files. But even a distutil based python package (with a setup.py) can be made into a deb package. Then the your requirement will be satisfied at least for most gnu/linux based distros. happy hacking. Krishnakant. From REMpeteOVE at petezilla.co.uk Sun Aug 2 16:00:15 2009 From: REMpeteOVE at petezilla.co.uk (Peter Chant) Date: Sun, 02 Aug 2009 21:00:15 +0100 Subject: Building / making an application References: <2i5hk6-8gh.ln1@phoenix.fire> Message-ID: Krishnakant wrote: > Have you considered creating a deb or rpm package for your application? > Most of the documentation for deb or rpm will talk about make files. > But even a distutil based python package (with a setup.py) can be made > into a deb package. > Then the your requirement will be satisfied at least for most gnu/linux > based distros. I'm a slacker, so what I would do would be to make a slack build, the slackbuild would take the source and build that. The stage I am at is the "how to build the source" stage. Don't really intend to get as far as distribution specific packages. What I could do is create a script in the source root directory (that sounds a bit overblown) that simply concatenates together all the python files in the right order and perhaps copies the result to /usr/local/bin or /usr/bin as appropriate. Is that the right way to go? It looks like distutils is appropriate only for modules. OTOH it might be appropriate to put the bulk of an application in a module and have a function calling it the only part of the main script. Pete -- http://www.petezilla.co.uk From deets at nospam.web.de Sun Aug 2 16:08:00 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 02 Aug 2009 22:08:00 +0200 Subject: Building / making an application In-Reply-To: References: <2i5hk6-8gh.ln1@phoenix.fire> Message-ID: <7dma10F2cd7tnU1@mid.uni-berlin.de> Peter Chant schrieb: > Krishnakant wrote: > > >> Have you considered creating a deb or rpm package for your application? >> Most of the documentation for deb or rpm will talk about make files. >> But even a distutil based python package (with a setup.py) can be made >> into a deb package. >> Then the your requirement will be satisfied at least for most gnu/linux >> based distros. > > I'm a slacker, so what I would do would be to make a slack build, the > slackbuild would take the source and build that. The stage I am at is > the "how to build the source" stage. Don't really intend to get as far as > distribution specific packages. > > What I could do is create a script in the source root directory (that sounds > a bit overblown) that simply concatenates together all the python files in > the right order and perhaps copies the result to /usr/local/bin or /usr/bin > as appropriate. Is that the right way to go? It looks like distutils is > appropriate only for modules. > > OTOH it might be appropriate to put the bulk of an application in a module > and have a function calling it the only part of the main script. You should consider using setuptools. Then you get an egg that people can install, and you can define "console_scripts"-entry-points which will be installed into /usr/local/bin or similar locations. Diez From aahz at pythoncraft.com Sun Aug 2 16:15:00 2009 From: aahz at pythoncraft.com (Aahz) Date: 2 Aug 2009 13:15:00 -0700 Subject: Help with Regex for domain names References: <0422bf8f-ce59-4de2-a1a4-b16a32e5f152@o15g2000yqm.googlegroups.com> Message-ID: In article , MRAB wrote: >Nobody wrote: >> On Thu, 30 Jul 2009 10:29:09 -0700, rurpy wrote: >> >>>> regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)') >>> You might also want to consider that some country >>> codes such as "co" for Columbia might match more than >>> you want, for example: >>> >>> re.match(r'[\w\-\.]+\.(?:us|au|de|co)', 'foo.boo.com') >>> >>> will match. >> >> ... so put \b at the end, i.e.: >> >> regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)\b') >> >It would still match "www.bbc.co.uk", so you might need: > >regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)\b(?!\.\b)') If it's a string containing just the candidate domain, you can do regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)$') -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Many customs in this life persist because they ease friction and promote productivity as a result of universal agreement, and whether they are precisely the optimal choices is much less important." --Henry Spencer From piet at cs.uu.nl Sun Aug 2 16:49:05 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 02 Aug 2009 22:49:05 +0200 Subject: Processes not exiting References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> <61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com> <01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> Message-ID: >>>>> MRAB (M) wrote: >M> I wonder whether one of the workers is raising an exception, perhaps due >M> to lack of memory, when there are large number of jobs to process. But that wouldn't prevent the join. And you would probably get an exception traceback printed. I wonder if something fishy is happening in the multiprocessing infrastructure. Or maybe the Fortran code goes wrong because it has no protection against buffer overruns and similar problems, I think. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From fatkinson at mishmash.com Sun Aug 2 17:18:28 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sun, 02 Aug 2009 14:18:28 -0700 Subject: Seeding the rand() Generator References: Message-ID: On Sun, 02 Aug 2009 08:53:50 -0700, Scott David Daniels wrote: >Fred Atkinson wrote: >> How does one seed the rand() generator when retrieving random >> recordings in MySQL? > >It is not entirely clear what you are asking. If you are talking about >MySQL's random number generator, you are talking in the wrong newsgroup. >If you are talking about Python's, does this work? > import random > random.seed(123542552) >I'm not quite sure how you came to believe that Python controls MySQL, >as opposed to using its services. > >--Scott David Daniels >Scott.Daniels at Acm.Org I am coding in Python. I am accessing a MySQL database. I have a string to instruct the MySQL database to use the 'rand()' function to randomly choose one of the records in the database. I know how to seed it in PHP. Does anyone know how to see it from with Python? Regards, Fred From fatkinson at mishmash.com Sun Aug 2 17:20:02 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sun, 02 Aug 2009 14:20:02 -0700 Subject: Predefined Variables References: Message-ID: On Sun, 02 Aug 2009 08:11:22 -0700, Scott David Daniels wrote: >Piet van Oostrum wrote: >>>>>>> Scott David Daniels (SDD) wrote: >>> SDD> Stephen Cuppett (should have written in this order): >>>>> "Fred Atkinson" wrote ... >>>>>> Is there a pre-defined variable that returns the GET line... >>>>> os.environment('QUERY_STRING') >>> SDD> Maybe you mean: >>> SDD> os.environ['USER'] >> Let's take the best of both: >> os.environ['QUERY_STRING'] > >Sorry about that. I was testing expression before posting, and I don't >do that much cgi stuff. I forgot to restore the variable name. > >--Scott David Daniels >Scott.Daniels at Acm.Org I finally got it to work with x =getenv('QUERY_STRING') Regards, Fred From victorsubervi at gmail.com Sun Aug 2 17:22:20 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 2 Aug 2009 16:22:20 -0500 Subject: RE Question Message-ID: <4dc0cfea0908021422x43972682ra58c53a2a43351ee@mail.gmail.com> Hi; How do I search and replace something like this: aLine = re.sub('[<]?[p]?[>]?[<]?[b]?[>]?', '', aLine) where RE *only* looks for the possibility of "

" at the beginning of the string; that is, not the individual components as I have it coded above, but the entire 3-character block? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcusw at cox.net Sun Aug 2 17:51:11 2009 From: marcusw at cox.net (Marcus Wanner) Date: Sun, 02 Aug 2009 17:51:11 -0400 Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: On 8/2/2009 10:43 AM, Christian Heimes wrote: > Marcus Wanner wrote: >> I believe that python is buffer overflow proof. In fact, I think that >> even ctypes is overflow proof... > > No, ctypes isn't buffer overflow proof. ctypes can break and crash a > Python interpreter easily. > > Christian > I see. I thought that it said "invalid array index" when you try to read/write outside of an array's bounds, though... Marcus From REMpeteOVE at petezilla.co.uk Sun Aug 2 18:26:08 2009 From: REMpeteOVE at petezilla.co.uk (Peter Chant) Date: Sun, 02 Aug 2009 23:26:08 +0100 Subject: Building / making an application References: <2i5hk6-8gh.ln1@phoenix.fire> <7dma10F2cd7tnU1@mid.uni-berlin.de> Message-ID: <0dghk6-12j.ln1@phoenix.fire> Diez B. Roggisch wrote: > You should consider using setuptools. Then you get an egg that people > can install, and you can define "console_scripts"-entry-points which > will be installed into /usr/local/bin or similar locations. Interesting, I think I need to have a play with that. The cross platform bit could be useful as well. Pete -- http://www.petezilla.co.uk From missive at hotmail.com Sun Aug 2 18:27:49 2009 From: missive at hotmail.com (Lee Harr) Date: Mon, 3 Aug 2009 02:57:49 +0430 Subject: [ANNC] pybotwar-0.3 Message-ID: pybotwar is a fun and educational game where players create computer programs to control simulated robots to compete in a battle arena. http://pybotwar.googlecode.com/ pybotwar uses pybox2d for the physical simulation, and uses pygame and pygsear for the visualization. pybotwar is released under GPLv3. Changes in pybotwar-0.3: - make tarball extract in to versioned directory _________________________________________________________________ With Windows Live, you can organize, edit, and share your photos. http://www.microsoft.com/middleeast/windows/windowslive/products/photo-gallery-edit.aspx From suruti94 at gmail.com Sun Aug 2 19:22:45 2009 From: suruti94 at gmail.com (Mohan Parthasarathy) Date: Sun, 2 Aug 2009 16:22:45 -0700 Subject: Python docs disappointing In-Reply-To: References: Message-ID: <89dd3da60908021622k9967c90raa98afff1881bcc4@mail.gmail.com> I am a newbie and about a month old with Python. There is a wealth of material about Python and I am really enjoying learning Python. One thing that could have helped Python documentation is that instead of the very "raw" doc string, it could have used something like PythonDoc (java doc style) so that the functions/classes are documented better. At least I am planning to use PythonDoc for the code that I am going to write. Let me know if there is a better one.. -mohan On Fri, Jul 31, 2009 at 1:10 PM, kj wrote: > > > > I'm pretty new to Python, and I like a lot overall, but I find the > documentation for Python rather poor, overall. > > I'm sure that Python experts don't have this problem: they have > internalized some good ways to access the documentation, are > productive with it, and therefore have lost the ability to see why > the Python documentations is deficient for beginners. This explains > why a suboptimal situation can persist like this: those who are > most able fix it are also the least able to perceive it. > > I've heard similar complaints from other experienced programmers > who are trying out Python for the first time: poor documentation. > > Here is an *entirely typical* example: on some Unix, try > > % pydoc urllib > > The displayed documentation mention the optional parameter "data" > in practically every function listed (a few dozen of them). This > parameter is not documented *anywhere* on that page. All that we > are told is that its default value is always None. > > I'm sure that I can find a full description of this parameter if > I fire up Google, and search online. In fact, more likely than > not, I'll find far more documentation than I want. But my point > is that a programmer should not need to do this. The full > documentation should be readily accessible directly through a few > keystrokes. > > I would love to know how experienced Python programmers quickly > zero in on the Python documentation they need. > > TIA! > > kynn > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Aug 2 19:40:20 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 Aug 2009 16:40:20 -0700 Subject: Python docs disappointing In-Reply-To: <89dd3da60908021622k9967c90raa98afff1881bcc4@mail.gmail.com> References: <89dd3da60908021622k9967c90raa98afff1881bcc4@mail.gmail.com> Message-ID: <50697b2c0908021640o38f1de9fnd778da4d985c4672@mail.gmail.com> > On Fri, Jul 31, 2009 at 1:10 PM, kj wrote: >> I'm pretty new to Python, and I like a lot overall, but I find the >> documentation for Python rather poor, overall. >> >> I'm sure that Python experts don't have this problem: they have >> internalized some good ways to access the documentation, are >> productive with it, and therefore have lost the ability to see why >> the Python documentations is deficient for beginners. ?This explains >> why a suboptimal situation can persist like this: those who are >> most able fix it are also the least able to perceive it. >> >> I've heard similar complaints from other experienced programmers >> who are trying out Python for the first time: poor documentation. >> >> Here is an *entirely typical* example: on some Unix, try >> >> % pydoc urllib >> >> The displayed documentation mention the optional parameter "data" >> in practically every function listed (a few dozen of them). ?This >> parameter is not documented *anywhere* on that page. ?All that we >> are told is that its default value is always None. >> >> I'm sure that I can find a full description of this parameter if >> I fire up Google, and search online. ?In fact, more likely than >> not, I'll find far more documentation than I want. ?But my point >> is that a programmer should not need to do this. ?The full >> documentation should be readily accessible directly through a few >> keystrokes. >> >> I would love to know how experienced Python programmers quickly >> zero in on the Python documentation they need. On Sun, Aug 2, 2009 at 4:22 PM, Mohan Parthasarathy wrote: > I am a newbie and about a month old with Python. There is a wealth of > material about Python and I am really enjoying learning Python. > > One thing that could have helped Python documentation is that instead of the > very "raw" doc string, it could have used something like PythonDoc (java doc > style) so that the functions/classes are documented better. At least I am > planning to use PythonDoc for the code that I am going to write. Let me know > if there is a better one.. If you use reStructuredText (http://docutils.sf.net/rst.html), you can leverage Sphinx (http://sphinx.pocoo.org/), which generates the superb-looking official Python docs. Cheers, Chris P.S. Please don't top-post (http://en.wikipedia.org/wiki/Top-post) in the future. -- http://blog.rebertia.com From pavlovevidence at gmail.com Sun Aug 2 20:00:40 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 Aug 2009 17:00:40 -0700 (PDT) Subject: Seeding the rand() Generator References: Message-ID: On Aug 2, 2:18?pm, Fred Atkinson wrote: > On Sun, 02 Aug 2009 08:53:50 -0700, Scott David Daniels > > wrote: > >Fred Atkinson wrote: > >> ? ? ? ?How does one seed the rand() generator when retrieving random > >> recordings in MySQL? ? > > >It is not entirely clear what you are asking. ?If you are talking about > >MySQL's random number generator, you are talking in the wrong newsgroup. > >If you are talking about Python's, does this work? > > ? ? import random > > ? ? random.seed(123542552) > >I'm not quite sure how you came to believe that Python controls MySQL, > >as opposed to using its services. > > >--Scott David Daniels > >Scott.Dani... at Acm.Org > > ? ? ? ? I am coding in Python. ? > > ? ? ? ? I am accessing a MySQL database. ? > > ? ? ? ? I have a string to instruct the MySQL database to use the > 'rand()' function to randomly choose one of the records in the > database. ? > > ? ? ? ? I know how to seed it in PHP. ?Does anyone know how to see it > from with Python? ? It sounds like you are using MySQL's rand() function, which means that whatever SQL command you used to seed it in PHP is the same command you would use to seed it in Python. You'll have to give us more information if you want a better answer than that. Carl Banks From lists at cheimes.de Sun Aug 2 20:39:34 2009 From: lists at cheimes.de (Christian Heimes) Date: Mon, 03 Aug 2009 02:39:34 +0200 Subject: Python docs disappointing In-Reply-To: <89dd3da60908021622k9967c90raa98afff1881bcc4@mail.gmail.com> References: <89dd3da60908021622k9967c90raa98afff1881bcc4@mail.gmail.com> Message-ID: Mohan Parthasarathy schrieb: > I am a newbie and about a month old with Python. There is a wealth of > material about Python and I am really enjoying learning Python. > > One thing that could have helped Python documentation is that instead of the > very "raw" doc string, it could have used something like PythonDoc (java doc > style) so that the functions/classes are documented better. At least I am > planning to use PythonDoc for the code that I am going to write. Let me know > if there is a better one.. Several projects are trying to improve the doc strings with an extended syntax. Personally I prefer the epytext syntax from epydoc [1]. It's a JavaDoc like markup language that extends the raw doc strings with useful information. Christian [1] http://epydoc.sourceforge.net/manual-epytext.html From r1chardj0n3s at gmail.com Sun Aug 2 21:07:55 2009 From: r1chardj0n3s at gmail.com (Richard Jones) Date: Mon, 3 Aug 2009 11:07:55 +1000 Subject: Registation is open for the 9th PyWeek game programming challenge! Message-ID: <3A356906-89BE-47A4-9ECE-4C87A7EA89BE@gmail.com> The ninth PyWeek challenge will run between: Sunday 30th August to Sunday 6th September (00:00UTC to 00:00UTC) The PyWeek challenge invites entrants to write a game in one week from scratch either as an individual or in a team. Entries must be developed in Python, during the challenge, and must incorporate some theme chosen at the start of the challenge. REGISTRATION IS NOW OPEN -- Visit the challenge website to sign up, join discussions in the message board or read the timetable and rules: http://www.pyweek.org/9/ PLANNING FOR THE CHALLENGE -- Make sure you have working versions of the libraries you're going to use. The rules page has a list of libraries and other resources. Make sure you can build packages to submit as your final submission (if you're going to use py2exe, make sure you know how to use it and that it works). If you don't have access to Linux, Windows or a Mac to test on, contact friends, family or other competitors to find someone who is able to test for you. From milesck at umich.edu Sun Aug 2 21:15:10 2009 From: milesck at umich.edu (Miles Kaufmann) Date: Sun, 2 Aug 2009 18:15:10 -0700 Subject: Skipping a superclass In-Reply-To: <02857910$0$20667$c3e8da3@news.astraweb.com> References: <02857910$0$20667$c3e8da3@news.astraweb.com> Message-ID: <3597BCD2-E6D1-4A76-85A2-6C1CA3D8B40B@umich.edu> On Aug 2, 2009, at 5:36 AM, Steven D'Aprano wrote: > I have a series of subclasses like this: > > class A(object): > def method(self, *args): > print "Lots of work gets done here in the base class" > > class B(A): > def method(self, *args): > print "A little bit of work gets done in B" > super(B, self).method(*args) > > class C(B): > def method(self, *args): > print "A little bit of work gets done in C" > super(C, self).method(*args) > > > However, the work done in C.method() makes the work done in B.method() > obsolete: I want one to run, or the other, but not both. C does need > to > inherit from B, for the sake of the other methods, so I want > C.method() > *only* to skip B while still inheriting from A. (All other methods > have > to inherit from B as normal.) This might not be applicable to the larger problem you're trying to solve, but for this sample, I would write it as: class A(object): def method(self, *args): self._method(*args) print "Lots of work gets done here in the base class" def _method(self, *args): pass # or perhaps raise NotImplemented class B(A): def _method(self, *args): print "A little bit of work gets done in B" class C(B): def _method(self, *args): print "A little bit of work gets done in C" > So what I have done is change the call to super in C to super(B, self) > instead of super(C, self). It seems to work, but is this safe to do? > Or > are there strange side-effects I haven't seen yet? In a diamond-inheritance situation, you may end up skipping methods besides just B.method(). -Miles From wuwei23 at gmail.com Sun Aug 2 21:23:39 2009 From: wuwei23 at gmail.com (alex23) Date: Sun, 2 Aug 2009 18:23:39 -0700 (PDT) Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: <182b3193-d249-4887-ad23-b9c5a3b6dcd8@y4g2000prf.googlegroups.com> On Aug 3, 4:07?am, Terry Reedy wrote: > Peter Otten wrote: > > Steven D'Aprano wrote: [...] Fantastic question, answer & explanation, guys. Well done. From torriem at gmail.com Sun Aug 2 21:36:08 2009 From: torriem at gmail.com (Michael Torrie) Date: Sun, 02 Aug 2009 19:36:08 -0600 Subject: Queryable Daemon In-Reply-To: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> References: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> Message-ID: <4A763F08.3000504@gmail.com> Justin DeCell wrote: > I was hoping for a little help with a project I'm working on. I'm > writing a daemon in python that I want to be queryable (i.e. I should > be able to run foo -s and it will report some internal information > about the foo daemon if it's running) but I can't figure out a way get > information from that process from an external process. I was thinking > that there should be a way to open a file descriptor, have the daemon > write to that every so often and then have the query process just read > from that fd but it looks like on the process reading from an fd has > to be a child of the daemon for this to work. The only other way I > thought of would be to write to a file on disk every so often from the > daemon and just read the from the query process but it seems like > there should be a more elegant way to do this... Most daemon programs I know of that do this use unix sockets. The socket is typically put in /tmp, or probably better in /var/run, or some other appropriate place. Often this is configurable in a config file that both the daemon and the program or instance that checks the daemon read. Another possibility is shared memory segments. I'm not sure how security is done in this case. Anyway, shared memory is a common IPC mechanism. From steve at nospam.au Sun Aug 2 22:27:22 2009 From: steve at nospam.au (steve) Date: Mon, 3 Aug 2009 12:27:22 +1000 Subject: Test for Pythonwin? References: <4a728aac$0$9744$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <4a764b0a$0$22840$5a62ac22@per-qv1-newsreader-01.iinet.net.au> "steve" wrote in message news:4a728aac$0$9744$5a62ac22 at per-qv1-newsreader-01.iinet.net.au... > Is there a good way to check if a script is running inside Pythonwin? > Perhaps a property or method that is exposed by that environment? > > or, alternatively, is there a better place to ask :-) > > Steven > > 'pywin' in sys.modules Didn't want to check for redirection because my redirection code is in a different thread, and I'd have to think about thread synchronization as well. Thanks guys, Steven From icebergwtf at gmail.com Sun Aug 2 22:33:53 2009 From: icebergwtf at gmail.com (tiefeng wu) Date: Mon, 3 Aug 2009 10:33:53 +0800 Subject: RE Question In-Reply-To: <4dc0cfea0908021422x43972682ra58c53a2a43351ee@mail.gmail.com> References: <4dc0cfea0908021422x43972682ra58c53a2a43351ee@mail.gmail.com> Message-ID: <4314c1f70908021933o68857e6fia8a99f039ea9f1d9@mail.gmail.com> 2009/8/3 Victor Subervi : -> Hi; -> How do I search and replace something like this: > aLine = re.sub('[<]?[p]?[>]? a-zA-Z0-9"\'=:]*>[<]?[b]?[>]?', '', aLine) > where RE *only* looks for the possibility of "

" at the beginning of the > string; that is, not the individual components as I have it coded above, but > the entire 3-character block? > TIA, > Victor I'm not sure I totally understand your problem, try this: aLine = re.sub(r'(?:

)?]*>(?:)'.format(str(x)), '', aLine) tiefeng wu 2009-08-03 From aahz at pythoncraft.com Sun Aug 2 22:52:14 2009 From: aahz at pythoncraft.com (Aahz) Date: 2 Aug 2009 19:52:14 -0700 Subject: Printing with colors in a portable way References: <33e19169-19b4-497a-b262-2bcf7b5637d5@r38g2000yqn.googlegroups.com> Message-ID: In article <33e19169-19b4-497a-b262-2bcf7b5637d5 at r38g2000yqn.googlegroups.com>, Robert Dailey wrote: > >Anyone know of a way to print text in Python 3.1 with colors in a >portable way? In other words, I should be able to do something like >this: > >print_color( "This is my text", COLOR_BLUE ) > >And this should be portable (i.e. it should work on Linux, Mac, >Windows). Much as I hate to say, use a cross-platform GUI -- Tkinter comes with Python, and you can also use SDL via PyGame, wxWindows, pyQT, PyOpenGL, and so on. If that's not an option, you should have said "command-line program". ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From joshua at azariah.com Sun Aug 2 23:18:43 2009 From: joshua at azariah.com (Joshua J. Kugler) Date: Sun, 2 Aug 2009 19:18:43 -0800 Subject: ANNOUNCE: AwstatsReader 0.01 Message-ID: <200908021918.44365.joshua@azariah.com> ABOUT THE MODULE ================ AwstatsReader is an attempt at a pythonic interface to AWStats data cache files. ?Using it, you can access year, month, and individual data points via dictionary-like accessors. Download here: http://azariah.com/open_source.html ABOUT THE AUTHOR ================ Joshua Kugler (joshua at azariah.com) is a programmer and system administrator with over 10 years of industry experience. ?He is currently looking for a job. ?Happen to have one you could offer him? :) Resume at: http://jjncj.com/papers/KuglerAll.pdf DISCLAIMER ========== This is a "release early, release often" release, codnamed Joshua-hopes- somebody-downloads-this-and-likes-code-quality-and-hires-him. This is an early release...probably pre-alpha. ?There are no tests yet (haven't generated cache files I can release publically), not much documentation, and the interface may change (but I hope not too much). And I haven't even put this in a public repository, as the name might (but probably won't) change. I wrote this via examples from an AWStats cache file, so I'm sure there are sections for which I do not have definitions. ?If you would send me those sections, I'll be sure to add them. The error handling is probably a little light. ?Certainly could be improved. Right now, this will parse and display cache files from AWStats 6.5. I've not tested other versions yet, as 6.5 is the only version I've had access to so far. INSTALLATION ============ See INSTALL LICENSE ======= See COPYING EXAMPLE ======= import AwstatsReader obj ?= AwstatsReader.AwstatsReader('/path/to/awstats_logs', 'example.com') print obj[2007] print obj[2008][6] m = obj[2009][7] print m['general'] # Access like a dictionary... print m['general']['LastLine'] #...or like an object attribute print m['general'].LastLine print m.general.LastLine FEEDBACK ======== Please send questions/comments/suggestions to awstatsreader at azariah.com For now, you can find the latest version here: http://azariah.com/open_source.html From gagsl-py2 at yahoo.com.ar Mon Aug 3 00:13:17 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Aug 2009 01:13:17 -0300 Subject: RE Question References: <4dc0cfea0908021422x43972682ra58c53a2a43351ee@mail.gmail.com> Message-ID: En Sun, 02 Aug 2009 18:22:20 -0300, Victor Subervi escribi?: > How do I search and replace something like this: > aLine = re.sub('[<]?[p]?[>]? a-zA-Z0-9"\'=:]*>[<]?[b]?[>]?', '', aLine) > where RE *only* looks for the possibility of "

" at the beginning of > the > string; that is, not the individual components as I have it coded above, > but > the entire 3-character block? An example would make it more clear; I think you want to match either "

" is optional. Use a normal group or a non-capturing group: r'(

)? Message-ID: <19e16923-b200-498b-9ab2-f7d316b568a6@d32g2000yqh.googlegroups.com> On Aug 2, 9:52?pm, a... at pythoncraft.com (Aahz) wrote: [snip] > Much as I hate to say, use a cross-platform GUI -- Tkinter comes with > Python, [snip] Why is Tkinter such a whipping boy of the Python community? I know it's very simple and does not have all the bells and whistles of wx, but i think the gentle learning curve is very important for those struggling to learn GUI's. Even today I always use Tkinter first, and then only reach for wx when absolutely necessary. Seems to me the relativity small footprint(GUI wise) compared to the payoffs are worth the inclusion. I think if Tkinter where ever removed from Python it would be not only a disservice to the language but also a detriment to the *new* users of the language. Just my humble opinion From anthra.norell at bluewin.ch Mon Aug 3 03:40:00 2009 From: anthra.norell at bluewin.ch (Anthra Norell) Date: Mon, 03 Aug 2009 09:40:00 +0200 Subject: Compiling regex inside function? Message-ID: <4A769450.5080702@bluewin.ch> Hi all, I have a regex that has no use outside of a particular function. From an encapsulation point of view it should be scoped as restrictively as possible. Defining it inside the function certainly works, but if re.compile () is run every time the function is called, it isn't such a good idea after all. E.g. def entries (l): r = re.compile ('([0-9]+) entr(y|ies)') match = r.search (l) if match: return match.group (1) So the question is: does "r" get regex-compiled once at py-compile time or repeatedly at entries() run time? Frederic From greg.ewing at canterbury.ac.nz Mon Aug 3 03:40:41 2009 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Mon, 03 Aug 2009 19:40:41 +1200 Subject: Registation is open for the 9th PyWeek game programming challenge! In-Reply-To: <3A356906-89BE-47A4-9ECE-4C87A7EA89BE@gmail.com> References: <3A356906-89BE-47A4-9ECE-4C87A7EA89BE@gmail.com> Message-ID: <4A769479.9080707@canterbury.ac.nz> Richard Jones wrote: > The ninth PyWeek challenge will run between: > > Sunday 30th August to Sunday 6th September (00:00UTC to 00:00UTC) Yow, hard on the heels of Pyggy! I'd hoped there might be a bit more breathing room, sorry about that! Hope the Pyggy entrants aren't feeling too burned out to participate. -- Greg From deets at nospam.web.de Mon Aug 3 03:45:32 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Aug 2009 09:45:32 +0200 Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: <7dnissF2bthr0U1@mid.uni-berlin.de> Marcus Wanner schrieb: > On 8/2/2009 10:43 AM, Christian Heimes wrote: >> Marcus Wanner wrote: >>> I believe that python is buffer overflow proof. In fact, I think that >>> even ctypes is overflow proof... >> >> No, ctypes isn't buffer overflow proof. ctypes can break and crash a >> Python interpreter easily. >> >> Christian >> > I see. I thought that it said "invalid array index" when you try to > read/write outside of an array's bounds, though... But you can cast the resulting pointer to an array of larger size, and there you are. Diez From davea at ieee.org Mon Aug 3 04:04:04 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Aug 2009 04:04:04 -0400 Subject: Run pyc file without specifying python path ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF67D49D318@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6701A26C4@enbmail01.lsi.com> <4A708F68.1010505@ieee.org> <7F0503CD69378F49BE0DC30661C6CCF6701A26C7@enbmail01.lsi.com> <4A7199FF.8010202@dejaviewphoto.com> <7F0503CD69378F49BE0DC30661C6CCF6701A26D2@enbmail01.lsi.com> <4A71D35F.3090800@dejaviewphoto.com> <7F0503CD69378F49BE0DC30661C6CCF67D49D30E@enbmail01.lsi.com> <4A755DE6.1000906@ieee.org> <7F0503CD69378F49BE0DC30661C6CCF67D49D318@enbmail01.lsi.com> Message-ID: <4A7699F4.1050400@ieee.org> Barak, Ron wrote: > >> -----Original Message----- >> From: Dave Angel [mailto:davea at ieee.org] >> Sent: Sunday, August 02, 2009 12:36 >> To: Barak, Ron >> Cc: 'python-list at python.org' >> Subject: Re: Run pyc file without specifying python path ? >> >> Barak, Ron wrote: >> >>> Hi Dave, >>> >>> It seems like I don't understand your solution. >>> I use the (attached) soapAPI.py as the wrapper to parsing.pyc. >>> However, if I do (for instance): >>> >>> $ python -u parsing.pyc -U aaa >>> >>> The last line of the output is (as expected): >>> >>> return_code: 12 ; params: {'username': 'aaa'} >>> >>> But, if I try the following: >>> >>> $ soapAPI.py -U aaa >>> >>> I don't get this line. Only the output to stderr gets >>> >> printed to the screen. >> >>> Bye, >>> Ron. >>> >>> >>> >> Hi Ron, >> >> To make it easier for anybody following this thread, let me >> post the minimum equivalent source files, inline. >> >> parsing.py: >> ------------------------------ >> #!/usr/bin/env python >> >> import sys >> >> def main(): >> print >> sys.stderr, "This is stderr output" >> return 5, sys.argv >> >> if __name__ == "__main__": >> return_code, params = main() >> print "return_code:",return_code,"; params:",params >> sys.exit(return_code) >> ------------------------------- >> soapapi.py: >> ------------------------------- >> #!/usr/bin/env python >> >> import sys >> import parsing >> >> parsing.main() >> ------------------------------ >> >> >> When I run soapapi.;py, it indeed prints only the stderr output. >> >> The solution is to move (most or all) of the top-level code >> of parsing.py into a main() function. Since you already have >> a main(), I'll rename that, and make a new one that calls it. >> >> new parsing.py: >> ------------------------------- >> #!/usr/bin/env python >> >> import sys >> >> def innermain(): >> print >> sys.stderr, "This is stderr output" >> return 5, sys.argv >> >> def main(): >> return_code, params = innermain() >> print "return_code:",return_code,"; params:",params >> sys.exit(return_code) >> >> if __name__ == "__main__": >> main() >> ------------------------------- >> >> The output is now two lines, one from innermain(), and one >> from main(). >> And it's the same whether the user runs parsing.py or soapAPI.py >> >> To clarify what happened, realize that when the user invokes >> parsing.py, the module is considered a script, and gets a >> pseudo-name of >> "__main__" When that same module is imported by another one, it is >> considered a library module, and gets its own name "parsing" >> >> So any logic that explicitly checks for "__main__" has to >> change, because we want identical behavior in the two cases. >> >> DaveA >> >> >> > > Hi Dave, > > Trying your above scripts, I get other results than you do. E.g.: > > $ python parsing.py --help > return_code: 5 ; params: ['parsing.py', '--help'] > This is stderr output > > $ python soapapi.py --help > This is stderr output > > $ > > So, in my environment (cygwin on win xp, python Python 2.5.2) I'm getting different results than you get, namely - soapapi.py on my environment does not show the stdout output. > On which environment did you get identical results from your parsing.py and soapapi.py ? > > Bye, > Ron. > > $ cat parsing.py > #!/usr/bin/env python > > import sys > > def main(): > print >> sys.stderr, "This is stderr output" > return 5, sys.argv > > if __name__ == "__main__": > return_code, params = main() > print "return_code:",return_code,"; params:",params > sys.exit(return_code) > > $ cat soapapi.py > #!/usr/bin/env python > > import sys > import parsing > > parsing.main() > > > > Please read my message again, especially starting with the words "the solution is." I showed two versions of parsing.py, and you're still using the broken version. I posted both versions, with descriptions of what I changed and why, so that you could see why the change was important. I'm using sys.version == 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] Running on XP Sp3. And 2.5 will give identical results, though I don't have it installed any more. DaveA From matt.urry at googlemail.com Mon Aug 3 04:36:41 2009 From: matt.urry at googlemail.com (ma3mju) Date: Mon, 3 Aug 2009 01:36:41 -0700 (PDT) Subject: Processes not exiting References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> <61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com> <01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> Message-ID: <996e50f5-c126-4ac2-ae8d-458d22a26ee1@v20g2000yqm.googlegroups.com> On 2 Aug, 21:49, Piet van Oostrum wrote: > >>>>> MRAB (M) wrote: > >M> I wonder whether one of the workers is raising an exception, perhaps due > >M> to lack of memory, when there are large number of jobs to process. > > But that wouldn't prevent the join. And you would probably get an > exception traceback printed. > > I wonder if something fishy is happening in the multiprocessing > infrastructure. Or maybe the Fortran code goes wrong because it has no > protection against buffer overruns and similar problems, I think. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org I don't think it's a memory problem, the reason for the hard and easy queue is because for larger examples it uses far more RAM. If I run all of workers with harder problems I do begin to run out of RAM and end up spending all my time switching in and out of swap so I limit the number of harder problems I run at the same time. I've watched it run to the end (a very boring couple of hours) and it stays out of my swap space and everything appears to be staying in RAM. Just hangs after all "poison" has been printed for each process. The other thing is that I get the message "here" telling me I broke out of the loop after seeing the poison pill in the process and I get all the things queued listed as output surely if I were to run out of memory I wouldn't expect all of the jobs to be listed as output. I have a serial script that works fine so I know individually for each example the fortran code works. Thanks Matt From MatzeGuentert at gmx.de Mon Aug 3 04:46:29 2009 From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=) Date: Mon, 03 Aug 2009 08:46:29 +0000 Subject: M2Crypto: X509.X509_Extension_Stack() throws AssertionError Message-ID: <1249289189.3205.5.camel@celsius> Hello python-list members Why is the following code snippet throwing an AssertionError? Is that behavior a bug within X509.X509_Extension_Stack()? How would you suggest popping every element from the stack? Regards, Matthias G?ntert ------------------------------------------------- from M2Crypto import X509 if __name__ == '__main__': cert_extension_stack = X509.X509_Extension_Stack() cert_extension_1 = X509.new_extension("basicConstraints", "CA:FALSE") cert_extension_1.set_critical() cert_extension_2 = X509.new_extension("keyUsage", "101000000") cert_extension_2.set_critical() cert_extension_3 = X509.new_extension("subjectAlternativeName", "DNS:www.mydomain.tld") print cert_extension_stack.push(cert_extension_1) print cert_extension_stack.push(cert_extension_2) print cert_extension_stack.push(cert_extension_3) print cert_extension_stack.pop() ------------------------------------------------- ------------------------------------------------- Traceback (most recent call last): File "test.py", line 18, in print cert_extension_stack.pop() File "/usr/lib64/python2.6/site-packages/M2Crypto/X509.py", line 159, in pop assert len(self.pystack) == 0 AssertionError 1 2 3 ------------------------------------------------- From zdenekmaxa at yahoo.co.uk Mon Aug 3 05:19:11 2009 From: zdenekmaxa at yahoo.co.uk (Zdenek Maxa) Date: Mon, 03 Aug 2009 11:19:11 +0200 Subject: urllib2.urlopen timeout Message-ID: <4A76AB8F.5090403@yahoo.co.uk> Hi, I would like to ask how I should set timeout for a call: f = urllib2.urlopen(url) I am using Python 2.5. I have already tried socket.setdefaulttimeout(3). However, this adversely affects other connections the application makes, since it seems to affect all socket connections. I know that Python 2.6 offers urllib2.urlopen(url[, data][, timeout]) which would elegantly solved my problem, but I have to stick to Python 2.5. I am doing urlopen in a thread so I want to avoid really long hanging on this call, which happens at times, until some default timeout ticks out. All hints appreciated. Thanks, Zdenek From jeanmichel at sequans.com Mon Aug 3 06:46:45 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 03 Aug 2009 12:46:45 +0200 Subject: Printing with colors in a portable way In-Reply-To: References: <33e19169-19b4-497a-b262-2bcf7b5637d5@r38g2000yqn.googlegroups.com> Message-ID: <4A76C015.5010600@sequans.com> Nobody wrote: > On Thu, 30 Jul 2009 15:40:37 -0700, Robert Dailey wrote: > > >> Anyone know of a way to print text in Python 3.1 with colors in a >> portable way? In other words, I should be able to do something like >> this: >> >> print_color( "This is my text", COLOR_BLUE ) >> >> And this should be portable (i.e. it should work on Linux, Mac, >> Windows). >> > > The way that terminals (and emulators) handle colour is fundamentally > different from the DOS/Windows console. If you want something which will > work on both, you will have write separate implementations for terminals > and the DOS/Windows console. > > For terminals, you can use the "curses" package, e.g.: > > import curses > > curses.setupterm() > setaf = curses.tigetstr('setaf') > setab = curses.tigetstr('setab') > > def foreground(num): > if setaf: > sys.stdout.write(curses.tparm(setaf, num)) > > def background(num): > if setab: > sys.stdout.write(curses.tparm(setab, num)) > > For the Windows console, you'll need to use ctypes to interface to the > SetConsoleTextAttribute() function from Kernel32.dll. > > FYI http://github.com/jbowes/markymark/blob/59511b36a752b40243cc18fb0fb9800c74549ac1/markymark.py If the URL ever becomes invalid, then google for markymark.py You can use it either to color your Linux/Unix terms, or you can just look at the python code to see how to set colors and attributes. JM From hitechpundir at gmail.com Mon Aug 3 07:12:15 2009 From: hitechpundir at gmail.com (sirjee) Date: Mon, 3 Aug 2009 04:12:15 -0700 (PDT) Subject: problem in event handling on change of variable value. References: <9c0d7a31-0310-4499-9974-92afc588f315@d15g2000prc.googlegroups.com> Message-ID: <27a8e24c-7f58-4952-b45a-439601223199@13g2000prl.googlegroups.com> On Aug 1, 2:22?pm, sirjee wrote: > hello; > > i m facing a problem in handling events on change of value of > environment variable in a toolCANoe. > > class CANoeEvents: > ? ? def OnChange(self,value): > ? ? ? ? print "value of environment variable has changed" > ? ? def OnOpen(self,App): > ? ? ? ? print "opening Application" > > App_Event = DispatchWithEvents('CANoe.Application',CANoeEvents) > time.sleep(2) > App_Event.Open("C:\projectConfig.cfg") ?# printd "opening Application" > and event handled properly. > .......(now a code file runs in thecanoein which value of > environment variable called dummy is changed during execution. Just > like OnOpen; OnChange is defined in specification which should be > called on change of environment variable.But it is not happening.) > while (): > ? ? ? ? ? ? ? ? myenvVar = App_Event.Environment.GetVariable("dummy") > > The VB does it very easily and defines a subroutine called : > Sub myenvVar _OnChange(value) > ? ?print "value of environment variable has changed" > End Sub > //////////////////////////////////////////////////however the > alternative for subroutine for OnOpen in VB (defined below) works fine > as shown above in python. > Sub AppEvent_OnOpen(App) > ? ? ? ? print "opening Application" > End Sub > > for VB; all this stuff is cake work.... object_eventname subroutine > and done.....what in python? hi all; strange !!!! i got answer to the problem posted by me only. now I have very good control of CANoe tool from python.... if anybody faces any problem wrt automation of CANoe tool using python; do contact me. here actual problem lied in analysing and implementing com heirarchy. ( which is really bit cumbersome) onChange event is associated with App_Event.Environment.GetVariable ("dummy") object. So we need to associate separate class with this object and then write onChange function: class evtClass: def __init__(self): print "initializing event class" def OnChange(self,value): print "value of environment variable changing" print "changed value of environment variable is" print value see = App_Event.Environment.GetVariable("dummy") see_temp=DispatchWithEvents(see,evtClass) this will solve problem. So we need to create separate classes for events associated with separate objects. regards sirjee From marcusw at cox.net Mon Aug 3 08:01:00 2009 From: marcusw at cox.net (Marcus Wanner) Date: Mon, 03 Aug 2009 08:01:00 -0400 Subject: Is python buffer overflow proof? In-Reply-To: <7dnissF2bthr0U1@mid.uni-berlin.de> References: <7dnissF2bthr0U1@mid.uni-berlin.de> Message-ID: On 8/3/2009 3:45 AM, Diez B. Roggisch wrote: > Marcus Wanner schrieb: >> On 8/2/2009 10:43 AM, Christian Heimes wrote: >>> Marcus Wanner wrote: >>>> I believe that python is buffer overflow proof. In fact, I think >>>> that even ctypes is overflow proof... >>> >>> No, ctypes isn't buffer overflow proof. ctypes can break and crash a >>> Python interpreter easily. >>> >>> Christian >>> >> I see. I thought that it said "invalid array index" when you try to >> read/write outside of an array's bounds, though... > > > But you can cast the resulting pointer to an array of larger size, and > there you are. > > Diez Ah, that makes sense. I had forgotten about ctypes.cast(). Marcus From riaz.ahmadskh at gmail.com Mon Aug 3 08:03:46 2009 From: riaz.ahmadskh at gmail.com (Riaz Ahmad) Date: Mon, 3 Aug 2009 05:03:46 -0700 (PDT) Subject: "PAKISTAN NEWS" "PAKISTANI NEWSPAPERS" "MAGAZINES ON LINE" "URDU LANGUAGE SOFTWARES" "URDU POETRY PAKISTAN" "PAKISTANI WEB SITE DIRECTOR" "PAKISTANI NEWSPAPERS" "PAKISTAN" "PAKISTAN" on www.pak-web-pages.blogspot.com Message-ID: "PAKISTAN NEWS" www.pak-web-pages.blogspot.com "PAKISTANI NEWSPAPERS" www.pak-web-pages.blogspot.com "MAGAZINES ON LINE" www.pak-web-pages.blogspot.com "URDU LANGUAGE SOFTWARES" www.pak-web-pages.blogspot.com "URDU POETRY PAKISTAN" www.pak-web-pages.blogspot.com "PAKISTANI WEB SITE DIRECTOR" www.pak-web-pages.blogspot.com "PAKISTANI NEWSPAPERS" www.pak-web-pages.blogspot.com "PAKISTAN" www.pak-web-pages.blogspot.com "PAKISTAN" www.pak-web-pages.blogspot.com on www.pak-web-pages.blogspot.com From hubaghdadi at gmail.com Mon Aug 3 08:14:35 2009 From: hubaghdadi at gmail.com (Hussein B) Date: Mon, 3 Aug 2009 05:14:35 -0700 (PDT) Subject: Executing remote command with paramiko Message-ID: Hey, I'm trying to run a sudo guarded command over SSH using paramiko +++++++++++++++++++ s = paramiko.SSHClient() s.load_system_host_keys() s.connect(hostname, port, username, passwd) stdin, stdout, stderr = s.exec_command('sudo -s') stdin.write('password\n') stdin.flush() print 'Flushing' stdin, stdout, stderr = s.exec_command('harvester') print stdout.read() s.close() +++++++++++++++++++ It seems to me that the sudo -s isn't getting executed at all. I commented the sudo -s code lines and no error is shown. Thanks for help and time. From duncan.booth at invalid.invalid Mon Aug 3 08:34:28 2009 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Aug 2009 12:34:28 GMT Subject: heapq "key" arguments References: <97932d10-8601-401f-bb69-a98db9036929@p15g2000vbl.googlegroups.com> <1582f82e-34aa-4b66-b989-c9f8351a5f1c@o9g2000prg.googlegroups.com> <4f096546-36a1-4633-9a24-1265ce0929ce@q14g2000vbi.googlegroups.com> Message-ID: "Gabriel Genellina" wrote: > Ok, it's not strictly the same, but usually it doesn't hurt. The heaqp > module doesn't promise anything about equal elements: it may keep the > original order, rearrange them at will, reverse them, whatever. The documentation doesn't say anything directly about stability, but the implementation is actually stable. You can probably assume it must be at least for nlargest and nsmallest otherwise the stated equivalence wouldn't hold: e.g. nsmallest documentation says: Equivalent to: sorted(iterable, key=key)[:n] -- Duncan Booth http://kupuguy.blogspot.com From sjmachin at lexicon.net Mon Aug 3 09:00:33 2009 From: sjmachin at lexicon.net (John Machin) Date: Mon, 3 Aug 2009 06:00:33 -0700 (PDT) Subject: New implementation of re module References: Message-ID: On Jul 28, 2:34?am, MRAB wrote: > Hi all, > > I've been working on a new implementation of the re module. The details > are athttp://bugs.python.org/issue2636, specifically fromhttp://bugs.python.org/issue2636#msg90954. I've included a .pyd file for > Python 2.6 on Windows if you want to try it out. > Where/how should we report perceived bugs: On that bugs.python.org issue? Here? Private e-mail? From ram.rachum at gmail.com Mon Aug 3 09:18:29 2009 From: ram.rachum at gmail.com (cool-RR) Date: Mon, 3 Aug 2009 06:18:29 -0700 (PDT) Subject: Announcing PythonTurtle Message-ID: Hello, I wanted to announce that I have just released my little side project, PythonTurtle. Here is its website: http://pythonturtle.com Its goal is to be the lowest-threshold way to learn (or teach) Python. You can read more about it and download it on the website. Ram. From mydevforums at gmail.com Mon Aug 3 10:04:07 2009 From: mydevforums at gmail.com (IronyOfLife) Date: Mon, 3 Aug 2009 07:04:07 -0700 (PDT) Subject: Python configuration question when python scripts are executed using Appweb as web server. Message-ID: Hi All I have installed python 2.6.2 in windows xp professional machine. I have set the following environment variables -- PYTHONPATH. It points to following windows folders: python root folder, the lib folder and lib-tk folder. I have configured IIS to execute python scripts. I do not have any issues executing python scripts from the python interpreter window or from the browser using IIS as the web server. However, when I use the open source Appweb web browser to execute python scripts. It is able to execute only simple script without issues. For example, hello.py executes fine. hello.py -------------------------------------------------------- #!/usr/bin/env python print "Content-type: text/html\n\n" print "Hello world!" However I am not able to execute python scripts that contain import statements. I need to point out here that i do not have issue with using os or sys packages. When I tried to execute the sample client script that came with the gnutls wrapper for python, I got error. I narrowed it down to the "from ... import" line in the example. from gnutls.crypto import * from gnutls.connection import * Next I modified it to the functions used in the client python scripts (NOTE: I have added some additional functions to connection and crypto python scripts). from gnutls.crypto import X509Certificate, X509PrivateKey, X509CRL from gnutls.connection import AnonClientCred Next step, in order to debug, I used the module finder to see what is happening. To being with I used the module finder to find out the modules loaded for the simple script hello.py. hello2.py -------------------------------------------------------- #!/usr/bin/env python import modulefinder import pdb pdb.set_trace() finder = modulefinder.ModuleFinder() finder.run_script('hello.py') print "Content-type: text/html\n\n" print "" print sys.exc_info() print 'Loaded modules:' for name, mod in finder.modules.iteritems(): print '%s: ' % name, print ','.join(mod.globalnames.keys()[:3]) print '-'*50 print 'Modules not imported:' print '\n'.join(finder.badmodules.iterkeys()) print "" I got the error. Please see below for error as captured from Appweb logs. See lines 3 to 5. cgi:5 main 356: CGI Response: read 89 bytes cgi:6 main 356: Data is: > c:\appweb\web\hello2.py(9)() -> finder = modulefinder.ModuleFinder() (Pdb) cgi:5 main 356: CGI Response: read 0 bytes cmd:7 main getExitCode: process 0, code 1 default:1 main Error: 503 "Service Unavailable" for "/hello2.py", file "c:/appweb/web/hello2.py": CGI process /hello2.py: exited abnormally with exit code: 1 request:5 main 356: flushOutput: background 0 Once again, let me stress that this issue is happening only when I use appweb as the web server. Some details on Appweb that I found out: Appweb opens up a new console process and executes the python scripts. See sample below: cmd:5 pool.0 Running: C:\Dev\Ironic\Tools\Python26\python.exe c:/ appweb/web/hello2.py When python scripts are executed in this fashion, should there be additional command line arguments be passed? Am I missing any additional settings. Also can you help with improving the debugging lines in hello2.py so that I can identify the issue. Please help. Thanks. Ram G. From jeanmichel at sequans.com Mon Aug 3 10:38:43 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 03 Aug 2009 16:38:43 +0200 Subject: Generate a new object each time a name is imported In-Reply-To: <02853264$0$20667$c3e8da3@news.astraweb.com> References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: <4A76F673.9010701@sequans.com> Steven D'Aprano wrote: > I would like to generate a new object each time I import a name from a > module, rather than getting the same object each time. For example, > currently I might do something like this: > > # Module > count = 0 > def factory(): > # Generate a unique object each time this is called > global count > count += 1 > return "Object #%d" % count > > > # Calling module > from Module import factory > a = factory() # a == "Object #1" > b = factory() # b == "Object #2" > del factory > > > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a # a == "Object #1" > from Module import factory() as b # b == "Object #2" > > except of course that syntax is illegal. > > > Why making standard statements do what they're not meant to do ? You could write >import Module > >a = factory() >b = factory() But you already know that. So what's the purpose of making >from Module import factory as a >from Module import factory as b return 2 different objects ? If I had to write this code I would expect 'a is b' to return 'True'. This is no "don't do that" answer, it's a sincere question: what is the benefit of your /new/ syntax ? JM From andre.roberge at gmail.com Mon Aug 3 10:53:43 2009 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 3 Aug 2009 07:53:43 -0700 (PDT) Subject: Announcing PythonTurtle References: Message-ID: <44a7457e-4dc7-4ad4-be80-3585ce693bc9@f37g2000yqn.googlegroups.com> On Aug 3, 10:18?am, cool-RR wrote: > Hello, > > I wanted to announce that I have just released my little side project, > PythonTurtle. > Here is its website:http://pythonturtle.com > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > You can read more about it and download it on the website. > > Ram. Why not make the source available? At the very least, people that do not run windows could try it too. Andr? From jcd at sdf.lonestar.org Mon Aug 3 10:54:05 2009 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 03 Aug 2009 10:54:05 -0400 Subject: A Bug By Any Other Name ... In-Reply-To: References: Message-ID: <1249311245.8865.11.camel@aalcdl07> On Sun, 2009-08-02 at 14:14 +0000, Albert van der Horst wrote: > >This is actually quite thoroughly untrue. In python, *indentation* > is > >significant. Whitespace (internal to a line) is not. You can even > call > >methods like this if you want: > > You totally don't get it. You describe how python is now. > I propose a change to be made to python. Small wonder that that is > different from what it is now. > > > > >>>> s = 'abc' > >>>> s . upper() > >ABC > > You prove nothing by giving examples. > You can disprove by giving one counter example, > here it goes. > > Whitespace (internal to a line) is significant. > In Python you cannot change > xleftgoing = 123000000 > to > x left going = 123 000 000 > > (You can in Algol68) I had a feeling that counterexample would be coming sooner or later. However, it doesn't really address the change you're looking for. Internal whitespace *is* irrelevant, except insofar as it can be used to delimit different tokens in parsing. If tokens are separate, they are separate, and no more or less whitespace is going to make any difference. Again, I'm describing how python is now. Which is not to say it couldn't be changed, I just want to make sure you understand how deep into the heart of python you are trying to cut. You make it sound like a small change, but it is not. You are proposing changing the parsing rules, which completely changes the scope of what is possible and what isn't with python syntax. All to solve a problem that, so far, hasn't been proven to exist in anything other than a speculative way. You're trying to turn an ocean liner around because you left your sunscreen on the dock. Cheers, Cliff From newsgroup at silveraxe.de Mon Aug 3 10:56:17 2009 From: newsgroup at silveraxe.de (Hilmar Bunjes) Date: Mon, 03 Aug 2009 16:56:17 +0200 Subject: Announcing PythonTurtle In-Reply-To: <44a7457e-4dc7-4ad4-be80-3585ce693bc9@f37g2000yqn.googlegroups.com> References: <44a7457e-4dc7-4ad4-be80-3585ce693bc9@f37g2000yqn.googlegroups.com> Message-ID: <4a76fa98$0$31327$9b4e6d93@newsspool4.arcor-online.net> Andr? schrieb: >> I wanted to announce that I have just released my little side project, >> PythonTurtle. >> Here is its website:http://pythonturtle.com >> >> Its goal is to be the lowest-threshold way to learn (or teach) Python. >> You can read more about it and download it on the website. >> >> Ram. > > Why not make the source available? At the very least, people that do > not run windows could try it too. Isn't this the source: http://github.com/cool-RR/PythonTurtle/tree/master ? Linked at the bottom of the page. Best, Hilmar From sandhyaprabhakaran at gmail.com Mon Aug 3 11:17:53 2009 From: sandhyaprabhakaran at gmail.com (Sandhya Prabhakaran) Date: Mon, 3 Aug 2009 08:17:53 -0700 (PDT) Subject: Extract the numeric and alphabetic part from an alphanumeric string Message-ID: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Hi, I have a string as str='123ACTGAAC'. I need to extract the numeric part from the alphabetic part which I did using >>>numer=re.findall(r'\d+',str) >>>numer 123 To get the alphabetic part, I could do >>>alpha=str.replace('123','') >>>alpha ACTGAAC But when I give >>>alpha=str.replace(numer,'') Traceback (most recent call last): File "", line 1, in TypeError: expected a character buffer object How do I blank out the initial numeric part so as to get just the alphabetic part. The string is always in the same format. Please help. Regards, Sandhya From ram.rachum at gmail.com Mon Aug 3 11:22:50 2009 From: ram.rachum at gmail.com (cool-RR) Date: Mon, 3 Aug 2009 08:22:50 -0700 (PDT) Subject: Announcing PythonTurtle References: <44a7457e-4dc7-4ad4-be80-3585ce693bc9@f37g2000yqn.googlegroups.com> Message-ID: On Aug 3, 5:53?pm, Andr? wrote: > On Aug 3, 10:18?am, cool-RR wrote: > > > Hello, > > > I wanted to announce that I have just released my little side project, > > PythonTurtle. > > Here is its website:http://pythonturtle.com > > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > > You can read more about it and download it on the website. > > > Ram. > > Why not make the source available? ?At the very least, people that do > not run windows could try it too. > > Andr? Sorry that the link is obscure like that. I'll change it so it's easier to see. From peter at peter-b.co.uk Mon Aug 3 11:31:09 2009 From: peter at peter-b.co.uk (Peter Brett) Date: Mon, 03 Aug 2009 16:31:09 +0100 Subject: Extract the numeric and alphabetic part from an alphanumeric string References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Message-ID: Sandhya Prabhakaran writes: > Hi, > > I have a string as str='123ACTGAAC'. > > I need to extract the numeric part from the alphabetic part which I > did using >>>>numer=re.findall(r'\d+',str) >>>>numer > 123 > > To get the alphabetic part, I could do >>>>alpha=str.replace('123','') >>>>alpha > ACTGAAC > But when I give >>>>alpha=str.replace(numer,'') > Traceback (most recent call last): > File "", line 1, in > TypeError: expected a character buffer object > > How do I blank out the initial numeric part so as to get just the > alphabetic part. The string is always in the same format. Firstly, you really should read the Regular Expression HOWTO: http://docs.python.org/howto/regex.html#regex-howto Secondly, is this what you wanted to do? >>> p = re.compile(r'^\d+') >>> p.sub('', '123ACTGAAC') 'ACTGAAC' Regards, Peter -- Peter Brett Remote Sensing Research Group Surrey Space Centre From andreas.tawn at ubisoft.com Mon Aug 3 11:33:00 2009 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Mon, 3 Aug 2009 17:33:00 +0200 Subject: Extract the numeric and alphabetic part from an alphanumeric string In-Reply-To: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Message-ID: <8AEDA5E3386EA742B8C24C95FF0C758007C8ACF4@PDC-MAIL3.ubisoft.org> > Hi, > > I have a string as str='123ACTGAAC'. > > I need to extract the numeric part from the alphabetic part which I > did using > >>>numer=re.findall(r'\d+',str) > >>>numer > 123 > > To get the alphabetic part, I could do > >>>alpha=str.replace('123','') > >>>alpha > ACTGAAC > But when I give > >>>alpha=str.replace(numer,'') > Traceback (most recent call last): > File "", line 1, in > TypeError: expected a character buffer object > > How do I blank out the initial numeric part so as to get just the > alphabetic part. The string is always in the same format. > > Please help. > > Regards, > Sandhya If the format's always the same, you could use slicing instead. >>> s = '123ACTGAAC' >>> s[:3] '123' >>> s[3:] 'ACTGAAC' BTW, you should avoid using built-ins like str for variable names. Bad things will happen. Cheers, Drea From python at mrabarnett.plus.com Mon Aug 3 11:43:30 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 03 Aug 2009 16:43:30 +0100 Subject: Extract the numeric and alphabetic part from an alphanumeric string In-Reply-To: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Message-ID: <4A7705A2.2010301@mrabarnett.plus.com> Sandhya Prabhakaran wrote: > Hi, > > I have a string as str='123ACTGAAC'. > > I need to extract the numeric part from the alphabetic part which I > did using >>>> numer=re.findall(r'\d+',str) >>>> numer > 123 > [snip] I get: ['123'] which is a _list_ of the strings found. From kushal.kumaran+python at gmail.com Mon Aug 3 11:49:15 2009 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Mon, 3 Aug 2009 21:19:15 +0530 Subject: Extract the numeric and alphabetic part from an alphanumeric string In-Reply-To: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Message-ID: <1e364c4e0908030849u7583637h9c8d688f8520b904@mail.gmail.com> On Mon, Aug 3, 2009 at 8:47 PM, Sandhya Prabhakaran wrote: > Hi, > > I have a string as str='123ACTGAAC'. > > I need to extract the numeric part from the alphabetic part which I > did using >>>>numer=re.findall(r'\d+',str) >>>>numer > 123 > The docs for re.findall say that it returns a list of matches. So '123' will be numer[0]. > To get the alphabetic part, I could do >>>>alpha=str.replace('123','') >>>>alpha > ACTGAAC > But when I give >>>>alpha=str.replace(numer,'') > Traceback (most recent call last): > ?File "", line 1, in > TypeError: expected a character buffer object > That's what would happen if you pass in a list instead of a string to replace. > How do I blank out the initial numeric part so as to get just the > alphabetic part. The string is always in the same format. > > Please help. > -- kushal From python at mrabarnett.plus.com Mon Aug 3 12:00:05 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 03 Aug 2009 17:00:05 +0100 Subject: New implementation of re module In-Reply-To: References: Message-ID: <4A770985.5020900@mrabarnett.plus.com> John Machin wrote: > On Jul 28, 2:34 am, MRAB wrote: >> Hi all, >> >> I've been working on a new implementation of the re module. The details >> are athttp://bugs.python.org/issue2636, specifically fromhttp://bugs.python.org/issue2636#msg90954. I've included a .pyd file for >> Python 2.6 on Windows if you want to try it out. >> > > Where/how should we report perceived bugs: On that bugs.python.org > issue? Here? Private e-mail? > Probably on http://bugs.python.org/issue2636. From ethan at stoneleaf.us Mon Aug 3 12:00:43 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 03 Aug 2009 09:00:43 -0700 Subject: Python docs disappointing In-Reply-To: <7bb4df03-f09a-40b0-83f8-1c6d0c9800a8@j21g2000vbn.googlegroups.com> References: <7bb4df03-f09a-40b0-83f8-1c6d0c9800a8@j21g2000vbn.googlegroups.com> Message-ID: <4A7709AB.4060105@stoneleaf.us> Carl Banks wrote: > On Jul 31, 1:55 pm, Mark Lawrence wrote: > >>Apart from that what have the Pythonistas ever done for us? Nothing!:) > > > > Please don't feed the trolls. > > And if you do feed the trolls don't smile at them. > > > Carl Banks And if you do smile at them, don't show your teeth! ~Ethan~ From deets at nospam.web.de Mon Aug 3 12:01:14 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Aug 2009 18:01:14 +0200 Subject: Compiling regex inside function? References: Message-ID: <7dofubF2crctpU1@mid.uni-berlin.de> Anthra Norell wrote: > Hi all, > > I have a regex that has no use outside of a particular function. From > an encapsulation point of view it should be scoped as restrictively as > possible. Defining it inside the function certainly works, but if > re.compile () is run every time the function is called, it isn't such a > good idea after all. E.g. > > def entries (l): > r = re.compile ('([0-9]+) entr(y|ies)') > match = r.search (l) > if match: return match.group (1) > > So the question is: does "r" get regex-compiled once at py-compile time > or repeatedly at entries() run time? This can't be answered as simple yes/no-question. While the statement is executed each time, the resulting pattern-object isn't re-created, instead there is a caching-mechanism inside the module - so unless you create a situation where that cache's limits are exceeded and pattern objects are removed from it, you are essentially having the overhead of one function-call & a dict-lookup. Certainly worth it. As an additional note: r"" has *nothing* todo with this, that's just so-called raw string literals which have a different escaping-behavior - thus it's easier to write regexes in them. Diez From cjw at ncf.ca Mon Aug 3 12:04:50 2009 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 03 Aug 2009 12:04:50 -0400 Subject: Announcing PythonTurtle In-Reply-To: References: Message-ID: cool-RR wrote: > Hello, > > I wanted to announce that I have just released my little side project, > PythonTurtle. > Here is its website: > http://pythonturtle.com > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > You can read more about it and download it on the website. > > Ram. It looks neat but it's not yet ready for prime time. Colin W. From robert.kern at gmail.com Mon Aug 3 12:24:19 2009 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Aug 2009 11:24:19 -0500 Subject: iterate lines with regex In-Reply-To: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> Message-ID: On 2009-08-01 14:39, Michael Savarese wrote: > > I'm a python newbie and I'm trying to test several regular expressions > on the same line before moving on to next line. > it seems to move on to next line before trying all regular expressions > which is my goal. > it only returns true for first regular expression > does the curser have to be rest to beginning of line? If so, how would I > do that. > remember I'm new > thanks in advance to any advice > Mike S. > > the following is part of my code, > readThis=open('c:/9320.txt','r') > > for line in readThis: > try: > thisKey = key.search(line).group(1) > thisMap = map.search(line).group(1) > thisParcel = parcel.search(line).group(1) > except: > continue What is happening is that either key or map fails to match and trying to get a group raises an exception. This is caught, and the "continue" statement tells the for-loop to go to the next line in readThis. The "continue" statement does not mean "go back to where the error was raised and continue executing as if no error happened". The key to using try: except: properly is to surround as little code as possible. Also, to explicitly state which exceptions you are going to catch. In this case, though, you don't want to use exceptions. You should deal with the match objects that are the result of the .search() method. for line in readThis: key_match = key.search(line) if key_match is not None: this_key = key_match.group(1) # ... do something with this_key map_match = map.search(line) if map_match is not None: this_map = map_match.group(1) # ... do something with this_map parcel_match = parcel.search(line) if parcel_match is not None: this_parcel = parcel_match.group(1) # ... do something with this_parcel -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From wuwei23 at gmail.com Mon Aug 3 12:40:02 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Aug 2009 09:40:02 -0700 (PDT) Subject: Extract the numeric and alphabetic part from an alphanumeric string References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Message-ID: <3fc2ad25-8af7-452e-aab5-5716064d758f@y28g2000prd.googlegroups.com> Sandhya Prabhakaran wrote: > I have a string as str='123ACTGAAC'. You shouldn't use 'str' as a label like that, it prevents you from using the str() function in the same body of code. > How do I blank out the initial numeric part so as to get just the > alphabetic part. The string is always in the same format. >>> sample = '123ACTGAAC' >>> numer = ''.join(s for s in sample if s.isdigit()) >>> alpha = ''.join(s for s in sample if s.isalpha()) >>> numer, alpha ('123', 'ACTGAAC') If by 'always in the same format' you mean the positions of the numbers & alphas, you could slightly abuse the struct module: >>> import struct >>> sample = '123ACTGAAC' >>> format = '3s7s' # a string of 3 + a string of 7 >>> struct.unpack(format, sample) ('123', 'ACTGAAC') But seriously, you should use slicing: >>> sample = '123ACTGAAC' >>> sample[0:3], sample[3:] ('123', 'CTGAAC') You can also label the slices, which can be handy for self-documenting your code: >>> num = slice(3) >>> alp = slice(4,10) >>> sample[num], sample[alp] ('123', 'CTGAAC') From ram.rachum at gmail.com Mon Aug 3 12:47:43 2009 From: ram.rachum at gmail.com (cool-RR) Date: Mon, 3 Aug 2009 09:47:43 -0700 (PDT) Subject: Announcing PythonTurtle References: Message-ID: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> On Aug 3, 7:04?pm, "Colin J. Williams" wrote: > cool-RR wrote: > > Hello, > > > I wanted to announce that I have just released my little side project, > > PythonTurtle. > > Here is its website: > >http://pythonturtle.com > > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > > You can read more about it and download it on the website. > > > Ram. > > It looks neat but it's not yet ready for prime time. > > Colin W. I agree there's a lot that can be improved - I wanted to put it out there so I could get feedback and fix the important things first. So I'd appreciate you telling me what you think needs improvement. Ram. From sandhyaprabhakaran at gmail.com Mon Aug 3 12:52:48 2009 From: sandhyaprabhakaran at gmail.com (Sandhya Prabhakaran) Date: Mon, 3 Aug 2009 18:52:48 +0200 Subject: Extract the numeric and alphabetic part from an alphanumeric string In-Reply-To: <1e364c4e0908030849u7583637h9c8d688f8520b904@mail.gmail.com> References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> <1e364c4e0908030849u7583637h9c8d688f8520b904@mail.gmail.com> Message-ID: Oh yes indeed........! Now that works :D Thanks a lot !! 2009/8/3 Kushal Kumaran > > On Mon, Aug 3, 2009 at 8:47 PM, Sandhya > Prabhakaran wrote: > > Hi, > > > > I have a string as str='123ACTGAAC'. > > > > I need to extract the numeric part from the alphabetic part which I > > did using > >>>>numer=re.findall(r'\d+',str) > >>>>numer > > 123 > > > > The docs for re.findall say that it returns a list of matches. So > '123' will be numer[0]. > > > To get the alphabetic part, I could do > >>>>alpha=str.replace('123','') > >>>>alpha > > ACTGAAC > > But when I give > >>>>alpha=str.replace(numer,'') > > Traceback (most recent call last): > > File "", line 1, in > > TypeError: expected a character buffer object > > > > That's what would happen if you pass in a list instead of a string to > replace. > > > How do I blank out the initial numeric part so as to get just the > > alphabetic part. The string is always in the same format. > > > > Please help. > > > > -- > kushal > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rcn.com Mon Aug 3 12:55:06 2009 From: python at rcn.com (Raymond Hettinger) Date: Mon, 3 Aug 2009 09:55:06 -0700 (PDT) Subject: heapq "key" arguments References: <97932d10-8601-401f-bb69-a98db9036929@p15g2000vbl.googlegroups.com> <1582f82e-34aa-4b66-b989-c9f8351a5f1c@o9g2000prg.googlegroups.com> <4f096546-36a1-4633-9a24-1265ce0929ce@q14g2000vbi.googlegroups.com> Message-ID: <3d2f5ff5-201e-4451-b9e7-fb33652b44a7@d9g2000prh.googlegroups.com> [Duncan Booth] > The documentation doesn't say anything directly about stability, but the > implementation is actually stable. You can probably assume it must be at > least for nlargest and nsmallest otherwise the stated equivalence wouldn't > hold: > > e.g. nsmallest documentation says: > > ? ? ? ? Equivalent to: sorted(iterable, key=key)[:n] Yes. The code for nsmallest and nlargest preserves stability so that the equivalence is maintained. Raymond From wuwei23 at gmail.com Mon Aug 3 12:56:02 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Aug 2009 09:56:02 -0700 (PDT) Subject: Compiling regex inside function? References: Message-ID: Anthra Norell wrote: > def entries (l): > ? ? ? ? r = re.compile ('([0-9]+) entr(y|ies)') > ? ? ? ? match = r.search (l) > ? ? ? ? if match: return match.group (1) > > So the question is: does "r" get regex-compiled once at py-compile time > or repeatedly at entries() run time? The docs say: The compiled versions of the most recent patterns passed to re.match (), re.search() or re.compile() are cached, so programs that use only a few regular expressions at a time needn?t worry about compiling regular expressions. (But they don't say how few is 'only a few'...) If you're concerned about it, you could always set the compiled pattern to a default value in the function's argspec, as that _is_ only executed the once: def entries(line, regex = re.compile('([0-9]+) entr(y|ies)'): match = regex.search(line) ... From nagle at animats.com Mon Aug 3 12:57:08 2009 From: nagle at animats.com (John Nagle) Date: Mon, 03 Aug 2009 09:57:08 -0700 Subject: Help understanding the decisions *behind* python? In-Reply-To: References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> Message-ID: <4a7715ff$0$1641$742ec2ed@news.sonic.net> Dave Angel wrote: > sturlamolden wrote: >> On 20 Jul, 18:27, Phillip B Oldham wrote: >> Tuples are used for passing arguments to and from a function. Common >> use of tuples include multiple return values and optional arguments >> (*args). That's from Mesa, the Xerox PARC language of the 1970s. Mesa used tuples for subroutine arguments in a very straightforward way. Every function took one tuple as an argument, written as parameters in parentheses separated by commas. Every function returned a tuple as an argument. This had a nice symmetry; function outputs and function inputs had the same form. Mesa was the first language to break through the "single return value" syntax problem. Python doesn't go that far. John Nagle From wuwei23 at gmail.com Mon Aug 3 13:02:57 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Aug 2009 10:02:57 -0700 (PDT) Subject: Help understanding the decisions *behind* python? References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> <4a7715ff$0$1641$742ec2ed@news.sonic.net> Message-ID: <686a0fac-b746-488f-9514-a1849fbda94d@g1g2000pra.googlegroups.com> John Nagle wrote: > Every function returned a tuple as an argument. This had a nice > symmetry; function outputs and function inputs had the same form. ? > Mesa was the first language to break through the "single return > value" syntax problem. > > ? ? Python doesn't go that far. I assume here you're referring to the former point and not the latter? From nobody at nowhere.com Mon Aug 3 13:23:06 2009 From: nobody at nowhere.com (Nobody) Date: Mon, 03 Aug 2009 18:23:06 +0100 Subject: Queryable Daemon References: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> Message-ID: On Sun, 02 Aug 2009 19:36:08 -0600, Michael Torrie wrote: > Another possibility is shared memory segments. I'm not sure how > security is done in this case. Shared memory segments have an owner, group, and the standard ugo=rwx permissions (execute permission is present but ignored); see the shmget(2) and shmctl(2) manpages. But Unix-domain sockets are supported by the standard library, while shared memory would require a separate library, e.g.: http://semanchuk.com/philip/PythonIpc/ Also, there is unlikely to be an advantage to using shared memory in Python. In most cases, you would have to explicitly serialise Python objects into the shared memory region. It's more useful in C, where you can treat the region as a struct which is accessed directly from the program. From python at mrabarnett.plus.com Mon Aug 3 13:29:56 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 03 Aug 2009 18:29:56 +0100 Subject: iterate lines with regex In-Reply-To: References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> Message-ID: <4A771E94.70805@mrabarnett.plus.com> Robert Kern wrote: [snip] > > for line in readThis: > key_match = key.search(line) > if key_match is not None: > this_key = key_match.group(1) > # ... do something with this_key > map_match = map.search(line) > if map_match is not None: > this_map = map_match.group(1) > # ... do something with this_map > parcel_match = parcel.search(line) > if parcel_match is not None: > this_parcel = parcel_match.group(1) > # ... do something with this_parcel > re.search and re.match will return a MatchObject if successful or None if unsuccessful. A MatchObject is always true, so you can simplify to: ... if key_match: this_key = key_match.group(1) # ... do something with this_key ... From python at rcn.com Mon Aug 3 13:36:28 2009 From: python at rcn.com (Raymond Hettinger) Date: Mon, 3 Aug 2009 10:36:28 -0700 (PDT) Subject: heapq "key" arguments References: <97932d10-8601-401f-bb69-a98db9036929@p15g2000vbl.googlegroups.com> Message-ID: [Joshua Bronson]: > According tohttp://docs.python.org/library/heapq.html, Python 2.5 > added an optional "key" argument to heapq.nsmallest and > heapq.nlargest. I could never understand why they didn't also add a > "key" argument to the other relevant functions (heapify, heappush, > etc). The problem is that heapq acts on regular lists, so it does not have exclusive access to the structure. So, there is no reliable way for it to maintain a separate list of keys. Since the keys can't be saved in the structure (without possibly breaking other code), the fine grained heapq functions (like heappop and heappush) would need to call key functions every time they are invoked. This is at odds with the implicit guarantee of the key function that it will be called no more than once per key. The overall problem is one of granularity. A key function should be applied once in an initial pass, not on every call to a push/pop function. The everyday solution that most people use is to operate on a list of (key, record) tuples and let tuple comparison do the work for you. Another solution is to build a Heap class that does have exclusive access to the structure, but the API sugar often isn't worth the slightly weaker performance. One other thought. Heaps are a lazy evaluation structure, so their fined-grained mutation functions only work well with just a single ordering function, so there is not need to have (and every reason to avoid) changing key functions in mid-stream. IOW, the key function needs to be constant across all accesses. Contrast this with other uses of key functions where it makes perfect sense to run minage=min(data, key=attrgetter('age')) and then running minsal=min(data, key=attrgetter('salary')). The flexibility to change key functions just doesn't make sense in the context of the fine-grained heap functions. Accordingly, this is why I put key functions in nlargest() and nsmallest() but not in heappush() and friends. The former can guarantee no more than one key function call per entry and they evaluate immediately instead of lazily. Raymond From duncan.booth at invalid.invalid Mon Aug 3 13:47:05 2009 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Aug 2009 17:47:05 GMT Subject: Compiling regex inside function? References: Message-ID: alex23 wrote: > The docs say: > The compiled versions of the most recent patterns passed to re.match > (), re.search() or re.compile() are cached, so programs that use only > a few regular expressions at a time needn?t worry about compiling > regular expressions. > > (But they don't say how few is 'only a few'...) If you're interested then it isn't all that hard to open up re.py in an editor and see that the cache holds up to 100 items. Of course that's just an implementation detail so other versions might have a different size cache. Also implementation dependant, but it might be worth knowing that when you hit that limit the cache is simply cleared: there's no gradual clearing of the oldest or least used entries. From bcharrow at csail.mit.edu Mon Aug 3 14:26:38 2009 From: bcharrow at csail.mit.edu (Ben Charrow) Date: Mon, 03 Aug 2009 14:26:38 -0400 Subject: urllib2.urlopen timeout In-Reply-To: <4A76AB8F.5090403@yahoo.co.uk> References: <4A76AB8F.5090403@yahoo.co.uk> Message-ID: <4A772BDE.4020602@csail.mit.edu> Zdenek Maxa wrote: > Hi, > > I would like to ask how I should set timeout for a call: > > f = urllib2.urlopen(url) > > > I know that Python 2.6 offers > urllib2.urlopen(url[, data][, timeout]) > which would elegantly solved my problem, but I have to stick to Python 2.5. > There are three solutions that I know about: 1) Make your own little HTTP library and set timeouts for each of your sockets. 2) The same as the above, except use asynchronous sockets and the the select module. 3) If you're on a Unix style system, use the signal module (the example is helpful http://docs.python.org/library/signal.html#example) Here's some code: import urllib2 import signal class TimeoutException(Exception): """SIGALARM was sent to the process""" pass def raise_timeout(signum, frame): raise TimeoutException("Timeout!") signal.signal(signal.SIGALRM, raise_timeout) try: signal.alarm(5) # raise alarm in 5 seconds data = urllib2.urlopen("http://www.google.com").readlines() except TimeoutException, ex: data = None finally: signal.alarm(0) # disable alarm HTH, Ben From sakradevanamindra at gmail.com Mon Aug 3 14:39:24 2009 From: sakradevanamindra at gmail.com (Leo Brugud) Date: Mon, 3 Aug 2009 11:39:24 -0700 (PDT) Subject: Can python do something like the onclick events in javascript ? Message-ID: <68e15376-75b5-4ad7-afe4-e058e33a427a@p23g2000vbl.googlegroups.com> I'm trying to use python to build a simple web page that make use of the onclick behavior, instead of requiring users to click the 'submit' button. I realize in javascript there are onclick, onchange events. Is python capable of doing the same? Thanks in Advance From robert.kern at gmail.com Mon Aug 3 14:44:07 2009 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Aug 2009 13:44:07 -0500 Subject: iterate lines with regex In-Reply-To: <4A771E94.70805@mrabarnett.plus.com> References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> <4A771E94.70805@mrabarnett.plus.com> Message-ID: On 2009-08-03 12:29, MRAB wrote: > Robert Kern wrote: > [snip] >> >> for line in readThis: >> key_match = key.search(line) >> if key_match is not None: >> this_key = key_match.group(1) >> # ... do something with this_key >> map_match = map.search(line) >> if map_match is not None: >> this_map = map_match.group(1) >> # ... do something with this_map >> parcel_match = parcel.search(line) >> if parcel_match is not None: >> this_parcel = parcel_match.group(1) >> # ... do something with this_parcel >> > re.search and re.match will return a MatchObject if successful or None > if unsuccessful. A MatchObject is always true, so you can simplify to: > > ... > if key_match: > this_key = key_match.group(1) > # ... do something with this_key > ... True, but I prefer to maintain a consistent style for None-testing regardless of whether or not I am sure the not-None type will have a suitable __nonzero__ implementation. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From deets at nospam.web.de Mon Aug 3 14:45:14 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Aug 2009 20:45:14 +0200 Subject: Can python do something like the onclick events in javascript ? In-Reply-To: <68e15376-75b5-4ad7-afe4-e058e33a427a@p23g2000vbl.googlegroups.com> References: <68e15376-75b5-4ad7-afe4-e058e33a427a@p23g2000vbl.googlegroups.com> Message-ID: <7dophqF2crpcqU1@mid.uni-berlin.de> Leo Brugud schrieb: > I'm trying to use python to build a simple web page that make use of > the onclick behavior, instead of requiring users > to click the 'submit' button. If that's the only reason, don't use JS for that, it's annoying. > I realize in javascript there are onclick, onchange events. Is python > capable of doing the same? Somewhat, through a python-2-javascript-translation: http://pyjs.org/ Diez From benjamin.kaplan at case.edu Mon Aug 3 14:54:58 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 3 Aug 2009 14:54:58 -0400 Subject: Can python do something like the onclick events in javascript ? In-Reply-To: <68e15376-75b5-4ad7-afe4-e058e33a427a@p23g2000vbl.googlegroups.com> References: <68e15376-75b5-4ad7-afe4-e058e33a427a@p23g2000vbl.googlegroups.com> Message-ID: On Mon, Aug 3, 2009 at 2:39 PM, Leo Brugud wrote: > I'm trying to use python to build a simple web page that make use of > the onclick behavior, instead of requiring users > to click the 'submit' button. > > I realize in javascript there are onclick, onchange events. Is python > capable of doing the same? > It depends. Python is usually used as a server-side language while Javascript is client-side. The client's web browser requests a web page, your program processes that request and sends the client a web page. That web page can contain anything you want, including Javascript. Your python program never hears from that client again until the *client* initiates contact, be it through a submit button or a javascript event that submits an HTTP request. You'll have to add the onclick and onchange code to the resulting web page, using Javascript, because Python never handles sending the request, jsut receiving it. Of course, this isn't the case if you are using something like pyjs, which compiles Python code to Javascript, your code will be running as Javascript code and not Python code. > > Thanks in Advance > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From saimapk81 at gmail.com Mon Aug 3 15:01:51 2009 From: saimapk81 at gmail.com (saima81) Date: Mon, 3 Aug 2009 12:01:51 -0700 (PDT) Subject: "MAGZINES IN URDU" "PAKISTANI MAGZINES" PAKISTAN" "PAKISTAN" "PAKISTANI NEWSPAPERS" "tHE eXPRTESS" "JANG NEWS" "WAQT" "DAWN" ON www.pak-web-pages.blogspot.com Message-ID: <054ce11f-597a-4c6e-b130-68a3bee4ad1b@i18g2000pro.googlegroups.com> "MAGZINES IN URDU" "PAKISTANI MAGZINES" PAKISTAN" "PAKISTAN" "PAKISTANI NEWSPAPERS" "tHE eXPRTESS" "JANG NEWS" "WAQT" "DAWN" ON www.pak-web-pages.blogspot.com From sam at tregar.com Mon Aug 3 15:11:38 2009 From: sam at tregar.com (Sam Tregar) Date: Mon, 3 Aug 2009 15:11:38 -0400 Subject: Online payment module Message-ID: Hello all. I'm considering building a module to provide a cross-payment-gatewat API for making online payments. In the Perl world we have a module like this called Business::OnlinePayment ( http://search.cpan.org/~jasonk/Business-OnlinePayment-2.01/OnlinePayment.pm). Is there anything like this in Python? My searches so far haven't turned up anything. If I don't find one I'll probably build one, covering PayPal and Authorize.net to start. If anyone is interested in discussing the project and/or getting involved shoot me an email. Thanks, -sam -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Mon Aug 3 15:21:57 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 03 Aug 2009 12:21:57 -0700 Subject: .dbf tables and Null In-Reply-To: <2f4d5719-6ca8-4ef2-8734-420b3044b1dc@l35g2000pra.googlegroups.com> References: <2f4d5719-6ca8-4ef2-8734-420b3044b1dc@l35g2000pra.googlegroups.com> Message-ID: <4A7738D5.3010009@stoneleaf.us> John Machin wrote: > On Aug 1, 3:41 am, Ethan Furman wrote: > >>Mornin'! and a good one, too, I hope. >> >>Question for you... >> >>First part of the question: What is the general value in having Null >>capability for fields? > > > In general, in any database system, so that one can distinguish > between "the customer has no 'middle name'" ('') and "the customer's > 'middle name' is unknown" (NULL). > > >>Second part: Is there a tangible difference between Null, and the >>nothing of 0, '', False, etc, in python? > > > 0 is the zero thing, it is not nothing. False is not nothing. > > > >>Third part: If there is a tangible difference, do those of us who use >>python and these old, refuse-to-die, .dbf files actually have need of, >>or have tables including, Null values? >> >>P.S. part (for John Machin, if he sees this ;) >>Will the dbf package you are working on support Null values? > > > My philosophy when digging stuff out of arcane storages is to expose > what is found and leave any kludging/sanitising to the next layer. > > For example, None is returned for an N (Number) field that's all > spaces; it's up to the caller to decide whether to treat None as zero, > raise an exception, pop up a data-collection dialogue box, ... > > If you mean specifically the Visual Foxpro v3 _NullFlags hack, yes, it > already supports that, as well as the VFP9 abuse of that hack for > Varchar and Varbinary fields :-) Thank you. It's been an interesting journey learning Python. Probably the two most difficult concepts for me to really internalize have been "batteries included" (thank you for the pointer to struct!) (I finally 'found' and incorporated array into my dbf module), and "everything is an object, even functions!". The unittest module worked wonderfully in making sure everything still worked after switching over to array as well, and the 30+% speed-up is also nice! :) All in all, I *love* Python! ~Ethan~ From no.email at please.post Mon Aug 3 15:59:23 2009 From: no.email at please.post (kj) Date: Mon, 3 Aug 2009 19:59:23 +0000 (UTC) Subject: kw param question Message-ID: I want to write a decorator that, among other things, returns a function that has one additional keyword parameter, say foo=None. When I try def my_decorator(f): # blah, blah def wrapper(*p, foo=None, **kw): x = f(*p, **kw) if (foo): # blah, blah else # blah blah return wrapper ...i get a syntax error where it says "foo=None". I get similar errors with everything else I've tried. Is is possible to do this in Python? TIA! kynn From hjtoi-better-remove-before-reply at comcast.net Mon Aug 3 16:08:37 2009 From: hjtoi-better-remove-before-reply at comcast.net (Heikki Toivonen) Date: Mon, 03 Aug 2009 13:08:37 -0700 Subject: M2Crypto: X509.X509_Extension_Stack() throws AssertionError References: Message-ID: Matthias G?ntert wrote: > Why is the following code snippet throwing an AssertionError? Is that > behavior a bug within X509.X509_Extension_Stack()? How would you suggest > popping every element from the stack? > > cert_extension_2 = X509.new_extension("keyUsage", "101000000") Maybe your OpenSSL is too old. keyUsage needs to be defined in OpenSSL obj_dat.h file for this to work. > cert_extension_3 = X509.new_extension("subjectAlternativeName", > "DNS:www.mydomain.tld") And I believe you mispelled this, try subjectAltName. With the change in spelling for subjectAltName your test passes for me using OpenSSL 1.0.0beta3 and M2Crypto 0.20beta with the (still incomplete) patch to make M2Crypto work with OpenSSL 1.0: https://bugzilla.osafoundation.org/show_bug.cgi?id=12855 -- Heikki Toivonen - http://heikkitoivonen.net From marduk at letterboxes.org Mon Aug 3 16:27:34 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Mon, 03 Aug 2009 16:27:34 -0400 Subject: kw param question In-Reply-To: References: Message-ID: <1249331254.1179.7.camel@brotherus.corp.redhat.com> On Mon, 2009-08-03 at 19:59 +0000, kj wrote: > > I want to write a decorator that, among other things, returns a > function that has one additional keyword parameter, say foo=None. > > When I try > > def my_decorator(f): > # blah, blah > def wrapper(*p, foo=None, **kw): > x = f(*p, **kw) > if (foo): > # blah, blah > else > # blah blah > return wrapper > > ...i get a syntax error where it says "foo=None". I get similar > errors with everything else I've tried. > Not exactly sure what you're trying to do.. but, regular arguments must be used *before* positional and keyword arguments so the definition: def wrapper(*p, foo=None, **kw): is syntactically incorrect whereby the following is correct: def wrapper(foo=None, *p, **kw): But if what you are wanting is to actually add 'foo' to kw then I would do this: def my_decorator(f): # blah, blah def wrapper(*p, **kw): if 'foo' not in kw: kw['foo'] = None x = f(*p, **kw) if kw['foo']: # blah blah else: # blah blah return wrapper From rt8396 at gmail.com Mon Aug 3 16:35:51 2009 From: rt8396 at gmail.com (r) Date: Mon, 3 Aug 2009 13:35:51 -0700 (PDT) Subject: Announcing PythonTurtle References: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> Message-ID: Hello, I wanted to announce that I have just released my little side project, PythonTurtle. [snip] I think it looks great --haven't download the source yet-- but i really like the screenshot. This will be more "inviting" to the new, inexperianced users. I like the idea of packaging up the command prompt and the canvas into one very friendly interface. I especially like that you are using a "real" turtle. I can remember the first time i used turtle (in python stdlib) and i kept saying to myself... "Were the heck is this damn turtle?!?!" (>_<) :-) From bartsmeets86 at gmail.com Mon Aug 3 16:39:44 2009 From: bartsmeets86 at gmail.com (Bart Smeets) Date: Mon, 3 Aug 2009 22:39:44 +0200 Subject: easy_install: unresolved external symbol Message-ID: <2119ee90908031339o71e19624qa815241b446d739d@mail.gmail.com> Hello, I keep getting errors when trying to use easy_install to install bbfreeze or cxfreeze (same errors). This is the output: http://pastebin.com/m65ba474d The error message unresolved external symbol keeps popping up. I have no idea how to solve this. Can anyone give me a hint? Thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From wells at submute.net Mon Aug 3 16:47:23 2009 From: wells at submute.net (Wells Oliver) Date: Mon, 3 Aug 2009 15:47:23 -0500 Subject: Ordering of dict keys & values Message-ID: <3f1a902d0908031347g6e5dbbb7v832b0abc924a020@mail.gmail.com> I understand that the keys in a dictionary are ordered not randomly but something practically close to it, but if I create a SQL query like so: query = 'INSERT INTO Batting (%s) VALUES(%s)' % (','.join(stats.keys()), ','.join(stats.values())) Can I at least rely on the value being in the same index as its corresponding key? -- Wells Oliver wells at submute.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From dciphercomputing at gmail.com Mon Aug 3 16:55:13 2009 From: dciphercomputing at gmail.com (Simon) Date: Mon, 3 Aug 2009 13:55:13 -0700 (PDT) Subject: Newbie Question regarding __init__() References: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> Message-ID: <01bcf8b8-687c-4bf4-acbb-b059a480d382@f33g2000vbm.googlegroups.com> On Aug 2, 5:51?am, Dave Angel wrote: > Simon wrote: > > Okay I will fix my code and include "self" and see what happens. ?I > > know I tried that before and got another error which I suspect was > > another newbie error. > > > The idea behind the init_Pre is that I can put custom code here to > > customize the __init__ instead of creating a new subclass. ?This kind > > of hook pattern allows you to flatten your inheritance hierarchy. ?I > > can choose in the init_Pre method to execute code before the init_exec > > (which contains the default __init__ code) and still execute the > > init_Exec method or I can completely customize the entire __init__ by > > returning False from init_Pre and prevent the init_Exec from being > > called. ?I use this type of pattern with almost all my methods. ?In > > this way I can create a less complicated inheritance chain but still > > have have custom code when needed without sub-classing. > > > I am use to Visual FoxPro which where you can do > > > =is.init_Pre().And.This.init_Exec() and the result is discarded so > > that is why it looks the way it does. ?In this form init_Exec has to > > return a value. ?However, If self.init_Pre(): self.init_Exec() would > > work the same and then I could avoid returning a value. > > > Thanks, > > Simon > > > On Aug 1, 5:52 am, Dave Angel wrote: > > >> Nat Williams wrote: > > >>> As MRAB described, ALL instance methods need to accept 'self' as a first > >>> parameter, as that will be passed to them implicitly when they are called. > >>> This includes __init__. ?The name 'self' is just a commonly accepted > >>> convention for the name of the instance object passed to methods. ?You don't > >>> have to call it that, but you really should. > > >>> Take a look athttp://docs.python.org/tutorial/classes.html#class-objects > >>> It might help shed some light on how methods and instances work. > > >>> One other thing. ?I'm a little confused by the first line of > >>> dcObject.__init__: > > >>> self.init_Pre() and self.init_Exec() > > >>> I suspect this does not do what you think it does. ?init_Pre and init_Exec > >>> will both be called by this expression (unless init_Pre throws an exception, > >>> of course). ?You're not getting anything here that you wouldn't by just > >>> calling each method on a separate line, except just making it harder to > >>> read. > > >> Read the doc-string for init_Pre() and for init_Exec(). ?The final > >> version of init_Pre() will return False in some circumstances, and in > >> those circumstances Simon doesn't want init_Exec() to be called. ?He's > >> deliberately using the short-circuit evaluation of ?'and' ?to accomplish > >> that. > > >>> On Fri, Jul 31, 2009 at 8:53 PM, Simon wrote: > > >>>> Hi > > >>>> So should the dcObject class include the "self" as well since I have > >>>> not defined an __init__ method in dcCursor? > > >>>> Simon > > >>>> -- > >>>>http://mail.python.org/mailman/listinfo/python-list > > >> Every one of those methods in both of those classes need a "self" first > >> argument. ?As others have said, all instance methods need a 'self.' > > (Please don't top-post. ?You should put new responses at the end of > quoted text, or sometimes inline if that's clearer.) > > I don't understand your comparison to Foxpro. ?read on. > > As your code was last posted, you don't need a return value from > init_Exec() ?Every function that doesn't have an explicit return will > return None. ?And None is interpreted as False in an "and" expression. ? > If you had an "if" around the whole thing, then you'd care. > > DaveA All I meant by the FoxPro comment was the idea of using the equal sign without a variable to throw away the result. Also in FoxPro there is no such thing as automatically returning None. If there is no explicit return then True is returned. Thanks I did not know that None is interpreted as False. Simon From no.email at please.post Mon Aug 3 16:58:46 2009 From: no.email at please.post (kj) Date: Mon, 3 Aug 2009 20:58:46 +0000 (UTC) Subject: kw param question References: Message-ID: In Albert Hopkins writes: >On Mon, 2009-08-03 at 19:59 +0000, kj wrote: >> >> I want to write a decorator that, among other things, returns a >> function that has one additional keyword parameter, say foo=None. >> >> When I try >> >> def my_decorator(f): >> # blah, blah >> def wrapper(*p, foo=None, **kw): >> x = f(*p, **kw) >> if (foo): >> # blah, blah >> else >> # blah blah >> return wrapper >> >> ...i get a syntax error where it says "foo=None". I get similar >> errors with everything else I've tried. >> >Not exactly sure what you're trying to do.. Yeah, I wasn't too clear. I figured out how to do what I wanted to do: def my_decorator(f): # blah, blah def wrapper(*p, **kw): foo = kw.pop('force', None) x = f(*p, **kw) if (foo): # blah, blah else # blah blah return wrapper Now the definitions of the original functions do not include the foo=None argument, but "actual" functions (i.e. the ones generated by the decorator) all accept the optional foo parameter. The only remaining problem is how to document this... I don't see how pydoc could possibly figure this one out. I guess this is sufficient argument to abandon this idea. Bummer. kynn From pavlovevidence at gmail.com Mon Aug 3 17:04:12 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Aug 2009 14:04:12 -0700 (PDT) Subject: iterate lines with regex References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> <4A771E94.70805@mrabarnett.plus.com> Message-ID: <463f3ea4-c8a4-405b-9eab-95a878684db0@a13g2000yqc.googlegroups.com> On Aug 3, 11:44?am, Robert Kern wrote: > On 2009-08-03 12:29, MRAB wrote: > > > > > > > Robert Kern wrote: > > [snip] > > >> for line in readThis: > >> key_match = key.search(line) > >> if key_match is not None: > >> this_key = key_match.group(1) > >> # ... do something with this_key > >> map_match = map.search(line) > >> if map_match is not None: > >> this_map = map_match.group(1) > >> # ... do something with this_map > >> parcel_match = parcel.search(line) > >> if parcel_match is not None: > >> this_parcel = parcel_match.group(1) > >> # ... do something with this_parcel > > > re.search and re.match will return a MatchObject if successful or None > > if unsuccessful. A MatchObject is always true, so you can simplify to: > > > ... > > if key_match: > > this_key = key_match.group(1) > > # ... do something with this_key > > ... > > True, but I prefer to maintain a consistent style for None-testing regardless of > whether or not I am sure the not-None type will have a suitable __nonzero__ > implementation. There's one thing to keep in mind. In the unknown future, it's possible that re.match could be changed to return an object with a false value that contains some information about the reason for failure, or partial match information, or something like that. If that happens, code like: if m: will continue to work, while code like if m is not None: will suddenly fail. Granted, it's not likely to happen for regexps but it could happen in similar situations in other places. I am one of the biggest critics of implicit boolean values, but given that Python has it, I think it is best to adhere strongly idiomatic uses like regexps. Carl Banks From sturlamolden at yahoo.no Mon Aug 3 17:04:53 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 3 Aug 2009 14:04:53 -0700 (PDT) Subject: Is python buffer overflow proof? References: Message-ID: On 2 Aug, 15:50, Jizzai wrote: > Is a _pure_ python program buffer overflow proof? > > For example in C++ you can declare a char[9] to hold user input. > If the user inputs 10+ chars a buffer overflow occurs. Short answer: NO Bounds checking on sequence types is a protection against buffer overflow, but is certainly not sufficient. The Python interpreter is written in C. Python extension modules are written in C (or something similar). If you find an unprotected buffer in this C code, you can possibly overflow this buffer. This can be used for nasty things like corrupting the stack and injecting malicious code. There is a reason why the Python sandbox (rexec and Bastion modules) was disabled in Python 2.3. IronPython and Jython provides better protection against buffer overflow than CPython, as these interpreters are written in safer languages (C# and Java). You thus get an extra layer of protection between the Python code and the unsafe C (used in JVM and .NET runtimes). From no.email at please.post Mon Aug 3 17:07:32 2009 From: no.email at please.post (kj) Date: Mon, 3 Aug 2009 21:07:32 +0000 (UTC) Subject: no-clobber dicts? Message-ID: I use the term "no-clobber dict" to refer to a dictionary D with the especial property that if K is in D, then D[K] = V will raise an exception unless V == D[K]. In other words, D[K] can be set if K doesn't exist already among D's keys, or if the assigned value is equal to the current value of D[K]. All other assignments to D[K] trigger an exception. The idea here is to detect inconsistencies in the data. This is a data structure I often need. Before I re-invent the wheel, I thought I'd ask: is it already available? TIA! kynn From aurele.tux at gmail.com Mon Aug 3 17:11:20 2009 From: aurele.tux at gmail.com (aurelien) Date: Mon, 03 Aug 2009 23:11:20 +0200 Subject: Hello to the community Message-ID: <1249333880.7712.20.camel@r2d2> Hello to the Python community ! I'm a totaly newbbie in this langage. I hope i will learn a lot with you. Thanks. aurelien From boris.arloff at yahoo.com Mon Aug 3 17:25:06 2009 From: boris.arloff at yahoo.com (Boris Arloff) Date: Mon, 3 Aug 2009 14:25:06 -0700 (PDT) Subject: Trying to get ABC to work Message-ID: <358094.5069.qm@web65302.mail.ac2.yahoo.com> Hi, ? Looking for ideas on getting Abstract Base Classes to work as intended within a metaclass. ? I was wondering if I could use an abc method within a metaclass to force a reimplementation when a class is instantiated from the metaclass.? It seems like I cannot do so.? I implemented the following test case: ? import abc class MetaExample(type): ? def __init__(cls, name, bases, ns): ??? setattr(cls, 'cls_meth', cls.cls_meth)??? # cls method as instance method ??? setattr(cls, 'cls_abc', cls.cls_abc)????????# abc cls method as instance method ? ? def cls_meth(cls): ??? print('Class method defined stub') ? ? @abc.abstractmethod ? def cls_abc(cls): ??? try: ????? print('Class-Abstract method defined stub') ??? except NotImplementedError, err: ????? print('Must implement cls_abc.') ??? except: ????? print('General exception at cls_abc method.') ? Then I create class MyKlass from the metaclass and instantiate it as myklass: MyKlass(object): __metaclass__ = MetaExample myklass = MyKlass() myklass.cls_meth()?? --> prints "Class method defined stub" myklass.cls_abc()???? --> prints "Class-Abstract method defined stub" ? I was hopping for myklass.cls_abc() to print "Must implement cls_abc." ? However, this makes sense since?MyKlass implements from the metaclass the cls_abc method and?there will never be an abstraction?of this method. ? Any ideas on how to get this done?? Any way I could define an abstract method within a metaclass and have it behave?with abstraction when the class is created off the metaclass? ? I other words, I want to force an implementation of cls_abc() method when MyKlass(object): __metaclass__ = MetaExample is declared, or else get NotImplementedError exception. ? Thanks, Boris Arloff ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Mon Aug 3 17:25:18 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 Aug 2009 14:25:18 -0700 Subject: Ordering of dict keys & values In-Reply-To: <3f1a902d0908031347g6e5dbbb7v832b0abc924a020@mail.gmail.com> References: <3f1a902d0908031347g6e5dbbb7v832b0abc924a020@mail.gmail.com> Message-ID: <50697b2c0908031425i22fd02ffjde3e41a697eb1c30@mail.gmail.com> On Mon, Aug 3, 2009 at 1:47 PM, Wells Oliver wrote: > I understand that the keys in a dictionary are ordered not randomly but > something practically close to it, but if I create a SQL query like so: > > query = 'INSERT INTO Batting (%s) VALUES(%s)' % (','.join(stats.keys()), > ','.join(stats.values())) > > Can I at least rely on the value being in the same index as its > corresponding key? Yes. Per http://docs.python.org/library/stdtypes.html#dict.items : """ Note: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary?s history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). """ Cheers, Chris -- http://blog.rebertia.com From Samnsparky at gmail.com Mon Aug 3 17:29:05 2009 From: Samnsparky at gmail.com (Sparky) Date: Mon, 3 Aug 2009 14:29:05 -0700 (PDT) Subject: WindowsError: exception: access violation writing 0x00000000 Message-ID: <73c6c4f5-a00b-4f95-a85d-0f257b2f001a@c2g2000yqi.googlegroups.com> Hello! I am using cTypes on Windows to interface with a dll and I keep getting an error when I execute this method: def eDigitalIn(self, channel, idNum = None, demo = 0, readD=0): """ Name: U12.eAnalogIn(channel, idNum = None, demo = 0, readD=0) Args: See section 4.4 of the User's Guide Desc: This is a simplified version of Counter. Reads & resets the counter (CNT). """ if idNum is None: idNum = self.id ljid = ctypes.c_long(idNum) state = ctypes.c_long(999) ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, readD, ctypes.byref(state)) if ecode != 0: raise LabJackException(ecode) if ljid == -1: raise LabJackException(-1, "LabJack not found.") return {"idnum":ljid.value, "state":state.value} Here is the error message: Traceback (most recent call last): File "", line 1, in device.eDigitalIn(0) File "C:\Documents and Settings\All Users\Documents\Python \LabJackPython_new\u12.py", line 118, in eDigitalIn ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, readD, ctypes.byref(state)) WindowsError: exception: access violation writing 0x00000000 Here is the signature of the method (which is known to work with C++ programs): long _stdcall EDigitalIn(long *idnum, long demo, long channel, long readD, long *state); staticLib is declared with staticLib = ctypes.windll.LoadLibrary ("ljackuw"). Any ideas? Thanks, Sam From rt8396 at gmail.com Mon Aug 3 17:47:54 2009 From: rt8396 at gmail.com (r) Date: Mon, 3 Aug 2009 14:47:54 -0700 (PDT) Subject: no-clobber dicts? References: Message-ID: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> On Aug 3, 4:07?pm, kj wrote: > I use the term "no-clobber dict" to refer to a dictionary D with > the especial property that if K is in D, then > > ? D[K] = V > > will raise an exception unless V == D[K]. ?In other words, D[K] > can be set if K doesn't exist already among D's keys, or if the > assigned value is equal to the current value of D[K]. ?All other > assignments to D[K] trigger an exception. > > The idea here is to detect inconsistencies in the data. > > This is a data structure I often need. ?Before I re-invent the > wheel, I thought I'd ask: is it already available? > > TIA! > > kynn Not sure if something like this already exists, but it would be trivial to implement by overriding dict.__setitem__() badda-bing baby! From clp2 at rebertia.com Mon Aug 3 18:00:14 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 Aug 2009 15:00:14 -0700 Subject: no-clobber dicts? In-Reply-To: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> References: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> Message-ID: <50697b2c0908031500w23af3271y49ef3aab49a67695@mail.gmail.com> On Mon, Aug 3, 2009 at 2:47 PM, r wrote: > On Aug 3, 4:07?pm, kj wrote: >> I use the term "no-clobber dict" to refer to a dictionary D with >> the especial property that if K is in D, then >> >> ? D[K] = V >> >> will raise an exception unless V == D[K]. ?In other words, D[K] >> can be set if K doesn't exist already among D's keys, or if the >> assigned value is equal to the current value of D[K]. ?All other >> assignments to D[K] trigger an exception. >> >> The idea here is to detect inconsistencies in the data. >> >> This is a data structure I often need. ?Before I re-invent the >> wheel, I thought I'd ask: is it already available? >> >> TIA! >> >> kynn > > Not sure if something like this already exists, but it would be > trivial to implement by overriding dict.__setitem__() That is, if you don't care about .update() not preserving the invariant. Otherwise, one will need to look at the UserDict module. Cheers, Chris -- http://blog.rebertia.com From ram.rachum at gmail.com Mon Aug 3 18:03:31 2009 From: ram.rachum at gmail.com (cool-RR) Date: Mon, 3 Aug 2009 15:03:31 -0700 (PDT) Subject: Announcing PythonTurtle References: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> Message-ID: On Aug 3, 11:35?pm, r wrote: > Hello, > I wanted to announce that I have just released my little side > project, > PythonTurtle. > [snip] > > I think it looks great --haven't download the source yet-- but i > really like the screenshot. This will be more "inviting" to the new, > inexperianced users. I like the idea of packaging up the command > prompt and the canvas into one very friendly interface. ?I especially > like that you are using a "real" turtle. > > I can remember the first time i used turtle (in python stdlib) and i > kept saying to myself... > > ? ? "Were the heck is this damn turtle?!?!" (>_<) > > :-) Thanks for the compliments; The things you mentioned you liked are all things that I was specifically thinking about when I decided to make PythonTurtle. Well, maybe minus the screenshot :) From victorsubervi at gmail.com Mon Aug 3 18:05:13 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Mon, 3 Aug 2009 18:05:13 -0400 Subject: RE Question In-Reply-To: References: <4dc0cfea0908021422x43972682ra58c53a2a43351ee@mail.gmail.com> Message-ID: <4dc0cfea0908031505t571b8d4cqa28579ae14c9209a@mail.gmail.com> That worked. Thank you again :) Victor On Mon, Aug 3, 2009 at 12:13 AM, Gabriel Genellina wrote: > En Sun, 02 Aug 2009 18:22:20 -0300, Victor Subervi < > victorsubervi at gmail.com> escribi?: > > > How do I search and replace something like this: >> aLine = re.sub('[<]?[p]?[>]?> a-zA-Z0-9"\'=:]*>[<]?[b]?[>]?', '', aLine) >> where RE *only* looks for the possibility of "

" at the beginning of the >> string; that is, not the individual components as I have it coded above, >> but >> the entire 3-character block? >> > > An example would make it more clear; I think you want to match either > "

" is > optional. Use a normal group or a non-capturing group: > r'(

)? > That said, using regular expressions to parse HTML or XML is terribly > fragile; I'd use a specific tool (like BeautifulSoup, ElementTree, or lxml) > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From darkneter at gmail.com Mon Aug 3 18:14:41 2009 From: darkneter at gmail.com (NighterNet) Date: Mon, 3 Aug 2009 15:14:41 -0700 (PDT) Subject: socket policy flash help References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> <8bede581-f260-4c69-abf0-1e8071380b76@z4g2000prh.googlegroups.com> <7e6cdc26-bcc0-4503-b7b4-9ad80b1041f6@v37g2000prg.googlegroups.com> Message-ID: On Aug 2, 12:25?pm, Piet van Oostrum wrote: > >>>>> NighterNet (N) wrote: > >N> Here the full code. > >N> flashpolicy.xml > >N> [[[ > >N> > >N> > >N> ? ? > >N> > >N> ]]] > >N> flashpolicytest_server3x.py > >N> [[[ > >N> #!/usr/local/bin/python > >N> ''' > >N> Still under testing... > >N> python version 3.x.x > >N> ''' > >N> importsocket > >N> import threading > >N> import sys > >N> import os > >N> file_name = 'flashpolicy.xml' > >N> fh = open(file_name, "r") > >N> policy = fh.read(10001) > > You never use that variable. > > > > >N> host = ''; #out side network > >N> port = 5555; > >N> print ("# ?------------- Init... ------------- ?#"); > >N> class ClientThread (threading.Thread): > >N> ? ? ? global policy; > >N> ? ? ? allClients = []; > >N> ? ? ? vlock = threading.Lock(); > >N> ? ? ? id = 0 # next available thread number > >N> ? ? ? def __init__(self,clientSocket): > >N> ? ? ? ? ? ? ? threading.Thread.__init__(self) > >N> ? ? ? ? ? ? ? self.sockfd = clientSocket; #socketclient > >N> ? ? ? ? ? ? ? self.name = ''; > >N> ? ? ? ? ? ? ? ClientThread.id += 1 > >N> ? ? ? ? ? ? ? self.id = ClientThread.id > >N> ? ? ? ? ? ? ? self.nickName = ''; > >N> ? ? ? ? ? ? ? self.allClients.append(self.sockfd); > >N> ? ? ? def sendAll(self,buff): > >N> ? ? ? ? ? ? ? for index,clientSock in enumerate(self.allClients): > >N> ? ? ? ? ? ? ? ? ? ? ? try: > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? clientSock.send(buff); > > There is no guarantee that send will indeed transmit all of buff. It is > better to use clientSock.sendall(buff). Or you should check the return > value of send and check if it is equal to the length of buff. And repeat > if not. (But sendall is easier). > > Also don't use ; at the end of the statement. It's not pythonic. > > >N> ? ? ? ? ? ? ? ? ? ? ? except (socket.error): > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print ('errorsocket%s\n',index,"| clean"); > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? clientSock.close() > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? del self.allClients[index] > >N> ? ? ? def run(self): > >N> ? ? ? ? ? ? ? while True: > >N> ? ? ? ? ? ? ? ? ? ? ? buff = self.sockfd.recv(1028); > > There is no guarantee that recv will get the whole message. It may even > get as little as 1 byte. So you should check the return value of recv. > The official way is to keep reading until you have enough input or until > you hit end of file. > > >N> ? ? ? ? ? ? ? ? ? ? ? if not buff: > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print ("connect close...(client side)"); > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.sockfd.close(); > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? break #incase it loop infinite > >N> ? ? ? ? ? ? ? ? ? ? ? if str(buff) == str("b\'\\x00\'"): > > What you check here is whether buff contains the byte sequence that starts with a > b, then a ' ... and ending with the 5 bytes \ x 0 0 ' which is wrong. > > Actually it should be: > > if buff == b\'\x00': > or > if buff == b\'\0': > > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print ('policy FOUND >>> sending...') > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print(buff) > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? b = b' >N> from domain=\"*\" to-ports=\"*\" />' > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print (b) > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.sockfd.send(b); > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.sockfd.sendall(b); > > Only self.sockfd.sendall; delete the line with self.sockfd.send(b). And > remove the semicolons for esthetical reasons. > > >N> Some odd reason I can't send flash policy from python to flashsocket > >N> to agrees with the connection. > > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org thanks it help. I was not sure about the format most the time. From nagle at animats.com Mon Aug 3 18:19:22 2009 From: nagle at animats.com (John Nagle) Date: Mon, 03 Aug 2009 15:19:22 -0700 Subject: Obtaining Python version Message-ID: <4a776184$0$1611$742ec2ed@news.sonic.net> This works, but it seems too cute: >>> pyver = map(int,sys.version.split()[0].split('.')) >>> print(pyver) [2, 6, 1] Is it guaranteed that the Python version string will be in a form suitable for that? In other words, does "sys.version" begin N.N.N other stuff in all versions, and will it stay that way? Are there ever non-numeric versions, like "3.2.rc1"? John Nagle From rhodri at wildebst.demon.co.uk Mon Aug 3 18:24:04 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 03 Aug 2009 23:24:04 +0100 Subject: fast video encoding In-Reply-To: <0c8cfac7-0a70-4e1f-90ec-19e9c45cae89@h21g2000yqa.googlegroups.com> References: <570097d0-2b2a-4705-892f-0d0154d69d63@b14g2000yqd.googlegroups.com> <0c8cfac7-0a70-4e1f-90ec-19e9c45cae89@h21g2000yqa.googlegroups.com> Message-ID: On Sun, 02 Aug 2009 03:44:17 +0100, sturlamolden wrote: > On 29 Jul, 10:14, gregorth wrote: > >> for a scientific application I need to save a video stream to disc for >> further post processing. > > I have worked a bit on this as well. There are two things that make > scientific applications different form common video encoding: > > First, a scientific video stream is often very different from a > 'movie': There are usually very little 'movement'. For example, when I > have filmed a mouse swimming in a water maze (a pool of milky white > water), the only thing that moves is the rat. So I could achieve > excellent compression just by saving the pixels that changed. These are referred to as P-frames; any encoder that gets further than the most basic version of any video protocol will do this for you. Unfortunately, water pixels change a lot from frame to frame, even when the camera is static, so it doesn't gain you as much as you might hope in cases like you mention. > Second, scientific data should be stored with lossless compression if > possible. If data storage is no object, be my guest. Of course, you're going to have to write your own codecs for this, since pretty much every video protocol in existence is lossy. In reality, lossless compression isn't necessary. As long as your quantisation isn't completely up the spout, the added precision isn't actually going to gain you anything unless you're working in very specialised situations; even then, if it does make a significant difference then you needed greater resolution anyway. -- Rhodri James *-* Wildebeest Herder to the Masses From andre.roberge at gmail.com Mon Aug 3 18:32:10 2009 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 3 Aug 2009 15:32:10 -0700 (PDT) Subject: Obtaining Python version References: <4a776184$0$1611$742ec2ed@news.sonic.net> Message-ID: <680573fa-6d5a-46eb-b48e-461841b8d887@c1g2000yqi.googlegroups.com> On Aug 3, 7:19?pm, John Nagle wrote: > This works, but it seems too cute: > > ?>>> pyver = map(int,sys.version.split()[0].split('.')) > ?>>> print(pyver) > [2, 6, 1] > You can also do: >>> import sys >>> sys.version_info (2, 5, 2, 'final', 0) or >>> sys.version_info[:3] (2, 5, 2) > Is it guaranteed that the Python version string will be in a form > suitable for that? ?In other words, does "sys.version" begin > > N.N.N other stuff > > in all versions, and will it stay that way? ?Are there ever > non-numeric versions, like "3.2.rc1"? > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle I strongly suspect that sys.version_info would never change... Andr? From rt8396 at gmail.com Mon Aug 3 18:34:53 2009 From: rt8396 at gmail.com (r) Date: Mon, 3 Aug 2009 15:34:53 -0700 (PDT) Subject: Announcing PythonTurtle References: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> Message-ID: <491ed6e7-08dd-4b26-acb8-38da475491ed@b14g2000yqd.googlegroups.com> On Aug 3, 5:03?pm, cool-RR wrote: [snip] > Thanks for the compliments; The things you mentioned you liked are all > things that I was specifically thinking about when I decided to make > PythonTurtle. Well, maybe minus the screenshot :) I *may* get roasted for this comment, but i think a turtle module along the lines of what you have here would better serve the stdlib. The current implementation is great, but the whole purpose of turtle is to help children or non-programmers get a feel of the language in a very, very, simple and fun way. Your app is presented in much the same way as any over-the-counter windows app any non-programmer has seen before making them *feel* a little more comfortable. [warning wild speculations ahead!!] I just guessing here, but i'll bet many of these *noobs* have found the current turtle just a wee-bit more advanced than they can handle, and *some* have been scared off. I would also venture to say a key-map of sorts that is available thru the help menu where one could push an "Up" button, or a "rotate" button, and have the proper command inserted in the prompt, and then have the command execute, may also help make the connections here, a sort of *real* Visual Basic programming -- sorry Microsoft :P From zuo at chopin.edu.pl Mon Aug 3 18:35:50 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 04 Aug 2009 00:35:50 +0200 Subject: Obtaining Python version In-Reply-To: <4a776184$0$1611$742ec2ed@news.sonic.net> References: <4a776184$0$1611$742ec2ed@news.sonic.net> Message-ID: 04-08-2009 o 00:19:22 John Nagle wrote: > This works, but it seems too cute: > > >>> pyver = map(int,sys.version.split()[0].split('.')) > >>> print(pyver) > [2, 6, 1] > > Is it guaranteed that the Python version string will be in a form > suitable for that? In other words, does "sys.version" begin > > N.N.N other stuff > > in all versions, and will it stay that way? Are there ever > non-numeric versions, like "3.2.rc1"? Why not to use: sys.version_info "A tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial. All values except releaselevel are integers; the release level is 'alpha', 'beta', 'candidate', or 'final'. The version_info value corresponding to the Python version 2.0 is (2, 0, 0, 'final', 0)." http://docs.python.org/library/sys.html#sys.version_info Cheers, *j -- Jan Kaliszewski (zuo) From keith at nekotaku.com Mon Aug 3 18:54:15 2009 From: keith at nekotaku.com (KB) Date: Mon, 3 Aug 2009 15:54:15 -0700 (PDT) Subject: Problem with reading CSV file from URL, last record truncated. Message-ID: <0996356d-ee7d-4a5e-9c0c-9f9502c01892@l5g2000pra.googlegroups.com> Hi, I am trying to download from a URL, a CSV using the following: import re import urllib, urllib2, cookielib import mechanize import csv import numpy import os def return_ranking(): cj = mechanize.MSIECookieJar(delayload=True) cj.load_from_registry() # finds cookie index file from registry # set things up for cookies opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) reply = opener.open('http://ichart.finance.yahoo.com/table.csv? s=CSCO&a=00&b=01&c=2009&d=01&e=2&f=2010&g=d&ignore=.csv').read() fout=open('csco.csv','wb') fout.write(reply) fout.close fin=open('csco.csv','rb') table = csv.reader(fin) fin.close for row in table: print row return_ranking() I need to use cookies etc (mechanize/urllib2) for a different, more complex URL but since it wasn't working, I went back to a simple Yahoo example (above) which I have working with urllib (not urllib2). The behaviour I am seeing is that the last record is being truncated: (sample output) ['2009-04-08', '17.29', '17.33', '16.94', '17.13', '45389100', '17.13'] ['2009-04-07', '17.20', '17.25', '16.58', '16.85', '59902600', '16.85'] ['200'] A friend said I should do the above writing out to a file and have csvreader read in the file, but as you can see, to no avail! Any help greatly appreciated! Note that urllib.urlretrieve works perfectly but I give up the ability to import cookies from my registry which is all important (AFAIK anyway mechanize requires urllib2). Any help greatly appreciated. From keith at nekotaku.com Mon Aug 3 19:21:02 2009 From: keith at nekotaku.com (KB) Date: Mon, 3 Aug 2009 16:21:02 -0700 (PDT) Subject: Problem with reading CSV file from URL, last record truncated. References: <0996356d-ee7d-4a5e-9c0c-9f9502c01892@l5g2000pra.googlegroups.com> Message-ID: On Aug 3, 3:54?pm, KB wrote: > Hi, > > I am trying to download from a URL, a CSV using the following: > > import re > import urllib, urllib2, cookielib > import mechanize > import csv > import numpy > import os > > def return_ranking(): > > ? ? ? ? cj = mechanize.MSIECookieJar(delayload=True) > ? ? ? ? cj.load_from_registry() ?# finds cookie index file from registry > > ? ? ? ? # set things up for cookies > > ? ? ? ? opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > > ? ? ? ? urllib2.install_opener(opener) > > ? ? ? ? reply = opener.open('http://ichart.finance.yahoo.com/table.csv? > s=CSCO&a=00&b=01&c=2009&d=01&e=2&f=2010&g=d&ignore=.csv').read() > > ? ? ? ? fout=open('csco.csv','wb') > ? ? ? ? fout.write(reply) > ? ? ? ? fout.close > > > return_ranking() > > I need to use cookies etc (mechanize/urllib2) for a different, more > complex URL but since it wasn't working, I went back to a simple Yahoo > example (above) which I have working with urllib (not urllib2). > > The behaviour I am seeing is that the last record is being truncated: > > (sample output) > ['2009-04-08', '17.29', '17.33', '16.94', '17.13', '45389100', > '17.13'] > ['2009-04-07', '17.20', '17.25', '16.58', '16.85', '59902600', > '16.85'] > ['200'] > > A friend said I should do the above writing out to a file and have > csvreader read in the file, but as you can see, to no avail! > > Any help greatly appreciated! Note that urllib.urlretrieve works > perfectly but I give up the ability to import cookies from my registry > which is all important (AFAIK anyway mechanize requires urllib2). > > Any help greatly appreciated. By moving: > fin=open('csco.csv','rb') > table = csv.reader(fin) > fin.close > > for row in table: > print row outside of the routine and into the mainline, it works like a charm. Would like to know why though, so would love to hear any clues! From piet at cs.uu.nl Mon Aug 3 19:26:58 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 04 Aug 2009 01:26:58 +0200 Subject: Executing remote command with paramiko References: Message-ID: >>>>> Hussein B (HB) wrote: >HB> Hey, >HB> I'm trying to run a sudo guarded command over SSH using paramiko >HB> +++++++++++++++++++ >HB> s = paramiko.SSHClient() >HB> s.load_system_host_keys() >HB> s.connect(hostname, port, username, passwd) >HB> stdin, stdout, stderr = s.exec_command('sudo -s') >HB> stdin.write('password\n') >HB> stdin.flush() >HB> print 'Flushing' >HB> stdin, stdout, stderr = s.exec_command('harvester') >HB> print stdout.read() >HB> s.close() >HB> +++++++++++++++++++ >HB> It seems to me that the sudo -s isn't getting executed at all. >HB> I commented the sudo -s code lines and no error is shown. >HB> Thanks for help and time. Your command 'harvester' is not run in the sudo shell, but separately in a new session. so it will run under 'username', not under 'root'. You could use stdin, stdout, stderr = s.exec_command('sudo harvester') instead. Or use the lower-level constructs: s = paramiko.SSHClient() s.load_system_host_keys() s.connect(hostname, port, username, password) t = s.get_transport() chan = t.open_session() chan.exec_command('sudo -s') print 'writing password' chan.send(password + '\n') print 'write command' chan.send('whoami\n') print "try to read" print chan.recv(9999) For more control you can use chan.recv_ready() to see if output is available. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From greg at cosc.canterbury.ac.nz Mon Aug 3 19:35:12 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 04 Aug 2009 11:35:12 +1200 Subject: Help understanding the decisions *behind* python? In-Reply-To: <4a7715ff$0$1641$742ec2ed@news.sonic.net> References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> <4a7715ff$0$1641$742ec2ed@news.sonic.net> Message-ID: <7dpagaF2cu16mU1@mid.individual.net> John Nagle wrote: > Mesa used tuples for subroutine arguments in a very straightforward > way. Every function took one tuple as an argument > > Python doesn't go that far. I believe that a very early version of Python did do something like that, but it was found to be a bad idea, because there was an ambiguity between multiple args and a single arg that happened to be a tuple. This was before keyword arguments existed -- they would have been hard to incorporate into the old scheme. -- Greg From rt8396 at gmail.com Mon Aug 3 19:39:25 2009 From: rt8396 at gmail.com (r) Date: Mon, 3 Aug 2009 16:39:25 -0700 (PDT) Subject: no-clobber dicts? References: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> Message-ID: <1d95f706-71f4-487e-a920-a31643b76c10@w6g2000yqw.googlegroups.com> On Aug 3, 5:00?pm, Chris Rebert wrote: > On Mon, Aug 3, 2009 at 2:47 PM, r wrote: [snip] > > Not sure if something like this already exists, but it would be > > trivial to implement by overriding dict.__setitem__() > > That is, if you don't care about .update() not preserving the > invariant. Otherwise, one will need to look at the UserDict module. > > Cheers, > Chris > --http://blog.rebertia.com Good catch Chris. However since the OP said this was for testing purposes, i just *assumed* he would be smart enough *not* to call update() on the dict at hand ;-). But sometimes i need to be protected from myself too -- at least thats what my therapist keeps telling me :-) From greg at cosc.canterbury.ac.nz Mon Aug 3 19:40:06 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 04 Aug 2009 11:40:06 +1200 Subject: fast video encoding In-Reply-To: References: <570097d0-2b2a-4705-892f-0d0154d69d63@b14g2000yqd.googlegroups.com> <0c8cfac7-0a70-4e1f-90ec-19e9c45cae89@h21g2000yqa.googlegroups.com> Message-ID: <7dpapgF2ckro4U1@mid.individual.net> Rhodri James wrote: > Unfortunately, water pixels change a lot from frame to frame, even > when the camera is static, so it doesn't gain you as much as you might > hope in cases like you mention. In the case mentioned, the water is of no interest, so it could be removed altogether by a suitable custom compressor. -- Greg From python at mrabarnett.plus.com Mon Aug 3 19:47:23 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Aug 2009 00:47:23 +0100 Subject: Problem with reading CSV file from URL, last record truncated. In-Reply-To: References: <0996356d-ee7d-4a5e-9c0c-9f9502c01892@l5g2000pra.googlegroups.com> Message-ID: <4A77770B.2070008@mrabarnett.plus.com> KB wrote: > On Aug 3, 3:54 pm, KB wrote: >> Hi, >> >> I am trying to download from a URL, a CSV using the following: >> >> import re >> import urllib, urllib2, cookielib >> import mechanize >> import csv >> import numpy >> import os >> >> def return_ranking(): >> >> cj = mechanize.MSIECookieJar(delayload=True) >> cj.load_from_registry() # finds cookie index file from registry >> >> # set things up for cookies >> >> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) >> >> urllib2.install_opener(opener) >> >> reply = opener.open('http://ichart.finance.yahoo.com/table.csv? >> s=CSCO&a=00&b=01&c=2009&d=01&e=2&f=2010&g=d&ignore=.csv').read() >> >> fout=open('csco.csv','wb') >> fout.write(reply) >> fout.close This should be: fout.close() >> > >> return_ranking() >> [snip] > By moving: >> fin=open('csco.csv','rb') >> table = csv.reader(fin) >> fin.close This should be: fin.close() >> >> for row in table: >> print row > > outside of the routine and into the mainline, it works like a charm. > > Would like to know why though, so would love to hear any clues! > The parentheses aren't optional; without them you're just referring to the method, not calling it. Because you weren't closing the file the text wasn't all written to disk. When it returns from return_ranking() there's no longer any reference to 'fout', so the file object is available for collection by the garbage collector. When the file object is collected it writes the remaining text to disk. In CPython the file object is collected as soon as there's no reference to it, but in other implementations that might not be the case. From mensanator at aol.com Mon Aug 3 20:32:03 2009 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Aug 2009 17:32:03 -0700 (PDT) Subject: Announcing PythonTurtle References: Message-ID: On Aug 3, 8:18?am, cool-RR wrote: > Hello, > > I wanted to announce that I have just released my little side project, > PythonTurtle. > Here is its website:http://pythonturtle.com > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > You can read more about it and download it on the website. I dunno, looks kind of worthless to me. http://www.mensanator.com/mensanator/PythonTurtle/PythonTurtle.htm > > Ram. From van.lindberg at gmail.com Mon Aug 3 20:42:14 2009 From: van.lindberg at gmail.com (VanL) Date: Mon, 03 Aug 2009 19:42:14 -0500 Subject: Extracting text from html Message-ID: Hello all, Does anyone know of a good tool to get a minimally-formatted text document out of an html document? Something along the lines of what you would get with a lynx -dump, but in Python. I have lxml installed, so I can roll my own if I need to. However, this seemed like the sort of thing that someone would have solved already. Thanks, Van From gagsl-py2 at yahoo.com.ar Mon Aug 3 20:42:47 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Aug 2009 21:42:47 -0300 Subject: Python configuration question when python scripts are executed using Appweb as web server. References: Message-ID: En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife escribi?: > I have installed python 2.6.2 in windows xp professional machine. I > have set the following environment variables -- PYTHONPATH. It points > to following windows folders: python root folder, the lib folder and > lib-tk folder. Why? Did you read it somewhere? Usually there is no need to set the PYTHONPATH variable at all; remove it. > I have configured IIS to execute python scripts. > > I do not have any issues executing python scripts from the python > interpreter window or from the browser using IIS as the web server. Try again after PYTHONPATH is removed, and make sure you can import all the required modules from the Python console. Only then try to run the cgi scripts. > However, when I use the open source Appweb web browser to execute > python scripts. It is able to execute only simple script without > issues. [...]However I am not able to execute python scripts that > contain import > statements. I need to point out here that i do not have issue with > using os or sys packages. When I tried to execute the sample client > script that came with the gnutls wrapper for python, I got error. I > narrowed it down to the "from ... import" line in the example. > > from gnutls.crypto import * > from gnutls.connection import * Check that the above lines work fine from inside the Python console. If not, something went wrong when you installed the gnutls Python package. > Next step, in order to debug, I used the module finder to see what is > happening. To being with I used the module finder to find out the > modules loaded for the simple script hello.py. Debugging cgi scripts isn't easy sometimes; try adding this line at the start of your script: import cgitb;cgitb.enable() You should get a nicely formatted stack trace whenever an exception is raised. If you get an HTTP error instead (like 500 Internal Server Error) it's likely a syntax error, you must fix it before continuing. Then, you may find that modulefinder is no more needed. > import pdb > pdb.set_trace() pdb cannot work inside a CGI script; remove that. > Once again, let me stress that this issue is happening only when I use > appweb as the web server. I don't know appweb, but if you first make sure the script works from the command line, it should be much easier to make it work in the web server. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Aug 3 21:10:57 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Aug 2009 22:10:57 -0300 Subject: easy_install: unresolved external symbol References: <2119ee90908031339o71e19624qa815241b446d739d@mail.gmail.com> Message-ID: En Mon, 03 Aug 2009 17:39:44 -0300, Bart Smeets escribi?: > I keep getting errors when trying to use easy_install to install > bbfreeze or > cxfreeze (same errors). > This is the output: > http://pastebin.com/m65ba474d Can't you use the binary packages? -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Aug 3 21:18:08 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Aug 2009 22:18:08 -0300 Subject: Ordering of dict keys & values References: <3f1a902d0908031347g6e5dbbb7v832b0abc924a020@mail.gmail.com> Message-ID: En Mon, 03 Aug 2009 17:47:23 -0300, Wells Oliver escribi?: > I understand that the keys in a dictionary are ordered not randomly but > something practically close to it, but if I create a SQL query like so: > > query = 'INSERT INTO Batting (%s) VALUES(%s)' % (','.join(stats.keys()), > ','.join(stats.values())) > > Can I at least rely on the value being in the same index as its > corresponding key? You already got the answer you wanted, but note that building a SQL statement that way is unsafe [1]. I prefer this way: query= 'INSERT INTO Batting (%s) VALUES(%s)' % ( ','.join(stats.keys()), ','.join(['?']*len(stats))) cursor.execute(query, stats.values()) [1] If you don't know what "SQL injection" means, see http://xkcd.com/327/ -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Aug 3 21:39:50 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Aug 2009 22:39:50 -0300 Subject: Is python buffer overflow proof? References: Message-ID: En Mon, 03 Aug 2009 18:04:53 -0300, sturlamolden escribi?: > On 2 Aug, 15:50, Jizzai wrote: > >> Is a _pure_ python program buffer overflow proof? >> >> For example in C++ you can declare a char[9] to hold user input. >> If the user inputs 10+ chars a buffer overflow occurs. > > Short answer: NO > > Bounds checking on sequence types is a protection against buffer > overflow, but is certainly not sufficient. > > The Python interpreter is written in C. Python extension modules are > written in C (or something similar). If you find an unprotected buffer > in this C code, you can possibly overflow this buffer. This can be > used for nasty things like corrupting the stack and injecting > malicious code. There is a reason why the Python sandbox (rexec and > Bastion modules) was disabled in Python 2.3. (I think the reason rexec and bastion were disabled has nothing to do with the possibility of buffer overflows in extension modules) > IronPython and Jython provides better protection against buffer > overflow than CPython, as these interpreters are written in safer > languages (C# and Java). You thus get an extra layer of protection > between the Python code and the unsafe C (used in JVM and .NET > runtimes). I disagree. You've just translated the responsability to check for buffer overflows, from the Python VM, to the Java VM or the .Net runtime (and all three suffered from buffer overruns and other problems in some way or another). Also, Python extensions written in C are equivalent to using JNI in Java or unmanaged code in C#: all three are likely to have hidden problems. It's always the same story: a *language* may declare that such things are impossible, but a particular *implementation* may have bugs and fail to comply with the specification. -- Gabriel Genellina From cocobear.cn at gmail.com Mon Aug 3 21:44:49 2009 From: cocobear.cn at gmail.com (cocobear) Date: Mon, 3 Aug 2009 18:44:49 -0700 (PDT) Subject: merge two png pic References: Message-ID: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> On Jul 31, 2:52?pm, Peter Otten <__pete... at web.de> wrote: > cocobear wrote: > > On Jul 29, 9:20 am, cocobear wrote: > >> Thistwopngfile has their own palette > > >> >>> im1.mode > >> 'P' > >> >>> im.mode > >> 'P' > >> >>> im.getpalette == im1.getpalette > > >> False > > >> I can use this code tomergetwopngpictogether: > > >> Map = Image.new("RGB", (x,y)) > >> Map.paste(im, box) > >> Map.paste(im1,box) > > >> Map = Map.convert("L", optimize=True, palette=Image.ADAPTIVE) > > >> But if thetwopngpicis too big , or if I have tomergemorepic > >> together, I will get MemoryError: > > >> >>> Image.new("RGB",(44544,38656)) > > As a workaround you could split the image into tiles that fit into your > machine's RAM. Or you could try to do the rendering on a 64-bit system. > You'll need at least > > >>> 3*44544*38656./(2**30) > > 4.8109130859375 > > 5 gigabytes for the target image plus memory for the biggest source image. > Alternatively there are probably tools that can keep parts of the image on > disk (imagemagick, maybe? you'll have to check yourself or ask in a > specialized forum). As a last resort you should be able to write such a tool > yourself. I don't know how hard it would be to generate the PNG, but the RGB > pasting should be trivial. > Thanks for you reply. Map = Image.new("RGB", ((x2-x1+1)*256, (y2-y1+1)*256)) for x in range(x1,x2+1): for y in range(y1,y2+1): #print x,y filename = "v=cn1.11&hl=zh-CN&x=%d&y=%d&z=%d&s=Galile" % (x,y,z) # box = ((x-x1)*256, (y-y1)*256, (x-x1)*256+256, (y-y1) *256+256) #print box im = Image.open(filename+".png") Map.paste(im, box) temp = "temp_map.png" Map.save(temp) del Map print "converting" Map = Image.open(temp) Map = Map.convert("P", palette=Image.ADAPTIVE) Now I use code above, the problem is when I create a RGB image, I need four times spaces then a 'P' mode image. Can I directly create a 'P' mode image, and paste those images on? (NOTICE: this small image has different palette) > >> Traceback (most recent call last): > >> File "", line 1, in > >> File "/usr/lib/python2.5/site-packages/PIL/Image.py", line 1710, in > >> new > >> return Image()._new(core.fill(mode, size, color)) > >> MemoryError > > >> How can I directlymergetwopicto a ?P' modepngwith palette. > > > Nobody replied. > > What do you want to do with such a big image? You will run into the same > limitation when you are trying to display it. > I want to download a map from google map with high precision > Peter From afriere at yahoo.co.uk Mon Aug 3 21:53:02 2009 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 3 Aug 2009 18:53:02 -0700 (PDT) Subject: Announcing PythonTurtle References: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> Message-ID: <1d144bd0-8829-4449-8935-60bf6f66a5d6@l5g2000pra.googlegroups.com> On Aug 4, 6:35?am, r wrote: [snip] > > I can remember the first time i used turtle (in python stdlib) and i > kept saying to myself... > > ? ? "Were the heck is this damn turtle?!?!" (>_<) > > :-) In Python2.6, try this: >>> turtle.shape('turtle') From benjamin.kaplan at case.edu Mon Aug 3 22:15:03 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 3 Aug 2009 22:15:03 -0400 Subject: [OT] Re: Ordering of dict keys & values In-Reply-To: References: <3f1a902d0908031347g6e5dbbb7v832b0abc924a020@mail.gmail.com> Message-ID: On Mon, Aug 3, 2009 at 9:18 PM, Gabriel Genellina wrote: > > [1] If you don't know what "SQL injection" means, see http://xkcd.com/327/ I love how XKCD is one of the preferred learning tools (along with Wikipeida) for people on this list. I think Randall Munroe should make a comic about it. :) From justin.mailinglists at gmail.com Mon Aug 3 22:32:22 2009 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Mon, 3 Aug 2009 19:32:22 -0700 (PDT) Subject: Extracting text from html References: Message-ID: <44201d0e-87fe-457e-a7e2-26b2c5027d76@b25g2000prb.googlegroups.com> http://tinyurl.com/kpoweq From fft1976 at gmail.com Mon Aug 3 22:51:36 2009 From: fft1976 at gmail.com (fft1976) Date: Mon, 3 Aug 2009 19:51:36 -0700 (PDT) Subject: RUBY vs COMMON LISP References: <389503e4-eb6a-48c2-af76-cebe1dc7141c@h30g2000vbr.googlegroups.com> <87my6ic1k5.fsf@galatea.local> <1a40c8fe-83e4-4c50-90e2-b72ef86a6ac4@m7g2000prd.googlegroups.com> <87hbwp9umw.fsf@galatea.local> Message-ID: <04aef600-150d-44fa-a0cd-d88a4b17e836@m7g2000prd.googlegroups.com> On Aug 3, 1:19?am, p... at informatimago.com (Pascal J. Bourguignon) wrote: > fft1976 writes: > > By the way, here is in 1 line of BF, a complete BF reader that is able > > to > > read all the BF syntax needed to write it: > > > ,+[-.,+] > > > Here's how to try it: > > > $ sudo apt-get install bf > > $ cat > reader.bf > > ,+[-.,+] > > $ bf reader.bf < reader.bf > > > Your 150 lines don't look very impressive now, do they? > > > Ruby < Lisp <<< BF! > > I specified a syntactic reader. ?Not just a reader. It is a syntactic reader. BF's syntax is just a sequence of characters. If you throw in illegal characters, the behavior is "undefined". Lisp's syntax is more complicated: it's a tree of identifiers (in its idealized form; of course, Common Lisp had to fuck it up). Ruby's and Python's syntaxes are even more complicated. The above was to illustrate the wrongness of your argument that the length of a self-parser determines the usefulness of the language. Hell, I know that BF can be a little *too* awesome. By the way, Python's syntax is much better than Ruby's. Dollar signs in front of variables? WTF were the designers smoking? That's like Perl! Haven't you learned your lesson? Python's syntax might even be better than Lisp's, but it's certainly harder to parse. From pavlovevidence at gmail.com Mon Aug 3 23:00:08 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Aug 2009 20:00:08 -0700 (PDT) Subject: Seeding the rand() Generator References: Message-ID: <0b7c702f-5775-418e-8fc5-2f9df7487867@c2g2000yqi.googlegroups.com> On Aug 3, 8:12?pm, Fred Atkinson wrote: > On Sun, 2 Aug 2009 17:00:40 -0700 (PDT), Carl Banks > > wrote: > > ? ? ? ? I appreciate the response. ? > > ? ? ? ? I am executing a statement to retrieve one record at random. ? > > ? ? ? ? An example would be: SELECT first, second, third, fourth, > fifth, sixth from sometable order by rand() limit 1 > > ? ? ? ? It would be contained as: stmt = "SELECT first, second, third, > fourth, fifth, sixth from sometable order by rand() limit 1" > > ? ? ? ? Then I would execute it with the command: cursor.execute(stmt) > > ? ? ? ? How would I correctly seed the random generator in the MySQL > statement from within Python? ? You apparently know how to run MySQL statements from Python, correct? You also apparently know how to run a particular MySQL statement from PHP that seeds the random number generator, correct? Given those two apparent facts, you should be able run whatever statement you ran in PHP to seed the RNG in Python. So I don't see what the problem is. Your question is a MySQL question, not a Python question. I don't know off hand how to seed the RNG in MySQL, and, since this is a Python group and not a MySQL group, I don't care to look it up. But if you were able to produce the MySQL statement in PHP that does it you shouldn't need to ask. If you don't "get" why this is a MySQL question and not a Python question, then you need to learn more about what you are doing. Carl Banks From davea at ieee.org Mon Aug 3 23:00:13 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Aug 2009 23:00:13 -0400 Subject: Newbie Question regarding __init__() In-Reply-To: <01bcf8b8-687c-4bf4-acbb-b059a480d382@f33g2000vbm.googlegroups.com> References: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> <01bcf8b8-687c-4bf4-acbb-b059a480d382@f33g2000vbm.googlegroups.com> Message-ID: <4A77A43D.4000709@ieee.org> Simon wrote: > On Aug 2, 5:51 am, Dave Angel wrote: > >> >> I don't understand your comparison to Foxpro. read on. >> >> As your code was last posted, you don't need a return value from >> init_Exec() Every function that doesn't have an explicit return will >> return None. And None is interpreted as False in an "and" expression. >> If you had an "if" around the whole thing, then you'd care. >> >> DaveA >> > > All I meant by the FoxPro comment was the idea of using the equal sign > without a variable to throw away the result. Also in FoxPro there is > no such thing as automatically returning None. If there is no > explicit return then True is returned. > > Thanks I did not know that None is interpreted as False. > > Simon > > > To throw away the result of an expression in Python is even easier. Just don't use it. func1() and func2() is a valid expression whose result is not used. And func2()'s result is therefore irrelevant. But shortcircuiting means that func2() is only called if func1() returned False (or something equivalent to it, like 0 or an empty list) From pavlovevidence at gmail.com Mon Aug 3 23:02:26 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Aug 2009 20:02:26 -0700 (PDT) Subject: RUBY vs COMMON LISP References: <389503e4-eb6a-48c2-af76-cebe1dc7141c@h30g2000vbr.googlegroups.com> <87my6ic1k5.fsf@galatea.local> <1a40c8fe-83e4-4c50-90e2-b72ef86a6ac4@m7g2000prd.googlegroups.com> <87hbwp9umw.fsf@galatea.local> <04aef600-150d-44fa-a0cd-d88a4b17e836@m7g2000prd.googlegroups.com> Message-ID: <3755ae21-b7b0-4f82-99d4-1095ec953c39@s6g2000vbp.googlegroups.com> On Aug 3, 7:51?pm, fft1976 wrote: > On Aug 3, 1:19?am, p... at informatimago.com (Pascal J. Bourguignon) > wrote: > > > > > > > fft1976 writes: > > > By the way, here is in 1 line of BF, a complete BF reader that is able > > > to > > > read all the BF syntax needed to write it: > > > > ,+[-.,+] > > > > Here's how to try it: > > > > $ sudo apt-get install bf > > > $ cat > reader.bf > > > ,+[-.,+] > > > $ bf reader.bf < reader.bf > > > > Your 150 lines don't look very impressive now, do they? > > > > Ruby < Lisp <<< BF! > > > I specified a syntactic reader. ?Not just a reader. > > It is a syntactic reader. BF's syntax is just a sequence of > characters. If you throw in illegal characters, the behavior is > "undefined". Lisp's syntax is more complicated: it's a tree of > identifiers (in its idealized form; of course, Common Lisp had to fuck > it up). Ruby's and Python's syntaxes are even more complicated. > > The above was to illustrate the wrongness of your argument that the > length of a self-parser determines the usefulness of the language. > Hell, I know that BF can be a little *too* awesome. > > By the way, Python's syntax is much better than Ruby's. Dollar signs > in front of variables? WTF were the designers smoking? That's like > Perl! Haven't you learned your lesson? > > Python's syntax might even be better than Lisp's, but it's certainly > harder to parse.- Hide quoted text - Go away, troll. [This is cross-posted; I recommend that no one else follow up.] Carl Banks From fft1976 at gmail.com Mon Aug 3 23:06:58 2009 From: fft1976 at gmail.com (fft1976) Date: Mon, 3 Aug 2009 20:06:58 -0700 (PDT) Subject: RUBY vs COMMON LISP References: <389503e4-eb6a-48c2-af76-cebe1dc7141c@h30g2000vbr.googlegroups.com> <87my6ic1k5.fsf@galatea.local> <1a40c8fe-83e4-4c50-90e2-b72ef86a6ac4@m7g2000prd.googlegroups.com> <87hbwp9umw.fsf@galatea.local> <04aef600-150d-44fa-a0cd-d88a4b17e836@m7g2000prd.googlegroups.com> <3755ae21-b7b0-4f82-99d4-1095ec953c39@s6g2000vbp.googlegroups.com> Message-ID: On Aug 3, 8:02?pm, Carl Banks wrote: > On Aug 3, 7:51?pm, fft1976 wrote: > > > > > On Aug 3, 1:19?am, p... at informatimago.com (Pascal J. Bourguignon) > > wrote: > > > > fft1976 writes: > > > > By the way, here is in 1 line of BF, a complete BF reader that is able > > > > to > > > > read all the BF syntax needed to write it: > > > > > ,+[-.,+] > > > > > Here's how to try it: > > > > > $ sudo apt-get install bf > > > > $ cat > reader.bf > > > > ,+[-.,+] > > > > $ bf reader.bf < reader.bf > > > > > Your 150 lines don't look very impressive now, do they? > > > > > Ruby < Lisp <<< BF! > > > > I specified a syntactic reader. ?Not just a reader. > > > It is a syntactic reader. BF's syntax is just a sequence of > > characters. If you throw in illegal characters, the behavior is > > "undefined". Lisp's syntax is more complicated: it's a tree of > > identifiers (in its idealized form; of course, Common Lisp had to fuck > > it up). Ruby's and Python's syntaxes are even more complicated. > > > The above was to illustrate the wrongness of your argument that the > > length of a self-parser determines the usefulness of the language. > > Hell, I know that BF can be a little *too* awesome. > > > By the way, Python's syntax is much better than Ruby's. Dollar signs > > in front of variables? WTF were the designers smoking? That's like > > Perl! Haven't you learned your lesson? > > > Python's syntax might even be better than Lisp's, but it's certainly > > harder to parse.- Hide quoted text - > > Go away, troll. > > [This is cross-posted; I recommend that no one else follow up.] > > Carl Banks Lispers were having fun badmouthing other languages for no good reason: """ Don't you realize how ugly Ruby syntax is? Here is in 150 lines of lisp, a simplified lisp reader that is able to read all the lisp syntax needed to write it. Try to parse Ruby syntax in Ruby and see how useless a language it is. """ http://groups.google.com/group/comp.lang.lisp/msg/52dde974d504ad54 Of course you don't like it when I point out just how wrong you are. From fatkinson at mishmash.com Mon Aug 3 23:12:49 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Mon, 03 Aug 2009 20:12:49 -0700 Subject: Seeding the rand() Generator References: Message-ID: On Sun, 2 Aug 2009 17:00:40 -0700 (PDT), Carl Banks wrote: I appreciate the response. I am executing a statement to retrieve one record at random. An example would be: SELECT first, second, third, fourth, fifth, sixth from sometable order by rand() limit 1 It would be contained as: stmt = "SELECT first, second, third, fourth, fifth, sixth from sometable order by rand() limit 1" Then I would execute it with the command: cursor.execute(stmt) How would I correctly seed the random generator in the MySQL statement from within Python? Regards, Fred From steven at REMOVE.THIS.cybersource.com.au Mon Aug 3 23:23:20 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 03:23:20 GMT Subject: no-clobber dicts? References: Message-ID: On Mon, 03 Aug 2009 21:07:32 +0000, kj wrote: > I use the term "no-clobber dict" to refer to a dictionary D with the > especial property that if K is in D, then > > D[K] = V > > will raise an exception unless V == D[K]. In other words, D[K] can be > set if K doesn't exist already among D's keys, or if the assigned value > is equal to the current value of D[K]. All other assignments to D[K] > trigger an exception. Coincidentally, I just built something very close to what you ask. Here it is: class ConstantNamespace(dict): """Dictionary with write-once keys.""" def __delitem__(self, key): raise TypeError("can't unbind constants") def __setitem__(self, key, value): if key in self: raise TypeError("can't rebind constants") super(ConstantNamespace, self).__setitem__(key, value) def clear(self): raise TypeError('cannot unbind constants') def pop(self, key, *args): raise TypeError("cannot pop constants") def popitem(self): raise TypeError("cannot pop constants") def update(self, other): for key in other: if key in self: raise TypeError('cannot update constants') # If we get here, then we're not modifying anything, # so okay to proceed. super(ConstantNamespace, self).update(other) def copy(self): c = self.__class__(**self) return c I also have a series of unit tests for it if you're interested in them. -- Steven From davea at ieee.org Mon Aug 3 23:23:38 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Aug 2009 23:23:38 -0400 Subject: file comparison In-Reply-To: <29a34bc20908031748j11280ab0mb4303da4156db54b@mail.gmail.com> References: <29a34bc20907310225n50b35fe2m322872af2058a465@mail.gmail.com> <200907311247.30793.hendrik@microcorp.co.za> <4A72E9BF.3080808@ieee.org> <29a34bc20908031748j11280ab0mb4303da4156db54b@mail.gmail.com> Message-ID: <4A77A9BA.4090104@ieee.org> learner learner wrote: > Firstly thanks for showing the interest. I shall elobarate more on the > problem: > > file-1.txt > -------------- > hai > how > r > u > > file-2.txt > --------------- > r > hai > u > > > The two files have some lines in common. > > For eg: File-1.txt-first line-"hai" does not match with File-2.txt-first > line-"r" but surely matches with File-2.txt -second > > line -"hai". On having an iterative search the file-1.txt should finally be > left out with mismatched string "how", which is > > to be dumped into a third file say file3.txt or rewritten to > file-1.txt/file-2.txt with this single word "how" in line 1. > > some facts to remember: > ------------------------ > > the srings in the files will be same including case sentiveness if at all > present, else will be pronounced as a mismatch. > > this is bascically an iterative string search amongst the files and > isolating the mismatched strings into a text file > > (By replying off-list, you are ignoring the intent of public mailing lists. So I'm copying your message to the list, along with my response.) As I said before: If the text files are each a list of items, with order and duplication irrelevant, then your best bet is probably to build a set from each, and difference the sets. Sets are case-sensitive, and your example above indicates that order is at least partially irrelevant to you. So read each file, converting the lines into a set. Then do a set difference of those two sets. Then build a list from the result, and write that to a file. If it doesn't work, post the code you tried, along with sample data and expected output for that sample data. DaveA From steven at REMOVE.THIS.cybersource.com.au Mon Aug 3 23:30:35 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 03:30:35 GMT Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: On Mon, 03 Aug 2009 16:38:43 +0200, Jean-Michel Pichavant wrote: > So what's the purpose of making > >>from Module import factory as a >>from Module import factory as b > > return 2 different objects ? If I had to write this code I would expect > 'a is b' to return 'True'. > > This is no "don't do that" answer, it's a sincere question: what is the > benefit of your /new/ syntax ? Consider it "properties for modules": a = obj.factory b = obj.factory doesn't promise that a is b, because factory might be a property that returns a new object each time. Actually, this behaviour pre-dates properties. If obj has a __getattr__ or __getattribute__ method, then it could do the same thing. -- Steven From steven at REMOVE.THIS.cybersource.com.au Mon Aug 3 23:44:54 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 03:44:54 GMT Subject: Is python buffer overflow proof? References: Message-ID: On Mon, 03 Aug 2009 14:04:53 -0700, sturlamolden wrote: > On 2 Aug, 15:50, Jizzai wrote: > >> Is a _pure_ python program buffer overflow proof? >> >> For example in C++ you can declare a char[9] to hold user input. If the >> user inputs 10+ chars a buffer overflow occurs. > > Short answer: NO > > Bounds checking on sequence types is a protection against buffer > overflow, but is certainly not sufficient. > > The Python interpreter is written in C. Python extension modules are > written in C (or something similar). If you find an unprotected buffer > in this C code, you can possibly overflow this buffer. How are C extension modules "_pure_ python"? -- Steven From thangappan143 at gmail.com Mon Aug 3 23:45:47 2009 From: thangappan143 at gmail.com (Thangappan.M) Date: Tue, 4 Aug 2009 09:15:47 +0530 Subject: Problem in installing PyGreSQL Message-ID: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> Dear all, I want to access the database related stuffs in python.So I found the PyGreSQL module in net. Then I tried to download the module.But I am not able to download it. I am not a super user. I am using Linux debian machine Python version is 2.4.4 -- Regards, Thangappan.M -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at REMOVE.THIS.cybersource.com.au Tue Aug 4 00:06:15 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 04:06:15 GMT Subject: kw param question References: Message-ID: On Mon, 03 Aug 2009 19:59:23 +0000, kj wrote: > I want to write a decorator that, among other things, returns a function > that has one additional keyword parameter, say foo=None. > > When I try > > def my_decorator(f): > # blah, blah > def wrapper(*p, foo=None, **kw): > x = f(*p, **kw) > if (foo): > # blah, blah > else > # blah blah > return wrapper > > ...i get a syntax error where it says "foo=None". I get similar errors > with everything else I've tried. > > Is is possible to do this in Python? Have you tried this under Python 2.6 or 3.0? I've run into similar issues, because you can't have keyword-only arguments in Python 2.5 :( My solution was to create a decorator that faked them. The docstring is longer than the decorator itself. from functools import wraps def keywords(**defaults): """Return a decorator which decorates a function to accept keyword arguments. Python 2.5 and earlier don't allow keyword-only arguments for non-builtin functions. The obvious syntax: def func(x, *args, key=None, word='parrot'): is not permitted. As a work-around, write your function something like the following example: >>> @keywords(key=None, word='parrot') ... def func(x, y=0, *args, **kwargs): ... # Inside the function, we can guarantee that kwargs['key'] and ... # kwargs['word'] both exist, and no other keys. ... print "x=%s, y=%s, args=%s" % (x, y, args) ... if kwargs['key'] is None: msg = "kwargs['key'] is None" ... else: msg = "kwargs['key'] is something else" ... msg += " and kwargs['word'] is %r" % kwargs['word'] ... print msg ... When you call func, if you don't provide a keyword-only argument, the default will be substituted: >>> func(1, 2, 3, 4) x=1, y=2, args=(3, 4) kwargs['key'] is None and kwargs['word'] is 'parrot' >>> func(1) x=1, y=0, args=() kwargs['key'] is None and kwargs['word'] is 'parrot' Naturally you can provide your own values for keyword-only arguments: >>> func(1, 2, 3, word='spam') x=1, y=2, args=(3,) kwargs['key'] is None and kwargs['word'] is 'spam' >>> func(1, 2, 3, word='spam', key=len) x=1, y=2, args=(3,) kwargs['key'] is something else and kwargs['word'] is 'spam' If you pass an unexpected keyword argument, TypeError is raised: >>> #doctest:+IGNORE_EXCEPTION_DETAIL ... func(1, 2, 3, 4, keyword='something') Traceback (most recent call last): ... TypeError: ... """ def decorator(func): """Decorate func to allow keyword-only arguments.""" @wraps(func) def f(*args, **kwargs): for key in kwargs: if key not in defaults: raise TypeError( "'%s' is an invalid keyword argument for " \ "this function" % key ) d = defaults.copy() d.update(kwargs) return func(*args, **d) return f return decorator (Copy and pasted from working code, but I make no guarantee that it will have survived the process in working order!) -- Steven From rt8396 at gmail.com Tue Aug 4 00:08:52 2009 From: rt8396 at gmail.com (r) Date: Mon, 3 Aug 2009 21:08:52 -0700 (PDT) Subject: Announcing PythonTurtle References: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> <1d144bd0-8829-4449-8935-60bf6f66a5d6@l5g2000pra.googlegroups.com> Message-ID: <02ad1097-bf09-4980-8d1d-18cdbf50cb5a@24g2000yqm.googlegroups.com> On Aug 3, 8:53?pm, Asun Friere wrote: > On Aug 4, 6:35?am, r wrote: > > [snip] > > > > > I can remember the first time i used turtle (in python stdlib) and i > > kept saying to myself... > > > ? ? "Were the heck is this damn turtle?!?!" (>_<) > > > :-) > > In Python2.6, try this: > > > > >>> turtle.shape('turtle') Thanks Asun, now i don't have anything to complain about! :-# From koranthala at gmail.com Tue Aug 4 00:09:05 2009 From: koranthala at gmail.com (koranthala) Date: Mon, 3 Aug 2009 21:09:05 -0700 (PDT) Subject: Which GUI framework to use? Message-ID: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> Hi, I am creating a very minimal application (a networking app). I have written the application using Twisted. Now, I need to put a GUI wrapper on the application. The application needs a login screen and also it needs to be minimized to system tray. If I right click the image on system tray, I should be able to close it. It uses some legacy code, so the whole app is written in Python 2.4. Also, my company requires that I use permissive licenses (no GPL - MIT, BSD, LGPL etc ok) Which GUI framework is best for this? I tried using Tkinter, but it does not support minimize to system tray (or I couldnt find it). This is my first foray to GUI programming, so other issues that I am worried about - 1. GUI needs a loop, Twisted needs a loop. How can both go ahead without messing each other? Thank You very much K From jjposner at optimum.net Tue Aug 4 00:12:34 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 04 Aug 2009 00:12:34 -0400 Subject: Announcing PythonTurtle In-Reply-To: References: Message-ID: <4A77B532.5020906@optimum.net> > ... I would also venture to say a key-map > of sorts that is available thru the help menu where one could push an > "Up" button, or a "rotate" button, and have the proper command > inserted in the prompt, and then have the command execute, may also > help make the connections here, a sort of *real* Visual Basic > programming -- sorry Microsoft :P > Along these lines, see my "ClixTur" application at www.jjposner.net. It's a point-and-click front end to the standard Python turtle module, implementing only a very small subset of the turtle commands. As you click, the "real turtle commands" appear in a transcript window. You can then save (and maybe edit) and replay the transcript. Ram, I like a lot of what you've done. Could you talk about your decision to embed the standard turtle module (which is implemented in Tkinter) in a wxPython application? -John From philip at semanchuk.com Tue Aug 4 00:34:10 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 4 Aug 2009 00:34:10 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> Message-ID: <4B1B10B5-24D5-44D0-B16F-6308D8D8FAD2@semanchuk.com> On Aug 3, 2009, at 11:45 PM, Thangappan.M wrote: > Dear all, > > I want to access the database related stuffs in python.So I found the > PyGreSQL module in net. > Then I tried to download the module.But I am not able to download it. > > I am not a super user. > I am using Linux debian machine > Python version is 2.4.4 Hi Thangappan, If you want us to be able to help you, you'll need to give more information. For instance, why are you not able to download PyGreSQL? You might want to try psycopg2 which also gives you access to PostgreSQL from Python. You can download it from this site: http://initd.org/ Hope this helps Philip From http Tue Aug 4 00:34:15 2009 From: http (Paul Rubin) Date: 03 Aug 2009 21:34:15 -0700 Subject: Is python buffer overflow proof? References: Message-ID: <7x1vnsmc3c.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > The Python interpreter is written in C. Python extension modules are > > written in C (or something similar). If you find an unprotected buffer > > in this C code, you can possibly overflow this buffer. > > How are C extension modules "_pure_ python"? A lot of basic Python constructs (like numbers and dictionaries) are implemented as C extension modules. It is reasonable to consider "pure Python" to include the contents of the Python standard library. From david.lyon at preisshare.net Tue Aug 4 00:42:25 2009 From: david.lyon at preisshare.net (David Lyon) Date: Tue, 04 Aug 2009 00:42:25 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> Message-ID: <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> On Tue, 4 Aug 2009 09:15:47 +0530, "Thangappan.M" wrote: > I want to access the database related stuffs in python.So I found the > PyGreSQL module in net. > Then I tried to download the module.But I am not able to download it. Did none of the links here work? http://www.pygresql.org/readme.html#where-to-get > I am not a super user. > I am using Linux debian machine > Python version is 2.4.4 Try building it from source. Otherwise try getting it from pypi http://pypi.python.org/pypi/PyGreSQL/ David From nagle at animats.com Tue Aug 4 01:06:06 2009 From: nagle at animats.com (John Nagle) Date: Mon, 03 Aug 2009 22:06:06 -0700 Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: <4a77c0d9$0$1584$742ec2ed@news.sonic.net> Gabriel Genellina wrote: > En Mon, 03 Aug 2009 18:04:53 -0300, sturlamolden > escribi?: > >> On 2 Aug, 15:50, Jizzai wrote: >> >>> Is a _pure_ python program buffer overflow proof? >>> >>> For example in C++ you can declare a char[9] to hold user input. >>> If the user inputs 10+ chars a buffer overflow occurs. >> >> Short answer: NO > I disagree. You've just translated the responsability to check for > buffer overflows, from the Python VM, to the Java VM or the .Net runtime > (and all three suffered from buffer overruns and other problems in some > way or another). A more useful question is whether the standard libraries are being run through any of the commercial static checkers for possible buffer overflows. John Nagle From wuwei23 at gmail.com Tue Aug 4 01:33:33 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Aug 2009 22:33:33 -0700 (PDT) Subject: no-clobber dicts? References: Message-ID: Steven D'Aprano wrote: > I also have a series of unit tests for it if you're interested in them. That's several times today that kj has asked a question and you've responded with ready-to-go code. If this was Stackoverflow, I'd accuse you of reputation-whoring... You _can_ just post your cool code without the double act, y'know! :) From david.lyon at preisshare.net Tue Aug 4 01:55:20 2009 From: david.lyon at preisshare.net (David Lyon) Date: Tue, 04 Aug 2009 01:55:20 -0400 Subject: Python docs disappointing - group effort to hire =?UTF-8?Q?writers=3F?= In-Reply-To: <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> References: <09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com> <109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com> <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> Message-ID: It isn't totally about the writers... Peoples egos are also at stake - it seems. If "Fred X wrote Doc Y".. they don't want their name taken off.. So they generally speaking don't want the docs changed. If you talk too much about docs.. you can be told you're OT.. even in a thread about docs... On Fri, 31 Jul 2009 17:12:43 -0700, Kee Nethery wrote: > I too find the Python docs not very useful and it really slows down my > learning curve. > > I wonder if it would make sense to find good tech writers, get a > quotes, and get some professionally written documentation WITH LOTS OF > EXAMPLES added to the standard Python documentation tree. > > I'd chip in money for that task. I've certainly spent enough buying > Python books to where it would be very reasonable to chip in the cost > of one book towards this project. Get enough people ... could be a > great thing. > > Even though it is not the version I use, I would suggest that the > really detailed docs with lots of examples be written against the > latest python version. > > Just a thought. > > Kee Nethery From steven at REMOVE.THIS.cybersource.com.au Tue Aug 4 02:09:52 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 06:09:52 GMT Subject: Is python buffer overflow proof? References: <7x1vnsmc3c.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 03 Aug 2009 21:34:15 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> > The Python interpreter is written in C. Python extension modules are >> > written in C (or something similar). If you find an unprotected >> > buffer in this C code, you can possibly overflow this buffer. >> >> How are C extension modules "_pure_ python"? > > A lot of basic Python constructs (like numbers and dictionaries) are > implemented as C extension modules. It is reasonable to consider "pure > Python" to include the contents of the Python standard library. Well, yes, but we're not saying that Python is bug-free. There could be bugs in the Python VM for that matter. The point is that code you write yourself can rely on "pure Python" to be free of buffer-overflows (for some definition of "rely") rather than having to worry about managing memory yourself. If you do this: buffer = [0]*1024 buffer[:] = [1]*1025 you don't over-write some random piece of memory, the list object resizes to accommodate, or fails with an exception instead. No special action is needed to avoid buffer overflows. You can't make that claim about C extensions. It's interesting to contrast that with DoS vulnerabilities in pure Python code. Python won't stop you from trying to calculate a googolplex: googol = 10**100 googolplex = 10**googol and doing so will be a moderately effective denial of service against your Python application. If you're concerned with that, you need to code defensively in the Python layer. Protecting against time-consuming operations is not part of Python's design. -- Steven From wuwei23 at gmail.com Tue Aug 4 02:21:20 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Aug 2009 23:21:20 -0700 (PDT) Subject: Python docs disappointing - group effort to hire writers? References: <09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com> <109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com> <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> Message-ID: <95ea30c4-a5e5-458e-a8e4-4398c376e52d@13g2000prl.googlegroups.com> On Aug 4, 3:55?pm, David Lyon wrote: > It isn't totally about the writers... > Peoples egos are also at stake - it seems. Citation please. > If "Fred X wrote Doc Y".. they don't want their name taken off.. So > they generally speaking don't want the docs changed. Ditto. > If you talk too much about docs.. you can be told you're OT.. > even in a thread about docs... And again. All I've _ever_ seen (on this group at least) is the much repeated phrase "All patches to the docs are welcomed". If you'd like to cast aspersions on the characters of those doing the work over actually contributing yourself, you're certainly free to do so, just don't expect your claims to be taken seriously. Other people's refusal to do the work that _you_ consider to be necessary isn't "ego". From deets at nospam.web.de Tue Aug 4 02:48:31 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 04 Aug 2009 08:48:31 +0200 Subject: Which GUI framework to use? In-Reply-To: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> References: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> Message-ID: <7dq3tvF2d74reU1@mid.uni-berlin.de> koranthala schrieb: > Hi, > I am creating a very minimal application (a networking app). > I have written the application using Twisted. > Now, I need to put a GUI wrapper on the application. > The application needs a login screen and also it needs to be > minimized to system tray. If I right click the image on system tray, I > should be able to close it. > It uses some legacy code, so the whole app is written in Python > 2.4. Also, my company requires that I use permissive licenses (no GPL > - MIT, BSD, LGPL etc ok) Google this group. The discussions are abundant about this. Keep in mind that while Qt changed licenses to LGPL, PyQt didn't and thus you can't use it. > Which GUI framework is best for this? I tried using Tkinter, but it > does not support minimize to system tray (or I couldnt find it). > > This is my first foray to GUI programming, so other issues that I > am worried about - > 1. GUI needs a loop, Twisted needs a loop. How can both go ahead > without messing each other? Google is your friend here, too: http://twistedmatrix.com/projects/core/documentation/howto/choosing-reactor.html Diez From contact at xavierho.com Tue Aug 4 02:59:50 2009 From: contact at xavierho.com (Xavier Ho) Date: Tue, 4 Aug 2009 16:59:50 +1000 Subject: Seeding the rand() Generator In-Reply-To: References: <0b7c702f-5775-418e-8fc5-2f9df7487867@c2g2000yqi.googlegroups.com> Message-ID: <2d56febf0908032359k4d3abf63i97bb4883a75b2a15@mail.gmail.com> On Tue, Aug 4, 2009 at 5:48 PM, Fred Atkinson wrote: > I tried using the same command I used when I did this in PHP. > That command was: mt_srand(date("w")) > > It was a PHP command that seeds the MySQL random function, > according to the folks on the PHP newsgroup. Well, some people have suggested to use that inside Python. That would work, right? Although, if you're just trying to find the Python-equivalent, fair enough. Regards, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From torppa at staff.megabaud.fi Tue Aug 4 03:12:30 2009 From: torppa at staff.megabaud.fi (Jarkko Torppa) Date: Tue, 04 Aug 2009 07:12:30 GMT Subject: Seeding the rand() Generator References: <0b7c702f-5775-418e-8fc5-2f9df7487867@c2g2000yqi.googlegroups.com> Message-ID: On 2009-08-04, Fred Atkinson wrote: > On Mon, 3 Aug 2009 20:00:08 -0700 (PDT), Carl Banks > wrote: >> >>If you don't "get" why this is a MySQL question and not a Python >>question, then you need to learn more about what you are doing. > > I wouldn't agree. > > I tried using the same command I used when I did this in PHP. > That command was: mt_srand(date("w")) > > It was a PHP command that seeds the MySQL random function, > according to the folks on the PHP newsgroup. It seems that they lied to you. Did you actually try that ? > I'm trying to figure out what the Python equivalent of that > is. Python equivalent of that is random.seed(x), if PHP docs are to be believed. > Now do you see? What you acutally want is "select *,rand(3) as rand from table order by rand" or something like that. That 3 is the seed in there. -- Jarkko Torppa From news123 at free.fr Tue Aug 4 03:24:57 2009 From: news123 at free.fr (News123) Date: Tue, 04 Aug 2009 09:24:57 +0200 Subject: merge two png pic In-Reply-To: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> References: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> Message-ID: <4a77e249$0$2449$426a74cc@news.free.fr> Hi, cocobear wrote: >> > >> Map = Image.new("RGB", (x,y)) >> > >> Map.paste(im, box) >> > >> Map.paste(im1,box) > >> > >> Map = Map.convert("L", optimize=True, palette=Image.ADAPTIVE) > >> > >> But if thetwopngpicis too big , or if I have tomergemorepic >> > >> together, I will get MemoryError: > >>>>> > >> >>> Image.new("RGB",(44544,38656)) >> >> What do you want to do with such a big image? You will run into the same >> limitation when you are trying to display it. >> > > I want to download a map from google map with high precision > For me it sounds strange to handle such big files. Is the map you download from Google really that big? Mostly Google maps uses normally tiles of sizes 256x256 pixel, wich you have to compose to get the big image. If your problem is to combine tiles with different palettes, then you should pobably look at a way to 'unify' the palette of all tiles befor combining them. Being no expert of PIL I don't know whether this is easily possible though? bye N From contact at xavierho.com Tue Aug 4 03:31:29 2009 From: contact at xavierho.com (Xavier Ho) Date: Tue, 4 Aug 2009 17:31:29 +1000 Subject: merge two png pic In-Reply-To: <4a77e249$0$2449$426a74cc@news.free.fr> References: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> <4a77e249$0$2449$426a74cc@news.free.fr> Message-ID: <2d56febf0908040031j2aabe2f8xa5c69be943030783@mail.gmail.com> Strange, I did reply but you didn't see it? >>>>> > >> >>> Image.new("RGB",(44544,38656)) > >> > >> What do you want to do with such a big image? You will run into the same > >> limitation when you are trying to display it. > >> > > > > I want to download a map from google map with high precision > Download several maps instead. Streaming if you have to. I'm not sure how you're going to avoid that MemoryError by trying to aggregate everything at once. Might have to make it a dynamic loader, and only load pictures as relevant (i.e: visible, and next to visible) Think how Google Maps do it. They can't possibly upload 5GB of pictures every time you access Maps - that wouldn't have worked. They work with the only visible areas. If you could tell us exactly what your program is trying to achieve, maybe we'll have a better solution for you. Best regards, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From lkrzysiak at gmail.com Tue Aug 4 03:33:49 2009 From: lkrzysiak at gmail.com (=?UTF-8?Q?=C5=81ukasz?=) Date: Tue, 4 Aug 2009 00:33:49 -0700 (PDT) Subject: Strange python script behaviour Message-ID: Hi, I have a problem with one of my python scripts. When I run this script from command line it works correctly, but if I set up cron to run this script on specified hour it works for a while and then "[Errno 32] Broken pipe" error occures (always). The strangest thing is that if I change command in CRON from python /home/xxx/script.py to python /home/xxx/script.py > /tmp/script.log 2>&1 the script always works correctly!!! The question is WHY? Any ideas? From electronixtar at gmail.com Tue Aug 4 03:38:27 2009 From: electronixtar at gmail.com (est) Date: Tue, 4 Aug 2009 00:38:27 -0700 (PDT) Subject: modify a exe's RT_ACCELERATOR table using pefile module Message-ID: Hi list, I need to modify a exe's RT_ACCELERATOR table, rename F1 to Ctrl+F1, and assign hotkey F1 to another function Is there a way to do it with pefile/python? A sample code is appreciated. Thanks! From ram.rachum at gmail.com Tue Aug 4 03:44:59 2009 From: ram.rachum at gmail.com (cool-RR) Date: Tue, 4 Aug 2009 00:44:59 -0700 (PDT) Subject: Announcing PythonTurtle References: Message-ID: <9e3b0c86-3a2a-4bc4-91f3-1b01a05d6b86@f37g2000yqn.googlegroups.com> On Aug 4, 7:12?am, John Posner wrote: > > ... I would also venture to say a key-map > > of sorts that is available thru the help menu where one could push an > > "Up" button, or a "rotate" button, and have the proper command > > inserted in the prompt, and then have the command execute, may also > > help make the connections here, a sort of *real* Visual Basic > > programming -- sorry Microsoft :P > > Along these lines, see my "ClixTur" application atwww.jjposner.net. > It's a point-and-click front end to the standard Python turtle module, > implementing only a very small subset of the turtle commands. As you > click, the "real turtle commands" appear in a transcript window. You can > then save (and maybe edit) and replay the transcript. > > Ram, I like a lot of what you've done. Could you talk about your > decision to embed the standard turtle module (which is implemented in > Tkinter) in a wxPython application? > > -John Certainly John- although I have not embedded the turtle module at all, I just wrote my own. This was actually quite a short process - What took the most time was developing the shell, which is a fork of PyShell. The original PyShell controls the same process it is run on, but my fork controls a different process (created by the multiprocessing package.) That took a lot of time. I actually created an independent package for it, called "shelltoprocess", which is a subfolder in PythonTurtle's source, so now anyone can use it for their own project. I am proud to say that this shell has some features that IDLE should envy. If you're asking WHY I put it in a wxPython application, the answer is pretty much what "r" said: To make it like any other "over the counter" Windows application, making people feel more comfortable with it. Also, not requiring them to install Python+packages, but just PythonTurtle. Ram. From fatkinson at mishmash.com Tue Aug 4 03:48:42 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Tue, 04 Aug 2009 00:48:42 -0700 Subject: Seeding the rand() Generator References: <0b7c702f-5775-418e-8fc5-2f9df7487867@c2g2000yqi.googlegroups.com> Message-ID: On Mon, 3 Aug 2009 20:00:08 -0700 (PDT), Carl Banks wrote: >Your question is a MySQL question, not a Python question. I don't >know off hand how to seed the RNG in MySQL, and, since this is a >Python group and not a MySQL group, I don't care to look it up. But >if you were able to produce the MySQL statement in PHP that does it >you shouldn't need to ask. > >If you don't "get" why this is a MySQL question and not a Python >question, then you need to learn more about what you are doing. I wouldn't agree. I tried using the same command I used when I did this in PHP. That command was: mt_srand(date("w")) It was a PHP command that seeds the MySQL random function, according to the folks on the PHP newsgroup. I'm trying to figure out what the Python equivalent of that is. Now do you see? Fred From http Tue Aug 4 03:56:05 2009 From: http (Paul Rubin) Date: 04 Aug 2009 00:56:05 -0700 Subject: Is python buffer overflow proof? References: <7x1vnsmc3c.fsf@ruckus.brouhaha.com> Message-ID: <7x4osoypuy.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > The point is that code you write yourself can rely on "pure Python" to be > free of buffer-overflows (for some definition of "rely") rather than > having to worry about managing memory yourself. Right. Basically the Python interpreter protects you reasonably well from silly errors. The interpreter hasn't had anywhere near the level of hardening required to claim to protect you from diabolically clever malicious code running in the same interpreter as your sensitive application. The Rexec/Bastion modules were basically swiss cheese. From loic.domaigne at googlemail.com Tue Aug 4 04:02:04 2009 From: loic.domaigne at googlemail.com (=?ISO-8859-1?Q?Lo=EFc_Domaign=E9?=) Date: Tue, 4 Aug 2009 01:02:04 -0700 (PDT) Subject: Strange python script behaviour References: Message-ID: Hi, > I have a problem with one of my python scripts. When I run this script > from command line it works correctly, but if I set up cron to run this > script on specified hour it works for a while and then "[Errno 32] > Broken pipe" error occures (always). > > The strangest thing is that if I change command in CRON > > from > python /home/xxx/script.py > to > python /home/xxx/script.py ?> /tmp/script.log 2>&1 > > the script always works correctly!!! > > The question is WHY? Any ideas? This is a cron issue, and has little with python to do. By default, cron will email the output produced by your script, unless you redirect. It does so by pipe to a "mail" program. Your error seems to indicate a problem with the latter (perhaps you don't have any "mail" program installed). HTH, Lo?c -- My Blog: http://www.domaigne.com/blog "To err is human, but to really foul things up you need a computer." -- Paul Ehrlich From anthra.norell at bluewin.ch Tue Aug 4 04:02:31 2009 From: anthra.norell at bluewin.ch (Anthra Norell) Date: Tue, 04 Aug 2009 10:02:31 +0200 Subject: Compiling regex inside function? In-Reply-To: References: Message-ID: <4A77EB17.2050308@bluewin.ch> alex23 wrote: > Anthra Norell wrote: > >> def entries (l): >> r = re.compile ('([0-9]+) entr(y|ies)') >> match = r.search (l) >> if match: return match.group (1) >> >> So the question is: does "r" get regex-compiled once at py-compile time >> or repeatedly at entries() run time? >> > The docs say: > The compiled versions of the most recent patterns passed to re.match > (), re.search() or re.compile() are cached, so programs that use only > a few regular expressions at a time needn?t worry about compiling > regular expressions. > > (But they don't say how few is 'only a few'...) > > If you're concerned about it, you could always set the compiled > pattern to a default value in the function's argspec, as that _is_ > only executed the once: > > def entries(line, regex = re.compile('([0-9]+) entr(y|ies)'): > match = regex.search(line) > ... > Excellent idea! Thank you all for the tips. Frederic From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 4 04:03:53 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 04 Aug 2009 10:03:53 +0200 Subject: Confessions of a Python fanboy In-Reply-To: <008eef29$0$9756$c3e8da3@news.astraweb.com> References: <008e82e8$0$9756$c3e8da3@news.astraweb.com> <4a72d7cf$0$25239$426a34cc@news.free.fr> <008eef29$0$9756$c3e8da3@news.astraweb.com> Message-ID: <4a77eb69$0$22600$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Fri, 31 Jul 2009 13:38:56 +0200, Bruno Desthuilliers wrote: > >>> On the other hand, we don't have to prefix names with @ and @@, >> Nope, we have to prefix them with 'self' or 'cls' (or even >> 'self.__class__'). > > Incorrect. Correct for all relevant cases, except this one: >>>> class K: > ... class_attribute = 'No @@ required.' > ... >>>> K().class_attribute > 'No @@ required.' Once again: Ruby's attributes are *private*, so you can't access an attribute (class or instance) from outside a method. IOW, the above example is irrelevant. (snip) > Disadvantages: your code is filled with line noise. It's an arbitrary > choice between @@ meaning instance attribute and @@ meaning class > attribute -- there's no logical reason for choosing one over the other, > so you have to memorise which is which. It's easy to get it wrong. So far that's something I have no difficulty living with. >>> and we >>> don't have the compiler trying to *guess* whether we're calling a >>> function or referring to a variable. >> Please re-read a bit more carefully - it's *all* method call. > > What did I misread from here? Nowhere - it's me that got it wrong here, sorry. (snip) >>> Somebody who knows more Ruby than me should try writing the Zen of >>> Ruby. Something like: >> (snip childish parody of Python Zen) >> >> Steven, is that any useful ? > > It made me feel good. Why ??? You don't like Ruby ? Fine, don't use it. Period. I can't see the point of all these pissing contests. > But seriously, while I admit that I have very little Ruby experience, and > so aren't in a great position to judge, it seems to me that Ruby doesn't > have anything like Python's over-riding design principles (the Zen). If > there is a design principle to Ruby, I can't see what it is. Fullfill the tastes of Matz ?-) (snip) >>> Although I'm sure Ruby has its good points. I'm not convinced anonymous >>> code blocks are one of them though. >> Ruby's code blocks come from Smalltalk, where they are an absolute >> necessity since message passing (which code blocks are part of) is the >> *only* builtin control flow in Smalltalk - so you just *need* this >> construction to provide branching and iterations. > > Just because Smalltalk had a particular (mis?)feature You can drop the 'mis' part IMHO. The point of code blocks in Smalltalk is that once you have something as powerful as the message+code blocks combo, you just don't need any other 'special form' for control flow. > doesn't mean that > other languages should copy it. Nope. But OTHO, Python is famous for all the features it copied from other languages !-) From spam.buster at web.de Tue Aug 4 04:08:23 2009 From: spam.buster at web.de (Lars Behrens) Date: Tue, 04 Aug 2009 10:08:23 +0200 Subject: Strange python script behaviour References: Message-ID: ?ukasz wrote: > The strangest thing is that if I change command in CRON > > from > python /home/xxx/script.py > to > python /home/xxx/script.py > /tmp/script.log 2>&1 > > the script always works correctly!!! > > The question is WHY? Any ideas? Seems to me that this is more of a shell thing... First of all, it is always a good idea to call applications with their full path from cronjobs: /usr/bin/python /home/xxx/script.py or whatever the output of your "which python" may be. How did you create the cronjob? Dependending on the editor you used, maybe there is a missing newline... -- Cheerz Lars From lkrzysiak at gmail.com Tue Aug 4 04:30:29 2009 From: lkrzysiak at gmail.com (=?UTF-8?Q?=C5=81ukasz?=) Date: Tue, 4 Aug 2009 01:30:29 -0700 (PDT) Subject: Strange python script behaviour References: Message-ID: <4cfffc2c-1923-4fc6-be0b-07ee4c4aae2b@h21g2000yqa.googlegroups.com> On 4 Sie, 10:02, Lo?c Domaign? wrote: > Hi, > > > I have a problem with one of my python scripts. When I run this script > > from command line it works correctly, but if I set up cron to run this > > script on specified hour it works for a while and then "[Errno 32] > > Broken pipe" error occures (always). > > > The strangest thing is that if I change command in CRON > > > from > > python /home/xxx/script.py > > to > > python /home/xxx/script.py ?> /tmp/script.log 2>&1 > > > the script always works correctly!!! > > > The question is WHY? Any ideas? > > This is a cron issue, and has little with python to do. > > By default, cron will email the output produced by your script, unless > you redirect. It does so by pipe to a "mail" program. Your error seems > to indicate a problem with the latter (perhaps you don't have any > "mail" program installed). > Hmm... interesting, but logical explanation. Cron has its weird issues. I guess I have to redirect outputs of all my scripts to /dev/ null in order to prevent them from this kind of error. Thanks for help :) From lkrzysiak at gmail.com Tue Aug 4 04:33:17 2009 From: lkrzysiak at gmail.com (=?UTF-8?Q?=C5=81ukasz?=) Date: Tue, 4 Aug 2009 01:33:17 -0700 (PDT) Subject: Strange python script behaviour References: Message-ID: <7e430558-f029-450e-bb06-2b273a7a2fe1@s31g2000yqs.googlegroups.com> On 4 Sie, 10:08, Lars Behrens wrote: > ?ukasz wrote: > > The strangest thing is that if I change command in CRON > > > from > > python /home/xxx/script.py > > to > > python /home/xxx/script.py ?> /tmp/script.log 2>&1 > > > the script always works correctly!!! > > > The question is WHY? Any ideas? > > Seems to me that this is more of a shell thing... > > First of all, it is always a good idea to call applications with their full > path from cronjobs: > > /usr/bin/python /home/xxx/script.py or whatever the output of your "which > python" may be. > > How did you create the cronjob? Dependending on the editor you used, maybe > there is a missing newline... > No, I've just simplified cron entries to not mess the example :) The key thing was redirecting stdin & stderr to file. But thanks anyway... :) From gagsl-py2 at yahoo.com.ar Tue Aug 4 04:48:15 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 04 Aug 2009 05:48:15 -0300 Subject: Is python buffer overflow proof? References: <4a77c0d9$0$1584$742ec2ed@news.sonic.net> Message-ID: En Tue, 04 Aug 2009 02:06:06 -0300, John Nagle escribi?: > Gabriel Genellina wrote: >> En Mon, 03 Aug 2009 18:04:53 -0300, sturlamolden >> escribi?: >> >>> On 2 Aug, 15:50, Jizzai wrote: >>> >>>> Is a _pure_ python program buffer overflow proof? >>>> For example in C++ you can declare a char[9] to hold user input. >>>> If the user inputs 10+ chars a buffer overflow occurs. > A more useful question is whether the standard libraries are being > run through any of the commercial static checkers for possible buffer > overflows. In the past the Python source code was checked with valgrind and some coverity tools; I don't know the current status. -- Gabriel Genellina From bartsmeets86 at gmail.com Tue Aug 4 04:52:20 2009 From: bartsmeets86 at gmail.com (Bart Smeets) Date: Tue, 4 Aug 2009 10:52:20 +0200 Subject: easy_install: unresolved external symbol In-Reply-To: References: <2119ee90908031339o71e19624qa815241b446d739d@mail.gmail.com> Message-ID: <2119ee90908040152k5a744f98l7d5bc7da755948a2@mail.gmail.com> I could ofcourse use cxfreeze's binary package. But bbfreeze is not available as a binary. I would love to get easy_install to work. But I have no idea what's going wrong here. 2009/8/4 Gabriel Genellina > En Mon, 03 Aug 2009 17:39:44 -0300, Bart Smeets > escribi?: > > I keep getting errors when trying to use easy_install to install bbfreeze >> or >> cxfreeze (same errors). >> This is the output: >> http://pastebin.com/m65ba474d >> > > Can't you use the binary packages? > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From loic.domaigne at googlemail.com Tue Aug 4 05:11:21 2009 From: loic.domaigne at googlemail.com (=?ISO-8859-1?Q?Lo=EFc_Domaign=E9?=) Date: Tue, 4 Aug 2009 02:11:21 -0700 (PDT) Subject: Strange python script behaviour References: <4cfffc2c-1923-4fc6-be0b-07ee4c4aae2b@h21g2000yqa.googlegroups.com> Message-ID: <328af145-daaa-4239-bb42-dbf0a379540e@f37g2000yqn.googlegroups.com> > > > I have a problem with one of my python scripts. When I run this script > > > from command line it works correctly, but if I set up cron to run this > > > script on specified hour it works for a while and then "[Errno 32] > > > Broken pipe" error occures (always). > > > > The strangest thing is that if I change command in CRON > > > > from > > > python /home/xxx/script.py > > > to > > > python /home/xxx/script.py ?> /tmp/script.log 2>&1 > > > > the script always works correctly!!! > > > > The question is WHY? Any ideas? > > > This is a cron issue, and has little with python to do. > > > By default, cron will email the output produced by your script, unless > > you redirect. It does so by pipe to a "mail" program. Your error seems > > to indicate a problem with the latter (perhaps you don't have any > > "mail" program installed). > > Hmm... interesting, but logical explanation. Cron has its weird > issues. I guess I have to redirect outputs of all my scripts to /dev/ > null in order to prevent them from this kind of error. You could also set the MAILTO variable to "". HTH, Lo?c -- My Blog: http://www.domaigne.com/blog "Hardware: The parts of a computer system that can be kicked." -- Jeff Pesis. From david.lyon at preisshare.net Tue Aug 4 05:12:07 2009 From: david.lyon at preisshare.net (David Lyon) Date: Tue, 04 Aug 2009 05:12:07 -0400 Subject: =?UTF-8?Q?easy=5Finstall=3A=20unresolved=20external=20symbol?= In-Reply-To: <2119ee90908040152k5a744f98l7d5bc7da755948a2@mail.gmail.com> References: <2119ee90908031339o71e19624qa815241b446d739d@mail.gmail.com> <2119ee90908040152k5a744f98l7d5bc7da755948a2@mail.gmail.com> Message-ID: <87f2eede5ce0f1391994db66153e3c96@preisshare.net> On Tue, 4 Aug 2009 10:52:20 +0200, Bart Smeets wrote: > I could ofcourse use cxfreeze's binary package. But bbfreeze is not > available as a binary. I would love to get easy_install to work. But I have > no idea what's going wrong here. What is going on is that setuptools does some very 'advanced' things. The best you can do is give the option to link to the ez_setup.py install script and let the users install it them themselves... David From steven at REMOVE.THIS.cybersource.com.au Tue Aug 4 05:28:50 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 09:28:50 GMT Subject: Confessions of a Python fanboy References: <008e82e8$0$9756$c3e8da3@news.astraweb.com> <4a72d7cf$0$25239$426a34cc@news.free.fr> <008eef29$0$9756$c3e8da3@news.astraweb.com> <4a77eb69$0$22600$426a74cc@news.free.fr> Message-ID: On Tue, 04 Aug 2009 10:03:53 +0200, Bruno Desthuilliers wrote: >> Disadvantages: your code is filled with line noise. It's an arbitrary >> choice between @@ meaning instance attribute and @@ meaning class >> attribute -- there's no logical reason for choosing one over the other, >> so you have to memorise which is which. It's easy to get it wrong. > > So far that's something I have no difficulty living with. I don't like arbitrary symbols. Most people don't -- that's why "line noise" is unpopular. It's hard to read, hard to write, hard to maintain, and hard to talk about. The more line-noise, the worse the language. Of course, *ultimately* every symbol is arbitrary. There's no reason why "2" should mean the integer two, or "list" should mean a sequence type, but some symbols have such a long history, or have some other connection (say, with human languages), that the arbitrariness is lost. For instance, "+" is the obvious, non-arbitrary choice for the addition operator in any programming language using Latin symbols, and probably any programming language on Earth. (Not the *only* choice, but the obvious one.) I have a similar dislike for decorator syntax, because "@" ("at" in English) has nothing to do with decorations. It's an arbitrary symbol. One might argue that "$" would have been a more logical choice, because we turn numerals into currency by decorating it with a $ sign. (At least in the US, Canada, Australia, and a few other countries.) I use decorators all the time, and they are a fantastic invention, but the arbitrariness of the @ syntax is a negative. Oh well, one negative out of a whole lot of positives isn't too bad. At least I only have to deal with *one* such arbitrary symbol that needs memorizing. There's no need to distinguish between @@function_decorator and @class_decorator (or should it be the other way around?). Similarly, Python's choice of syntax for attributes is consistent: object.attribute works for everything, whether object is a class, an instance, a module, and whether attribute is callable or not. You can even use it on ints, provided you are clever about it: >>> 42 .__class__ >>>> Somebody who knows more Ruby than me should try writing the Zen of >>>> Ruby. Something like: >>> (snip childish parody of Python Zen) >>> >>> Steven, is that any useful ? >> >> It made me feel good. > > Why ??? > > You don't like Ruby ? Fine, don't use it. Period. I can't see the point > of all these pissing contests. Criticism of a language is a pissing contest? Yeah, okay, I was a tad dismissive. I un-apologetically jump to strong impressions about languages based on minimal use -- but I'm also willing to change my mind. Ruby certainly looks to me like it has some nice features. Syntax that looks like Perl isn't one of them though. >> Just because Smalltalk had a particular (mis?)feature > > You can drop the 'mis' part IMHO. The point of code blocks in Smalltalk > is that once you have something as powerful as the message+code blocks > combo, you just don't need any other 'special form' for control flow. Well, maybe, but remember, programming languages are only partly for communication to the compiler. They also have the requirement to communicate with human programmers as well, and that's even more important, because (1) humans spent a lot more time working with code than compilers do; (2) human programmers charge much more money than compilers do; (3) and you can modify the compiler to suit human needs much more easily than you can modify programmers to suit the compiler's needs. So I'd ask, does Smalltalk's message passing model match the way human beings think? If not, then that's a good sign it might be a misfeature. >> doesn't mean that >> other languages should copy it. > > Nope. But OTHO, Python is famous for all the features it copied from > other languages !-) Absolutely! There's nothing wrong with copying *good* features :) -- Steven From gregor.lingl at aon.at Tue Aug 4 05:30:23 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 11:30:23 +0200 Subject: ANN: Python's turtle module: collection of examples + demoViewer Message-ID: <4a77ffb2$0$1552$91cee783@newsreader04.highway.telekom.at> Hi all, A few days ago I've created a repository of turtle graphics demos/applications, that use Python's new turtle module. You can find it at at google code: http://python-turtle-demo.googlecode.com There are two versions of the collection: one for use with Python 3.1 and one for use with Python 2.5 / 2.6. The latter contains a *** backport of version 1.1 of the turtle module *** *** (from Python 3.1) to Python 2.5 / 2.6 *** Among others it contains all the examples I have demonstrated at Pycon 2009 and at EuroPython 2009. Moreover it contains the demoViewer (which is also in the source distribution of CPython) that lets you select the examples via a menu, display their source code and execute them in parallel. If you are interested to amend some of these examples, add some explanatory material or contribute additional examples, please tell me so I could add you as a committer to the project. I'd be glad to expand the repository whith interesting examples and applications using the turtle module. If you have questions concerning the examples, feel free to ask here or ask me directly via my email-address. I hope this collection will prove to be useful. Best regards, Gregor P.S.: I tried to announce it at comp.lang.python.announce but for some unknown reason it was not accepted there From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 4 06:01:06 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 04 Aug 2009 12:01:06 +0200 Subject: Confessions of a Python fanboy In-Reply-To: References: <008e82e8$0$9756$c3e8da3@news.astraweb.com> <4a72d7cf$0$25239$426a34cc@news.free.fr> <008eef29$0$9756$c3e8da3@news.astraweb.com> <4a77eb69$0$22600$426a74cc@news.free.fr> Message-ID: <4a7806e2$0$438$426a34cc@news.free.fr> Steven D'Aprano a ?crit : > On Tue, 04 Aug 2009 10:03:53 +0200, Bruno Desthuilliers wrote: > >>> Disadvantages: your code is filled with line noise. It's an arbitrary >>> choice between @@ meaning instance attribute and @@ meaning class >>> attribute -- there's no logical reason for choosing one over the other, >>> so you have to memorise which is which. It's easy to get it wrong. >> So far that's something I have no difficulty living with. > > I don't like arbitrary symbols. Neither do I - when there are too many at least. But I can certainly live with a couple ones. Now the point wasn't about my personal tastes, but about the fact that this particular pair of "arbitrary symbols" was IMHO still usable - IOW, I wouldn't dismiss Ruby on this sole point. > Most people don't -- that's why "line > noise" is unpopular. It's hard to read, hard to write, hard to maintain, > and hard to talk about. The more line-noise, the worse the language. OTHO, too much verbosity is a pain too. Ever programmed in AppleScript ? "set the attribute XXX of object YYY of collection ZZZ to SomeValue"... Yuck. I bet you prefer "zzz[yyy].xxx = SomeValue" - which uses three arbitrary symbols. (snip) > Oh well, one negative out of > a whole lot of positives isn't too bad. Indeed. You could perhaps learn a bit more about Ruby's positives if you don't block on what you perceive (rightfully or not) as negative points ?-) (snip) >>>>> Somebody who knows more Ruby than me should try writing the Zen of >>>>> Ruby. Something like: >>>> (snip childish parody of Python Zen) >>>> >>>> Steven, is that any useful ? >>> It made me feel good. >> Why ??? >> >> You don't like Ruby ? Fine, don't use it. Period. I can't see the point >> of all these pissing contests. > > Criticism of a language is a pissing contest? Not necessarily. But: > Yeah, okay, I was a tad dismissive. I un-apologetically jump to strong > impressions about languages based on minimal use Possibly, yes. > -- but I'm also willing > to change my mind. Ruby certainly looks to me like it has some nice > features. Syntax that looks like Perl isn't one of them though. Not my cup of tea neither FWIW. But Ruby is nowhere near Perl in terms of "line noise". > >>> Just because Smalltalk had a particular (mis?)feature >> You can drop the 'mis' part IMHO. The point of code blocks in Smalltalk >> is that once you have something as powerful as the message+code blocks >> combo, you just don't need any other 'special form' for control flow. > > Well, maybe, but remember, programming languages are only partly for > communication to the compiler. They also have the requirement to > communicate with human programmers as well, and that's even more > important, because > > (1) humans spent a lot more time working with code than compilers do; > > (2) human programmers charge much more money than compilers do; > > (3) and you can modify the compiler to suit human needs much more easily > than you can modify programmers to suit the compiler's needs. > > So I'd ask, does Smalltalk's message passing model match the way human > beings think? Does all human beings think the same way ? And aren't human beings able to learn new ways ? Smalltalk's only control flow construct might seem a bit weird at first when all you've been exposed to so far are more "traditional" special constructs, but it's not hard to learn and is way more uniform and flexible than having special constructs for each and any possible situation. One could ask if functional programming or OO "matches the way human beings think". From experience, some of us just find FP and / or OO just obvious, and some won't never get it. FWIW, there are quite a few features and idioms in Python that I _now_ find readable and obvious, but that would have puzzled me ten years ago. This reminds me of a shop where the CTO had forbidden using any OO feature of the main language used there because "nobody would understand it" (needless to say, I only stayed there a couple weeks...). > >>> doesn't mean that >>> other languages should copy it. >> Nope. But OTHO, Python is famous for all the features it copied from >> other languages !-) > > Absolutely! There's nothing wrong with copying *good* features :) Well... at least when they make sense and integrate smoothly into the target language. From masklinn at masklinn.net Tue Aug 4 06:15:19 2009 From: masklinn at masklinn.net (Masklinn) Date: Tue, 4 Aug 2009 12:15:19 +0200 Subject: Help understanding the decisions *behind* python? In-Reply-To: <4a7715ff$0$1641$742ec2ed@news.sonic.net> References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> <4a7715ff$0$1641$742ec2ed@news.sonic.net> Message-ID: <80C5CBFA-5547-4675-B60E-033C5C60DEDB@masklinn.net> On 3 Aug 2009, at 18:57 , John Nagle wrote: > Dave Angel wrote: >> sturlamolden wrote: >>> On 20 Jul, 18:27, Phillip B Oldham wrote: >>> Tuples are used for passing arguments to and from a function. Common >>> use of tuples include multiple return values and optional arguments >>> (*args). > > That's from Mesa, the Xerox PARC language of the 1970s. > > Mesa used tuples for subroutine arguments in a very straightforward > way. Every function took one tuple as an argument, written as > parameters > in parentheses separated by commas. Most statically typed functional languages seem to do pretty much the same: uncurried functions really take a tuple as single argument rather than multiple arguments, using pattern matching to make it look like multiple arguments. Then again, most of them seem to default to curried functions these days, which is nice. From masklinn at masklinn.net Tue Aug 4 06:21:01 2009 From: masklinn at masklinn.net (Masklinn) Date: Tue, 4 Aug 2009 12:21:01 +0200 Subject: Confessions of a Python fanboy In-Reply-To: References: <008e82e8$0$9756$c3e8da3@news.astraweb.com> <4a72d7cf$0$25239$426a34cc@news.free.fr> <008eef29$0$9756$c3e8da3@news.astraweb.com> <4a77eb69$0$22600$426a74cc@news.free.fr> Message-ID: <6FE460F1-7484-4234-9D41-72AAE26AB06E@masklinn.net> On 4 Aug 2009, at 11:28 , Steven D'Aprano wrote: > So I'd ask, does Smalltalk's message passing model match the way human > beings think? Yes. From yinon.me at gmail.com Tue Aug 4 06:30:52 2009 From: yinon.me at gmail.com (Yinon Ehrlich) Date: Tue, 4 Aug 2009 03:30:52 -0700 (PDT) Subject: Obtaining Python version References: <4a776184$0$1611$742ec2ed@news.sonic.net> Message-ID: <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> On Aug 4, 1:19?am, John Nagle wrote: > This works, but it seems too cute: > > ?>>> pyver = map(int,sys.version.split()[0].split('.')) > ?>>> print(pyver) > [2, 6, 1] > > Is it guaranteed that the Python version string will be in a form > suitable for that? ?In other words, does "sys.version" begin > > N.N.N other stuff > > in all versions, and will it stay that way? ?Are there ever > non-numeric versions, like "3.2.rc1"? > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle Hi, Easy way to test for Python version: if sys.hexversion >= 0x2060100: pass -- Yinon From koranthala at gmail.com Tue Aug 4 06:32:51 2009 From: koranthala at gmail.com (koranthala) Date: Tue, 4 Aug 2009 03:32:51 -0700 (PDT) Subject: Which GUI framework to use? References: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> <7dq3tvF2d74reU1@mid.uni-berlin.de> Message-ID: On Aug 4, 11:48?am, "Diez B. Roggisch" wrote: > koranthala schrieb: > > > Hi, > > ? ?I am creating a very minimal application (a networking app). > > ? ?I have written the application using Twisted. > > ? ?Now, I need to put a GUI wrapper on the application. > > ? ?The application needs a login screen and also it needs to be > > minimized to system tray. If I right click the image on system tray, I > > should be able to close it. > > ? ?It uses some legacy code, so the whole app is written in Python > > 2.4. Also, my company requires that I use permissive licenses (no GPL > > - MIT, BSD, LGPL etc ok) > > Google this group. The discussions are abundant about this. Keep in mind > that while Qt changed licenses to LGPL, PyQt didn't and thus you can't > use it. > > > ? ?Which GUI framework is best for this? I tried using Tkinter, but it > > does not support minimize to system tray (or I couldnt find it). > > > ? ?This is my first foray to GUI programming, so other issues that I > > am worried about - > > ? ?1. GUI needs a loop, Twisted needs a loop. How can both go ahead > > without messing each other? > > Google is your friend here, too: > > http://twistedmatrix.com/projects/core/documentation/howto/choosing-r... > > Diez Sorry about it. I should have done the homework better. From lists at cheimes.de Tue Aug 4 06:58:03 2009 From: lists at cheimes.de (Christian Heimes) Date: Tue, 04 Aug 2009 12:58:03 +0200 Subject: Is python buffer overflow proof? In-Reply-To: <4a77c0d9$0$1584$742ec2ed@news.sonic.net> References: <4a77c0d9$0$1584$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > A more useful question is whether the standard libraries are being > run through any of the commercial static checkers for possible buffer > overflows. The CPython interpreter is constantly checked with http://www.coverity.com/. Although Python is used for critical stuff at large companies like Apple, Google and NASA, only a few critical bugs in the C code have been found in the last couple of years. From gregor.lingl at aon.at Tue Aug 4 07:19:48 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 13:19:48 +0200 Subject: Announcing PythonTurtle In-Reply-To: References: Message-ID: <4a781958$0$1552$91cee783@newsreader04.highway.telekom.at> cool-RR schrieb: > Hello, > > I wanted to announce that I have just released my little side project, > PythonTurtle. > Here is its website: > http://pythonturtle.com > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > You can read more about it and download it on the website. > > Ram. Hi Ram, that's indeed a nice starting point for kids to doing turtle graphics, although currently it seems to implement only a very small subset of Python's turtle module's capabilities, even less than those of the old turtle module (that shipped with Python upto 2.5). Moreover I have to complain that you decided to use different commands for the turtle's actions - go instead of forward, turn instead of left and right etc. First I think left and right are more intuitive than turn as they do not need negative angles as arguments, which might matter for young children. Also I cannot see the advantage of cammands like visible() or invisible() over showturtle() and hideturtle() But second even kids - when learning how to program - will arrive at a point where it's no more problem to use an editor like IDLE so they could easily switch to Python's turtle module. That would be even easier if they had not to learn a new command set. Moreover a learning environment like PythonTurtle needs something like an editor - at least a simple one - in order to create programs that can be run repeatedly. Coding, that's creating programs - not only issuing a sequence of cammands interactively. It would be certainly a good thing if one had a similar environment using Tkinter, preferably also as part of the standard distribution of Python accompanying the turtle module. I think it should not be that difficult to create a GUI of this sort combining IDLE's shell window, its editor and turtle.py. Alas, at the moment I'm too busy with some othr work to start a project like this. Perhaps someone else might be interested? I'd enjoy to join a team doing it. Finally I'd like to stress, that the aims of PythonTurtle and Python's turtle module are quite different - as one could grasp easily by trying out the collection of examples at python-turtle-demo.googlecode.com that I posted in another posting. Anyway they could very well complement one another in some more mature state of development. Best regards, Gregor From thorsten at thorstenkampe.de Tue Aug 4 07:23:12 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 4 Aug 2009 13:23:12 +0200 Subject: Is python buffer overflow proof? References: Message-ID: * Jizzai (Sun, 02 Aug 2009 13:50:14 GMT) > Is a _pure_ python program buffer overflow proof? You cannot create "your own" buffer overflow in Python as you can in C and C++ but your code could still be vulnerable if the underlying Python construct is written in C. See [1] for instance. Thorsten [1] http://www.gentoo.org/security/en/glsa/glsa-200610-07.xml From IDOL at il.ibm.com Tue Aug 4 07:25:17 2009 From: IDOL at il.ibm.com (Ido Levy) Date: Tue, 4 Aug 2009 14:25:17 +0300 Subject: How to fetch an XML file using an HTTPS query Message-ID: Hello All I am quite new to Python and I would appreciate your advice on the following issue. I am trying to fetch an XML file from a remote server using an HTTPS query. When testing the HTTPS query from the browser after I entered the URL I got a pop-up box asking me if I want to "save a file" or "open with". >From a Python script I tried using urllib but it fails. I validated that my Python release support https request by using the following code and a different URL: import urllib print urllib.urlopen('https://...').read() and got the expected result. When I tried the above code or the following one with the URL that should return an XML file import sys import urllib import urllib2 headers = {'User-Agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.12) Gecko/20050923 Firefox/1.0.7', 'Cookie': 'JSESSIONID=000000000000000000000000000:111111111;Path=/',} url = "https://..." req = urllib2.Request(url, None, headers) urlFH = urllib2.urlopen(req) headers = urlFH.info() page_content = urlFH.readlines() urlFH.close() for line in page_content: print 'line: %s' % line I got the following result in both cases: Invalid filter passed. Thanks in Advance Ido Levy -------------- next part -------------- An HTML attachment was scrubbed... URL: From sibtey.mehndi at genpact.com Tue Aug 4 07:31:42 2009 From: sibtey.mehndi at genpact.com (Mehndi, Sibtey) Date: Tue, 4 Aug 2009 04:31:42 -0700 Subject: how to create a Com object of Picalo Module Message-ID: <1A343A98C8DAE44A8D9D1BF310F90D5E0140E41E62@GCPWINGGN2EVS11.IND.CORP.AD> Hi I want to use the picalo module in to VB.NET so I have tried to create the COM object of picalo module but I am unable to create. Anyone can help me out to create the picalo com object. Thanks, Sibtey This e-mail (and any attachments), is confidential and may be privileged. It may be read, copied and used only by intended recipients. Unauthorized access to this e-mail (or attachments) and disclosure or copying of its contents or any action taken in reliance on it is unlawful. Unintended recipients must notify the sender immediately by e-mail/phone & delete it from their system without making any copies or disclosing it to a third person. -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Tue Aug 4 07:34:44 2009 From: contact at xavierho.com (Xavier Ho) Date: Tue, 4 Aug 2009 21:34:44 +1000 Subject: Obtaining Python version In-Reply-To: <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> Message-ID: <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> On Tue, Aug 4, 2009 at 8:30 PM, Yinon Ehrlich wrote: > Hi, > Easy way to test for Python version: > if sys.hexversion >= 0x2060100: > pass > Great suggestion. I just tested it on my newly installed Python 3.1 (as of 3.1r31) >>> import sys >>> "%X" % sys.hexversion '30100F0' That's genius - '301' for Python 3.1, and '00F0' is r31! I'm definitely going to use this more often in the future. Cheers, Xavier -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Tue Aug 4 07:37:11 2009 From: contact at xavierho.com (Xavier Ho) Date: Tue, 4 Aug 2009 21:37:11 +1000 Subject: Obtaining Python version In-Reply-To: <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> Message-ID: <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> On Tue, Aug 4, 2009 at 9:34 PM, Xavier Ho wrote: > ... and '00F0' is r31! > Actually, 00F0 is 576 in decimal. Maybe it's the subversion? Anyhow, it's still good! -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregor.lingl at aon.at Tue Aug 4 07:37:23 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 13:37:23 +0200 Subject: Announcing PythonTurtle In-Reply-To: <9e3b0c86-3a2a-4bc4-91f3-1b01a05d6b86@f37g2000yqn.googlegroups.com> References: <9e3b0c86-3a2a-4bc4-91f3-1b01a05d6b86@f37g2000yqn.googlegroups.com> Message-ID: <4a781d85$0$2311$91cee783@newsreader02.highway.telekom.at> cool-RR schrieb: > On Aug 4, 7:12 am, John Posner wrote: >>> ... I would also venture to say a key-map >>> ... > If you're asking WHY I put it in a wxPython application, the answer is > pretty much what "r" said: To make it like any other "over the > counter" Windows application, making people feel more comfortable with > it. > Also, not requiring them to install Python+packages, but just > PythonTurtle. Fortunately it's not necessary to install 'packages' to use Python's turtle module as it is one of it's 'batteries included'. And I think it's not so a bad idea to install Python if one want's to learn it, anyway. Regards, Gregor > > Ram. From cocobear.cn at gmail.com Tue Aug 4 08:01:47 2009 From: cocobear.cn at gmail.com (cocobear) Date: Tue, 4 Aug 2009 05:01:47 -0700 (PDT) Subject: merge two png pic References: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> <4a77e249$0$2449$426a74cc@news.free.fr> Message-ID: <72d7aad1-1fb7-4b32-a87f-636505b0faa2@v15g2000prn.googlegroups.com> On Aug 4, 3:24?pm, News123 wrote: > Hi, > > > > > > cocobear wrote: > >> > >> Map = Image.new("RGB", (x,y)) > >> > >> Map.paste(im, box) > >> > >> Map.paste(im1,box) > > >> > >> Map = Map.convert("L", optimize=True, palette=Image.ADAPTIVE) > > >> > >> But if thetwopngpicis too big , or if I have tomergemorepic > >> > >> together, I will get MemoryError: > > >>>>> > >> >>> Image.new("RGB",(44544,38656)) > > >> What do you want to do with such a big image? You will run into the same > >> limitation when you are trying to display it. > > > I want to download a map from google map with high precision > > For me it sounds strange to handle such big files. > > Is the map you download from Google really that big? > Mostly Google maps uses normally tiles of sizes 256x256 pixel, wich you > have to compose to get the ?big image. > The map I downloaded from Google is small(256x256). These small maps will compose a big image. > If your problem is to combine tiles with different palettes, then you > should pobably look at a way to ?'unify' the palette of all tiles befor > combining them. > I think it is impossible to 'unify' all this tiles. > Being no expert of PIL I don't know whether this is easily possible though? > > bye > > N From hendrik at microcorp.co.za Tue Aug 4 08:14:40 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 4 Aug 2009 14:14:40 +0200 Subject: Which GUI framework to use? In-Reply-To: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> References: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> Message-ID: <200908041414.41026.hendrik@microcorp.co.za> On Tuesday 04 August 2009 06:09:05 koranthala wrote: > Hi, > I am creating a very minimal application (a networking app). > I have written the application using Twisted. > Now, I need to put a GUI wrapper on the application. > The application needs a login screen and also it needs to be > minimized to system tray. If I right click the image on system tray, I > should be able to close it. > It uses some legacy code, so the whole app is written in Python > 2.4. Also, my company requires that I use permissive licenses (no GPL > - MIT, BSD, LGPL etc ok) > > Which GUI framework is best for this? I tried using Tkinter, but it > does not support minimize to system tray (or I couldnt find it). look at iconify, and at withdraw - Hendrik From ram.rachum at gmail.com Tue Aug 4 08:19:48 2009 From: ram.rachum at gmail.com (cool-RR) Date: Tue, 4 Aug 2009 05:19:48 -0700 (PDT) Subject: Announcing PythonTurtle References: <4a781958$0$1552$91cee783@newsreader04.highway.telekom.at> Message-ID: <766a3973-6960-4500-9c7c-88d5261b823c@24g2000yqm.googlegroups.com> > Hi Ram, > > that's indeed a nice starting point for kids to doing turtle graphics, > although currently it seems to implement only a very small subset of > Python's turtle module's capabilities, even less than those of the old > turtle module (that shipped with Python upto 2.5). > I agree - an undo feature for example would be nice and it's something I would like to do in a future version. Other than that though, I don't think having many turtle-functions is so important. I think the important thing is for the student to build complex things from simple building blocks. > Moreover I have to complain that you decided to use different commands > for the turtle's actions - go instead of forward, turn instead of left > and right etc. First I think left and right are more intuitive than turn > as they do not need negative angles as arguments, which might matter for > young children. Also I cannot see the advantage of cammands like > visible() or invisible() over showturtle() and hideturtle() > But second even kids - when learning how to program - will arrive at a > point where it's no more problem to use an editor like IDLE so they > could easily switch to Python's turtle module. That would be even easier > if they had not to learn a new command set. > Moreover a learning environment like PythonTurtle needs something like > an editor - at least a simple one - in order to create programs that can > be run repeatedly. Coding, that's creating programs - not only issuing > a sequence of cammands interactively. > A text editor would be a good feature for future versions. Regarding the naming of functions: I named them in the way that seemed best to me. You seem not to agree, you like the way your functions are named better, and there's little point in arguing over which convention is truly better. The convention I chose is the one that seemed ideal to me. I did consider naming the functions the same way you did for consistency, but I decided not to compromise the quality of PythonTurtle just to be compatible with a module that my users may not even use. > It would be certainly a good thing if one had a similar environment > using Tkinter, preferably also as part of the standard distribution of > Python accompanying the turtle module. I think it should not be that > difficult to create a GUI of this sort combining IDLE's shell window, > its editor and turtle.py. Alas, at the moment I'm too busy with some > othr work to start a project like this. Perhaps someone else might be > interested? I'd enjoy to join a team doing it. I agree that it shouldn't be difficult; The question is whether someone will step up and do it. > Finally I'd like to stress, that the aims of PythonTurtle and Python's > turtle module are quite different - as one could grasp easily by trying > out the collection of examples at python-turtle-demo.googlecode.com that > I posted in another posting. Anyway they could very well complement one > another in some more mature state of development. > > Best regards, > Gregor Thank you for your feedback Gregor. Ram Rachum. From thangappan143 at gmail.com Tue Aug 4 08:25:30 2009 From: thangappan143 at gmail.com (Thangappan.M) Date: Tue, 4 Aug 2009 17:55:30 +0530 Subject: Problem in Installing PyGreSQL Message-ID: <7aa29e790908040525p562245c8v95d5a5d875fe606f@mail.gmail.com> Dear all, While installing PyGreSQl module in my machine I got the error as pg_config command not found. I am not a super user. how can I install this pg_config tool. -- Regards, Thangappan.M -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Tue Aug 4 08:27:27 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 04 Aug 2009 07:27:27 -0500 Subject: Is python buffer overflow proof? In-Reply-To: References: <7dnissF2bthr0U1@mid.uni-berlin.de> Message-ID: <4A78292F.8040907@tim.thechases.com> Marcus Wanner wrote: > On 8/3/2009 3:45 AM, Diez B. Roggisch wrote: >> But you can cast the resulting pointer to an array of larger size, and >> there you are. > > Ah, that makes sense. I had forgotten about ctypes.cast(). You *can* shoot yourself in the foot with Python, you just have to aim much more carefully than you do with C/C++. -tkc From gregor.lingl at aon.at Tue Aug 4 08:45:47 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 14:45:47 +0200 Subject: Announcing PythonTurtle In-Reply-To: <766a3973-6960-4500-9c7c-88d5261b823c@24g2000yqm.googlegroups.com> References: <4a781958$0$1552$91cee783@newsreader04.highway.telekom.at> <766a3973-6960-4500-9c7c-88d5261b823c@24g2000yqm.googlegroups.com> Message-ID: <4a782d7b$0$1549$91cee783@newsreader04.highway.telekom.at> cool-RR schrieb: >> Hi Ram, >> >> that's indeed a nice starting point for kids to doing turtle graphics, >> although currently it seems to implement only a very small subset of >> Python's turtle module's capabilities, even less than those of the old >> turtle module (that shipped with Python upto 2.5). ... > A text editor would be a good feature for future versions. > Regarding the naming of functions: I named them in the way that seemed > best to me. You seem not to agree, you like the way your functions are > named better, and there's little point in arguing over which > convention is truly better. The convention I chose is the one that > seemed ideal to me. > I did consider naming the functions the same way you did for > consistency, but I decided not to compromise the quality of > PythonTurtle just to be compatible with a module that my users may not > even use. That's the advantage of not developing for the standard library. In fact those elementary commands you use were present already in the old turtle module. When I decided to extend the old turtle module a primary requirement was that it remains 100% compatible to the old one. New versions of a module in the standard library must not break code of previous users of that module. In short: I did not name these functions but I had to use the names that already were there. Nevertheless I'd prefer left and right over turn even today, especially for kids as I argued before. Regards, Gregor > >> It would be certainly a good thing if one had a similar environment >> using Tkinter, preferably also as part of the standard distribution of >> Python accompanying the turtle module. I think it should not be that >> difficult to create a GUI of this sort combining IDLE's shell window, >> its editor and turtle.py. Alas, at the moment I'm too busy with some >> othr work to start a project like this. Perhaps someone else might be >> interested? I'd enjoy to join a team doing it. > > I agree that it shouldn't be difficult; The question is whether > someone will step up and do it. > >> Finally I'd like to stress, that the aims of PythonTurtle and Python's >> turtle module are quite different - as one could grasp easily by trying >> out the collection of examples at python-turtle-demo.googlecode.com that >> I posted in another posting. Anyway they could very well complement one >> another in some more mature state of development. >> >> Best regards, >> Gregor > > Thank you for your feedback Gregor. > > Ram Rachum. From darcy at druid.net Tue Aug 4 08:48:56 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 Aug 2009 08:48:56 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> Message-ID: <20090804084856.b825967a.darcy@druid.net> On Tue, 04 Aug 2009 00:42:25 -0400 David Lyon wrote: > > Then I tried to download the module.But I am not able to download it. > > Did none of the links here work? > > http://www.pygresql.org/readme.html#where-to-get The RPM seems to be missing. I am currently trying to find one. I don't run Linux myself and sometimes forget to check that we have a working RPM. > > I am not a super user. > > I am using Linux debian machine > > Python version is 2.4.4 > > Try building it from source. That will work of course and it is a small enough package that it should build painlessly. There is a working setup.py. > Otherwise try getting it from pypi It is also missing the RPM. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From fatkinson at mishmash.com Tue Aug 4 08:58:46 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Tue, 04 Aug 2009 05:58:46 -0700 Subject: Seeding the rand() Generator References: <0b7c702f-5775-418e-8fc5-2f9df7487867@c2g2000yqi.googlegroups.com> Message-ID: <52cg759c3kg732ikns1emlgb5c3joom4md@4ax.com> On Tue, 04 Aug 2009 07:12:30 GMT, Jarkko Torppa wrote: >On 2009-08-04, Fred Atkinson wrote: >> On Mon, 3 Aug 2009 20:00:08 -0700 (PDT), Carl Banks >> wrote: >>> >>>If you don't "get" why this is a MySQL question and not a Python >>>question, then you need to learn more about what you are doing. >> >> I wouldn't agree. >> >> I tried using the same command I used when I did this in PHP. >> That command was: mt_srand(date("w")) >> >> It was a PHP command that seeds the MySQL random function, >> according to the folks on the PHP newsgroup. > >It seems that they lied to you. Did you actually try that ? > >> I'm trying to figure out what the Python equivalent of that >> is. > >Python equivalent of that is random.seed(x), if PHP docs are to be believed. > >> Now do you see? > >What you acutally want is "select *,rand(3) as rand from table >order by rand" or something like that. That 3 is the seed in there. Yes, I actually tried that and it worked. Things got much more random after I started using it. Regards, Fred From benjamin.kaplan at case.edu Tue Aug 4 09:03:55 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 4 Aug 2009 09:03:55 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: <20090804084856.b825967a.darcy@druid.net> References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> Message-ID: On Tue, Aug 4, 2009 at 8:48 AM, D'Arcy J.M. Cain wrote: > On Tue, 04 Aug 2009 00:42:25 -0400 > David Lyon wrote: >> > Then I tried to download the module.But I am not able to download it. >> >> Did none of the links here work? >> >> http://www.pygresql.org/readme.html#where-to-get > > The RPM seems to be missing. ?I am currently trying to find one. ?I > don't run Linux myself and sometimes forget to check that we have a > working RPM. > >> > I am not a super user. >> > I am using Linux debian machine >> > Python version is 2.4.4 >> >> Try building it from source. > > That will work of course and it is a small enough package that it > should build painlessly. ?There is a working setup.py. > >> Otherwise try getting it from pypi > > It is also missing the RPM. Doesn't matter here. Debians use DEBs (DEBian packages), not RPMs (for the Red Hat Package Manager). Either way, the OP can't install system level packages. That's what the comment about not being a super user meant. > > -- > D'Arcy J.M. Cain ? ? ? ? | ?Democracy is three wolves > http://www.druid.net/darcy/ ? ? ? ? ? ? ? ?| ?and a sheep voting on > +1 416 425 1212 ? ? (DoD#0082) ? ?(eNTP) ? | ?what's for dinner. > -- > http://mail.python.org/mailman/listinfo/python-list > From mydevforums at gmail.com Tue Aug 4 09:15:24 2009 From: mydevforums at gmail.com (IronyOfLife) Date: Tue, 4 Aug 2009 06:15:24 -0700 (PDT) Subject: Python configuration question when python scripts are executed using Appweb as web server. References: Message-ID: On Aug 3, 8:42?pm, "Gabriel Genellina" wrote: > En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife ? > escribi?: > > > I have installed python 2.6.2 in windows xp professional machine. I > > have set the following environment variables -- PYTHONPATH. It points > > to following windows folders: python root folder, the lib folder and > > lib-tk folder. > > Why? Did you read it somewhere? Usually there is no need to set the ? > PYTHONPATH variable at all; remove it. > > > I have configured IIS to execute python scripts. > > > I do not have any issues executing python scripts from the python > > interpreter window or from the browser using IIS as the web server. > > Try again after PYTHONPATH is removed, and make sure you can import all ? > the required modules from the Python console. Only then try to run the cgi ? > scripts. > > > However, when I use the open source Appweb web browser to execute > > python scripts. It is able to execute only simple script without > > issues. [...]However I am not able to execute python scripts that ? > > contain import > > statements. I need to point out here that i do not have issue with > > using os or sys packages. When I tried to execute the sample client > > script that came with the gnutls wrapper for python, I got error. I > > narrowed it down to the "from ... import" line in the example. > > > from gnutls.crypto import * > > from gnutls.connection import * > > Check that the above lines work fine from inside the Python console. > If not, something went wrong when you installed the gnutls Python package. > > > Next step, in order to debug, I used the module finder to see what is > > happening. To being with I used the module finder to find out the > > modules loaded for the simple script hello.py. > > Debugging cgi scripts isn't easy sometimes; try adding this line at the ? > start of your script: > > import cgitb;cgitb.enable() > > You should get a nicely formatted stack trace whenever an exception is ? > raised. If you get an HTTP error instead (like 500 Internal Server Error) ? > it's likely a syntax error, you must fix it before continuing. > Then, you may find that modulefinder is no more needed. > > > import pdb > > pdb.set_trace() > > pdb cannot work inside a CGI script; remove that. > > > Once again, let me stress that this issue is happening only when I use > > appweb as the web server. > > I don't know appweb, but if you first make sure the script works from the ? > command line, it should be much easier to make it work in the web server. > > -- > Gabriel Genellina Hi Gabriel Thanks for your reply. As I had mentioned in my original post, I am able to successfully execute gnutls client python script while using python interpreter and from the web browser while using IIS as web server. The scripts were not executing successfully only when I used AppWeb as web server. Setting PYTHONPATH environment variables is mentioned in Python docs. I figured out how to get the debug statements to write to Appweb logs and from there I found out the issue to be ImportError. Python does provide a very cryptic error message. "(, ImportError('DLL load failed: The specified module could not be found.',), )" I then downloaded filemon (as suggested in another forum) utility tool for windows environment. Using the tool I found that python.exe is trying to load gnutls related dlls from system path and a list of folders (I dont know why it didnt try to pick up the dlls from all the path provided in PATH environment variable) none of which contain the gnutls related dlls. I solved the issue temporarily by copying the gnutls related dlls to the path searched by python.exe Now my gnutls client python script executes successfully when i use Appweb as the web server, NOTE: When I use python interpreter or IIS as webserver the path where python.exe looks for gnutls related dll's are different. In this scenario python.exe is able to successfully load the required dlls. From davea at ieee.org Tue Aug 4 09:29:35 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 04 Aug 2009 09:29:35 -0400 Subject: Newbie Question regarding __init__() In-Reply-To: References: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> <01bcf8b8-687c-4bf4-acbb-b059a480d382@f33g2000vbm.googlegroups.com> <4A77A43D.4000709@ieee.org> Message-ID: <4A7837BF.6070903@ieee.org> Dennis Lee Bieber wrote: > On Mon, 03 Aug 2009 23:00:13 -0400, Dave Angel > declaimed the following in gmane.comp.python.general: > > >> To throw away the result of an expression in Python is even easier. >> Just don't use it. >> func1() and func2() >> is a valid expression whose result is not used. And func2()'s result is >> therefore irrelevant. But shortcircuiting means that func2() is only >> called if func1() returned False (or something equivalent to it, like 0 >> or an empty list) >> > > Backwards... > > When using "and", the RHS is only evaluated if the LHS evaluates to > TRUE (if the LHS is FALSE, why go further, since False and anything -> > False). > > Conversely, when using "or", the RHS is only evaluated if the LHS is > FALSE. > You're right of course. Slip of the keyboard. DaveA From nyamatongwe+thunder at gmail.com Tue Aug 4 09:32:55 2009 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 04 Aug 2009 13:32:55 GMT Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: Thorsten Kampe: > You cannot create "your own" buffer overflow in Python as you can in C > and C++ but your code could still be vulnerable if the underlying Python > construct is written in C. Python's standard library does now include unsafe constructs. import ctypes x = '1234' # Munging byte 1 OK ctypes.memset(x, 1, 1) print(x) # Next line writes beyond end of variable and crashes ctypes.memset(x, 1, 20000) print(x) Neil From philip at semanchuk.com Tue Aug 4 09:34:17 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 4 Aug 2009 09:34:17 -0400 Subject: Problem in Installing PyGreSQL In-Reply-To: <7aa29e790908040525p562245c8v95d5a5d875fe606f@mail.gmail.com> References: <7aa29e790908040525p562245c8v95d5a5d875fe606f@mail.gmail.com> Message-ID: On Aug 4, 2009, at 8:25 AM, Thangappan.M wrote: > Dear all, > > While installing PyGreSQl module in my machine I got the error as > pg_config > command not found. > I am not a super user. > how can I install this pg_config tool. Thangappan, pg_config is part of PostgreSQL. It reports various pieces of information about the Postgres installation, like the BINDIR, INCLUDEDIR, compile flags, version etc. If PostgreSQL is installed on your machine, then I'll bet that pg_config is also installed, but it isn't on your path so the PyGreSQl installer can't find it. When you're having trouble installing a specific package like PyGreSQl, you'll probably get better answers by posting your questions to a specific mailing list: http://mailman.vex.net/mailman/listinfo/pygresql By searching the archives you might even find that your question has been answered already. Good luck Philip From tycho at tycho.ws Tue Aug 4 09:41:30 2009 From: tycho at tycho.ws (Tycho Andersen) Date: Tue, 4 Aug 2009 08:41:30 -0500 Subject: How to fetch an XML file using an HTTPS query In-Reply-To: <49b3a7400908040638h46d4e4dcxe5cd4120e9c2c7a1@mail.gmail.com> References: <49b3a7400908040638h46d4e4dcxe5cd4120e9c2c7a1@mail.gmail.com> Message-ID: <49b3a7400908040641l5f5daaa8v374041b7fbac442a@mail.gmail.com> Blah, forgot to include the list. When is python-list going to get Reply-To? \t On Tue, Aug 4, 2009 at 8:38 AM, Tycho Andersen wrote: > Hi Ido, > > On Tue, Aug 4, 2009 at 6:25 AM, Ido Levy wrote: >> [snip] >> I got the following result in both cases: >> ? ? ? ? >> ? ? ? ? >> ? ? ? ? Invalid filter passed. >> ? ? ? ? > > To me, this doesn't look like a python problem: the application was > successfully connected to and returned a result. The problem you're > experiencing is that it wasn't the result you expected. Are you sure > you're setting the right headers, posting the right form values, etc. > and giving the app exactly what it wants? > > \t > From darcy at druid.net Tue Aug 4 09:53:40 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 Aug 2009 09:53:40 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> Message-ID: <20090804095340.67e2de0f.darcy@druid.net> On Tue, 4 Aug 2009 09:03:55 -0400 Benjamin Kaplan wrote: > Doesn't matter here. Debians use DEBs (DEBian packages), not RPMs (for > the Red Hat Package Manager). Either way, the OP can't install system > level packages. That's what the comment about not being a super user > meant. Urk! I thought that all the Linux distros used RPMs. Maybe I should just remove that link and let each distro provide their own package. As long as it was just one I could take some steps to make sure that I wasn't distributing malware but the more packages I supply that I can't personally test, the more uncomfortable I get. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From darcy at druid.net Tue Aug 4 09:55:47 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 Aug 2009 09:55:47 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> Message-ID: <20090804095547.a5274e22.darcy@druid.net> On Tue, 4 Aug 2009 09:03:55 -0400 Benjamin Kaplan wrote: > Doesn't matter here. Debians use DEBs (DEBian packages), not RPMs (for > the Red Hat Package Manager). Either way, the OP can't install system > level packages. That's what the comment about not being a super user > meant. By the way, you don't have to be super user to install PyGreSQL. You just need SU if you want to install it system wide. PyGreSQL doesn't require any special privileges to run. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From benjamin.kaplan at case.edu Tue Aug 4 10:02:23 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 4 Aug 2009 10:02:23 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: <20090804095547.a5274e22.darcy@druid.net> References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> <20090804095547.a5274e22.darcy@druid.net> Message-ID: On Tue, Aug 4, 2009 at 9:55 AM, D'Arcy J.M. Cain wrote: > On Tue, 4 Aug 2009 09:03:55 -0400 > Benjamin Kaplan wrote: >> Doesn't matter here. Debians use DEBs (DEBian packages), not RPMs (for >> the Red Hat Package Manager). Either way, the OP can't install system >> level packages. That's what the comment about not being a super user >> meant. > > By the way, you don't have to be super user to install PyGreSQL. ?You > just need SU if you want to install it system wide. ?PyGreSQL doesn't > require any special privileges to run. Right, but the packages install system-wide. That's why he could compile it himself but not use the package. > > -- > D'Arcy J.M. Cain ? ? ? ? | ?Democracy is three wolves > http://www.druid.net/darcy/ ? ? ? ? ? ? ? ?| ?and a sheep voting on > +1 416 425 1212 ? ? (DoD#0082) ? ?(eNTP) ? | ?what's for dinner. > -- > http://mail.python.org/mailman/listinfo/python-list > From darcy at druid.net Tue Aug 4 10:14:49 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 Aug 2009 10:14:49 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> <20090804095547.a5274e22.darcy@druid.net> Message-ID: <20090804101449.79cd4522.darcy@druid.net> On Tue, 4 Aug 2009 10:02:23 -0400 Benjamin Kaplan wrote: > > By the way, you don't have to be super user to install PyGreSQL. ?You > > just need SU if you want to install it system wide. ?PyGreSQL doesn't > > require any special privileges to run. > > Right, but the packages install system-wide. That's why he could > compile it himself but not use the package. Exactly so don't install the package. Do "python setup.py build" and put the three files that are built (_pg.so, pg.py and pgdb.py) into any directory and point PYTHONPATH to it. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From python at mrabarnett.plus.com Tue Aug 4 10:17:39 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Aug 2009 15:17:39 +0100 Subject: Obtaining Python version In-Reply-To: <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> Message-ID: <4A784303.2070804@mrabarnett.plus.com> Xavier Ho wrote: > On Tue, Aug 4, 2009 at 9:34 PM, Xavier Ho > wrote: > > ... > and '00F0' is r31! > > > Actually, 00F0 is 576 in decimal. Maybe it's the subversion? > 0x00F0 is 240. > Anyhow, it's still good! > From contact at xavierho.com Tue Aug 4 10:39:56 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 5 Aug 2009 00:39:56 +1000 Subject: Obtaining Python version In-Reply-To: <4A784303.2070804@mrabarnett.plus.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> <4A784303.2070804@mrabarnett.plus.com> Message-ID: <2d56febf0908040739i79d4bcc9o461d6641c68f5fb9@mail.gmail.com> On Wed, Aug 5, 2009 at 12:17 AM, MRAB wrote: > 0x00F0 is 240. ... Right. I wonder where my brain is. *searches pocket* So, what am I doing wrong here? >>> int(str(0x00F0), 16) 576 Cheers, -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From darcy at druid.net Tue Aug 4 10:44:43 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 Aug 2009 10:44:43 -0400 Subject: Obtaining Python version In-Reply-To: <2d56febf0908040739i79d4bcc9o461d6641c68f5fb9@mail.gmail.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> <4A784303.2070804@mrabarnett.plus.com> <2d56febf0908040739i79d4bcc9o461d6641c68f5fb9@mail.gmail.com> Message-ID: <20090804104443.72ebffba.darcy@druid.net> On Wed, 5 Aug 2009 00:39:56 +1000 Xavier Ho wrote: > So, what am I doing wrong here? > > >>> int(str(0x00F0), 16) Look at the output of str(0x00F0) for a clue. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From jjposner at optimum.net Tue Aug 4 10:45:24 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 04 Aug 2009 10:45:24 -0400 Subject: Announcing PythonTurtle In-Reply-To: References: Message-ID: <4A784984.6000903@optimum.net> > Certainly John- although I have not embedded the turtle module at all, > I just wrote my own. OK, then why the statements "from turtle import *" in the modules turtleprocess.py and turtlewidget.py? Tx, John From contact at xavierho.com Tue Aug 4 10:48:39 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 5 Aug 2009 00:48:39 +1000 Subject: Obtaining Python version In-Reply-To: <2d56febf0908040747s1a02f975ke383323e68732e6e@mail.gmail.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> <4A784303.2070804@mrabarnett.plus.com> <2d56febf0908040739i79d4bcc9o461d6641c68f5fb9@mail.gmail.com> <20090804104443.72ebffba.darcy@druid.net> <2d56febf0908040747s1a02f975ke383323e68732e6e@mail.gmail.com> Message-ID: <2d56febf0908040748y41c977c3k96d4437ed35edad@mail.gmail.com> On Wed, Aug 5, 2009 at 12:44 AM, D'Arcy J.M. Cain wrote: > On Wed, 5 Aug 2009 00:39:56 +1000 >> Xavier Ho wrote: >> > So, what am I doing wrong here? >> > >> > >>> int(str(0x00F0), 16) >> >> Look at the output of str(0x00F0) for a clue. >> > > ... Wow. I *am* slow tonight. Thanks. > > >>> int('00F0', 16) > 240 > (oops.) I was mixing the hex literals and the string literals. Thanks a bunch. -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From Samnsparky at gmail.com Tue Aug 4 11:25:28 2009 From: Samnsparky at gmail.com (Sparky) Date: Tue, 4 Aug 2009 08:25:28 -0700 (PDT) Subject: WindowsError: exception: access violation writing 0x00000000 References: <73c6c4f5-a00b-4f95-a85d-0f257b2f001a@c2g2000yqi.googlegroups.com> Message-ID: On Aug 3, 3:29?pm, Sparky wrote: > Hello! I am using cTypes on Windows to interface with a dll and I keep > getting an error when I execute this method: > > def eDigitalIn(self, channel, idNum = None, demo = 0, readD=0): > ? ? ? ? """ > ? ? ? ? Name: U12.eAnalogIn(channel, idNum = None, demo = 0, readD=0) > ? ? ? ? Args: See section 4.4 of the User's Guide > ? ? ? ? Desc: This is a simplified version of Counter. Reads & resets > the counter (CNT). > ? ? ? ? """ > > ? ? ? ? if idNum is None: > ? ? ? ? ? ? idNum = self.id > > ? ? ? ? ljid = ctypes.c_long(idNum) > ? ? ? ? state = ctypes.c_long(999) > > ? ? ? ? ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, > readD, ctypes.byref(state)) > > ? ? ? ? if ecode != 0: raise LabJackException(ecode) > ? ? ? ? if ljid == -1: raise LabJackException(-1, "LabJack not > found.") > > ? ? ? ? return {"idnum":ljid.value, "state":state.value} > > Here is the error message: > Traceback (most recent call last): > ? File "", line 1, in > ? ? device.eDigitalIn(0) > ? File "C:\Documents and Settings\All Users\Documents\Python > \LabJackPython_new\u12.py", line 118, in eDigitalIn > ? ? ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, readD, > ctypes.byref(state)) > WindowsError: exception: access violation writing 0x00000000 > > Here is the signature of the method (which is known to work with C++ > programs): > > long _stdcall EDigitalIn(long *idnum, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long demo, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long channel, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long readD, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long *state); > > staticLib is declared with staticLib = ctypes.windll.LoadLibrary > ("ljackuw"). > > Any ideas? > > Thanks, > Sam One more thing, I seem to be getting back incorrect values for doubles passed by reference. Any suggestions? I am on a 64-bit machine but I should think that should not make a difference. Thanks again, Sam From philip at semanchuk.com Tue Aug 4 11:47:31 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 4 Aug 2009 11:47:31 -0400 Subject: WindowsError: exception: access violation writing 0x00000000 In-Reply-To: References: <73c6c4f5-a00b-4f95-a85d-0f257b2f001a@c2g2000yqi.googlegroups.com> Message-ID: <2231CCC9-1EDA-4923-8110-20015F3BDA6E@semanchuk.com> On Aug 4, 2009, at 11:25 AM, Sparky wrote: > On Aug 3, 3:29 pm, Sparky wrote: >> Hello! I am using cTypes on Windows to interface with a dll and I >> keep >> getting an error when I execute this method: >> >> def eDigitalIn(self, channel, idNum = None, demo = 0, readD=0): >> """ >> Name: U12.eAnalogIn(channel, idNum = None, demo = 0, readD=0) >> Args: See section 4.4 of the User's Guide >> Desc: This is a simplified version of Counter. Reads & resets >> the counter (CNT). >> """ >> >> if idNum is None: >> idNum = self.id >> >> ljid = ctypes.c_long(idNum) >> state = ctypes.c_long(999) >> >> ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, >> readD, ctypes.byref(state)) >> >> if ecode != 0: raise LabJackException(ecode) >> if ljid == -1: raise LabJackException(-1, "LabJack not >> found.") >> >> return {"idnum":ljid.value, "state":state.value} >> >> Here is the error message: >> Traceback (most recent call last): >> File "", line 1, in >> device.eDigitalIn(0) >> File "C:\Documents and Settings\All Users\Documents\Python >> \LabJackPython_new\u12.py", line 118, in eDigitalIn >> ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, >> readD, >> ctypes.byref(state)) >> WindowsError: exception: access violation writing 0x00000000 >> >> Here is the signature of the method (which is known to work with C++ >> programs): >> >> long _stdcall EDigitalIn(long *idnum, >> long demo, >> long channel, >> long readD, >> long *state); >> >> staticLib is declared with staticLib = ctypes.windll.LoadLibrary >> ("ljackuw"). >> >> Any ideas? >> >> Thanks, >> Sam > > One more thing, I seem to be getting back incorrect values for doubles > passed by reference. Any suggestions? I am on a 64-bit machine but I > should think that should not make a difference. Hi Sam, ctypes is pretty straightforward, and I wouldn't expect it to break on something simple. I looked over your code (warning -- I am a ctypes novice) and it looks OK to me. If you're getting null pointer writes I'd suspect that the call signature isn't what you think it is, perhaps due to a lack of an extern "C" declaration or something like that. In short, I don't think this is a problem in your Python code or in ctypes. But since your Python code is the easiest to change, why not do a quick test of a minimal example? def eDigitalIn_test_version(self, channel, idNum = None, demo = 0, readD=0): ljid = ctypes.c_long(42) state = ctypes.c_long(999) ecode = staticLib.ECount(ctypes.byref(ljid), 0, 0, 0, ctypes.byref(state)) print ecode Does that work any better? You could also try replacing the byref() calls with pointers created by ctypes.pointer(). But I suspect that all this will do is give you confidence that it isn't your Python code that's wrong. You might want to write a minimal C program that invokes ECount. That would help you to prove whether or not you have a working C (not C++!) interface for your function. HTH Philip From cool-rr at cool-rr.com Tue Aug 4 12:04:17 2009 From: cool-rr at cool-rr.com (cool-RR) Date: Tue, 4 Aug 2009 19:04:17 +0300 Subject: Announcing PythonTurtle In-Reply-To: <4A784984.6000903@optimum.net> References: <4A784984.6000903@optimum.net> Message-ID: On Tue, Aug 4, 2009 at 5:45 PM, John Posner wrote: > > Certainly John- although I have not embedded the turtle module at all, >> I just wrote my own. >> > > OK, then why the statements "from turtle import *" in the modules > turtleprocess.py and turtlewidget.py? > > Tx, > John > > It's from a module turtle.py in my own PythonTurtle package. -- Sincerely, Ram Rachum -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at please.post Tue Aug 4 12:07:34 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 16:07:34 +0000 (UTC) Subject: kw param question References: Message-ID: In Steven D'Aprano writes: >On Mon, 03 Aug 2009 19:59:23 +0000, kj wrote: >> I want to write a decorator that, among other things, returns a function >> that has one additional keyword parameter, say foo=None. >> >> When I try >> >> def my_decorator(f): >> # blah, blah >> def wrapper(*p, foo=None, **kw): >> x = f(*p, **kw) >> if (foo): >> # blah, blah >> else >> # blah blah >> return wrapper >> >> ...i get a syntax error where it says "foo=None". I get similar errors >> with everything else I've tried. >> >> Is is possible to do this in Python? >Have you tried this under Python 2.6 or 3.0? >I've run into similar issues, because you can't have keyword-only >arguments in Python 2.5 :( >My solution was to create a decorator that faked them. The docstring is >longer than the decorator itself. >from functools import wraps >def keywords(**defaults): > """Return a decorator which decorates a function to accept keyword > arguments. > Python 2.5 and earlier don't allow keyword-only arguments for > non-builtin functions. The obvious syntax: > def func(x, *args, key=None, word='parrot'): > is not permitted. As a work-around, write your function something > like the following example: > >>> @keywords(key=None, word='parrot') > ... def func(x, y=0, *args, **kwargs): > ... # Inside the function, we can guarantee that kwargs['key'] and > ... # kwargs['word'] both exist, and no other keys. > ... print "x=%s, y=%s, args=%s" % (x, y, args) > ... if kwargs['key'] is None: msg = "kwargs['key'] is None" > ... else: msg = "kwargs['key'] is something else" > ... msg += " and kwargs['word'] is %r" % kwargs['word'] > ... print msg > ... > When you call func, if you don't provide a keyword-only argument, the > default will be substituted: > >>> func(1, 2, 3, 4) > x=1, y=2, args=(3, 4) > kwargs['key'] is None and kwargs['word'] is 'parrot' > >>> func(1) > x=1, y=0, args=() > kwargs['key'] is None and kwargs['word'] is 'parrot' > Naturally you can provide your own values for keyword-only arguments: > >>> func(1, 2, 3, word='spam') > x=1, y=2, args=(3,) > kwargs['key'] is None and kwargs['word'] is 'spam' > >>> func(1, 2, 3, word='spam', key=len) > x=1, y=2, args=(3,) > kwargs['key'] is something else and kwargs['word'] is 'spam' > If you pass an unexpected keyword argument, TypeError is raised: > >>> #doctest:+IGNORE_EXCEPTION_DETAIL > ... func(1, 2, 3, 4, keyword='something') > Traceback (most recent call last): > ... > TypeError: ... > """ > def decorator(func): > """Decorate func to allow keyword-only arguments.""" > @wraps(func) > def f(*args, **kwargs): > for key in kwargs: > if key not in defaults: > raise TypeError( > "'%s' is an invalid keyword argument for " \ > "this function" % key > ) > d = defaults.copy() > d.update(kwargs) > return func(*args, **d) > return f > return decorator Thanks for this. It's very useful. A lot of stuff for me to chew on. kynn From MatzeGuentert at gmx.de Tue Aug 4 12:27:40 2009 From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=) Date: Tue, 04 Aug 2009 18:27:40 +0200 Subject: M2Crypto: X509.X509_Extension_Stack() throws AssertionError In-Reply-To: References: Message-ID: <1249403260.3396.6.camel@celsius> > > cert_extension_2 = X509.new_extension("keyUsage", "101000000") > > Maybe your OpenSSL is too old. keyUsage needs to be defined in OpenSSL > obj_dat.h file for this to work. I am using OpenSSL version 0.9.8k-fips which is the latest version. I replaced: cert_extension_2 = X509.new_extension("keyUsage", "101000000") with: cert_extension_2 = X509.new_extension("keyUsage", "keyCertSign, cRLSign") which worked for me. Also I found an easy way to iterate through the extension stack using: cert = X509.X509() for e in cert_extension_stack: cert.add_ext(e) > > cert_extension_3 = X509.new_extension("subjectAlternativeName", > > "DNS:www.mydomain.tld") > And I believe you mispelled this, try subjectAltName. Changing "subjectAlternativeName" to "subjectAltName" did the trick. Thank you! From MatzeGuentert at gmx.de Tue Aug 4 12:51:39 2009 From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=) Date: Tue, 04 Aug 2009 18:51:39 +0200 Subject: M2Crypto: How to generate subjectKeyIdentifier / authorityKeyIdentifier Message-ID: <1249404699.3396.30.camel@celsius> Hello I am trying to add the extensions "subjectKeyIdentifier" and "authorityKeyIdentifier" to a x509v3 certificate. Regarding rfc5280, section 4.2.1.2 the key identifier is composed of the 160-bit SHA-1 hash of the BIT STRING subjectPublicKey http://tools.ietf.org/html/rfc5280#section-4.2.1.2 I don't know how or which function to use from EVP.PKey() to compose a fingerprint from the public key, as you can see below I was playing around with some functions, which simply returned nonsense (at least for me) I would be happy if someone could provide some example code on how to generate a fingerprint from the public key. "print keyp.final()" nor "print keyp.sign_final() on the last line does return anything... -------------------------------------------------------- from M2Crypto import X509, m2, RSA, EVP from config import * import os.path class Keypair(object): def __init__(self): self.config = Config() self.keypair = EVP.PKey() def create_keypair(self, key_size=1024): # generate an RSA key pair # OpenSSL book page 232 # second argument should be a constant RSA_F4 or RSA_3 rsa_key_pair = RSA.gen_key(key_size, m2.RSA_F4) # check if RSA key pair is usable # OpenSSL book page 232 if rsa_key_pair.check_key() != 1: print 'error while generating key!' sys.exit() # EVP object which can hold either a DSA or an RSA object # OpenSSL book page 236 evp_key_container = EVP.PKey() evp_key_container.assign_rsa(rsa_key_pair) self.keypair = evp_key_container def save_keypair(self, filename): if not os.path.exists(filename): self.keypair.save_key(filename, None) else: print "error in save_keypair(): cannot save key, it already exists" def load_keypair(self, filename): try: self.keypair = EVP.load_key(filename) except TypeError: print "error in load_keypair(): maybe file does not exist?" def get_keypair(self): return self.keypair def get_public_key(self): return self.keypair.pkey def print_keypair(self): print self.keypair.as_pem(None) if __name__ == "__main__": keypair = Keypair() keypair.create_keypair() # keypair.save_keypair("test.keys") keyp = keypair.get_keypair() print keyp.final() print keyp.sign_final() --------------------------------------------------------- And this maybe some OT question but how can I use OpenSSL to generate some fingerprint for testing and comparison purpose? For example I have got a certificate client.crt and the keys client.key $ openssl x509 -noout -text -in client.crt [...] X509v3 Subject Key Identifier: D2:C0:39:37:45:F6:A3:BF:D8:91:A2:F5:C7:43:42:80:6A:3C:38:AF X509v3 Authority Key Identifier: A7:E2:2E:59:F8:53:1F:68:F2:59:34:32:42:F6:21:20:C0:D1:3A:89 [...] But openssl provides me different fingerprint... so whats wrong here? $ openssl rsa -pubout -in client_1.key | openssl sha1 -c writing RSA key cc:d2:ab:16:1f:a1:23:3e:fe:45:03:ab:4f:86:57:65:52:16:b2:1a From bartsmeets86 at gmail.com Tue Aug 4 12:52:05 2009 From: bartsmeets86 at gmail.com (Bart Smeets) Date: Tue, 4 Aug 2009 18:52:05 +0200 Subject: easy_install: unresolved external symbol In-Reply-To: <87f2eede5ce0f1391994db66153e3c96@preisshare.net> References: <2119ee90908031339o71e19624qa815241b446d739d@mail.gmail.com> <2119ee90908040152k5a744f98l7d5bc7da755948a2@mail.gmail.com> <87f2eede5ce0f1391994db66153e3c96@preisshare.net> Message-ID: <2119ee90908040952p6233d28ek99584bcd4f5f6f42@mail.gmail.com> How do I give the option to link to the ez_setup.py? 2009/8/4 David Lyon > On Tue, 4 Aug 2009 10:52:20 +0200, Bart Smeets > wrote: > > I could ofcourse use cxfreeze's binary package. But bbfreeze is not > > available as a binary. I would love to get easy_install to work. But I > have > > no idea what's going wrong here. > > What is going on is that setuptools does some very 'advanced' things. > > The best you can do is give the option to link to the ez_setup.py > install script and let the users install it them themselves... > > David > -------------- next part -------------- An HTML attachment was scrubbed... URL: From r.a.teterin at gmail.com Tue Aug 4 13:08:45 2009 From: r.a.teterin at gmail.com (Roman) Date: Tue, 4 Aug 2009 21:08:45 +0400 Subject: Trying to get ABC to work In-Reply-To: <358094.5069.qm@web65302.mail.ac2.yahoo.com> References: <358094.5069.qm@web65302.mail.ac2.yahoo.com> Message-ID: <20090804170845.GA3092@localhost> Following code works, although I'm not sure that it's exactly what you want: import abc class MetaExample(abc.ABCMeta): def __new__(mcs, name, bases, ns): ns['cls_meth'] = mcs.cls_meth if not 'cls_abc' in ns: ns['cls_abc'] = mcs.cls_abc return super().__new__(mcs, name, bases, ns) def cls_meth(cls): print('Class method defined stub') @abc.abstractmethod def cls_abc(cls): try: print('Class-Abstract method defined stub') except NotImplementedError as err: print('Must implement cls_abc') except: print('General exception at cls_abc method') That's how I've tested it: class Test1(object, metaclass=MetaExample): def cls_abc(self): print("method of", self) class Test2(object, metaclass=MetaExample): pass test1 = Test1() test1.cls_meth() test1.cls_abc() test2 = Test2() Output: Class method defined stub method of <__main__.Test1 object at 0xb7b5f52c> Traceback (most recent call last): File "/tmp/test.py", line 32, in test2 = Test2() TypeError: Can't instantiate abstract class Test2 with abstract methods cls_abc According to the documentation, @abstractmethod "requires that the metaclass is ABCMeta or derived from it", so I've changed base class from type to ABCMeta. Also I don't think that using try/except inside the abstract method will work, maybe it would be better to check presence of all required methods directly inside the metaclass, without @abstractmethod decorator. From holger at merlinux.eu Tue Aug 4 13:19:16 2009 From: holger at merlinux.eu (holger krekel) Date: Tue, 4 Aug 2009 19:19:16 +0200 Subject: pylib/py.test 1.0.0 released Message-ID: <20090804171915.GS31589@trillke.net> Hello everyone, i am happy to announce pylib/py.test 1.0.0, a MIT-licensed library geared towards advanced testing and elastic distributed programming with Python. It features the mature cross-project py.test automated testing tool with many new features, aiming to: * allow writing zero-boilerplate automated tests in Python * offer strong debugging and reporting of test failures * rapidly run and ad-hoc distribute tests to multiple CPUs/platforms * support unit-, functional and integration testing * be easy to extend and tackle growing testing needs, (current prime example oejskit, a live-browser javascript unittesting 3rd party plugin) Please check things out at: http://pytest.org or read the blogged release announcement: http://tetamap.wordpress.com/2009/08/04/pylib-1-0-0 or read on for some ... Distinctive new features shipping with py.test 1.0.0 ------------------------------------------------------ For those already knowing about the older 0.9.2 release or being experienced with other testing approaches i'll try to give a summary of the distinctive testing features shipping with 1.0.0: * test function arguments ("funcargs"): With this, python test functions can name arguments and one writes factory functions to provide instances for such "fixture" arguments. This page http://codespeak.net/py/dist/test/funcargs.html contains reference info and tutorial examples. Test function arguments also allow for natural test parametrization - one provides several different argument values, no changes to the test function needed, no magic "yield" for generating tests anymore - although 1.0 still allows them and of course still supports traditional xUnit-style setup_module/class/function or (new) direct runs of unittest.TestCase style tests. * distributed testing: distributing test runs among Linux/OSX/Windows hosts and across python-2.4 till python-2.6 interpreters works reasonably stable now. This means that you can easily iron out test-module/function specific problems across a variety of platforms, accelerating the change & test feedback cycle. * xfail: a new way to mark tests as "expected to fail" which means they run normally but are reported/counted specially. This "xfail" mark is meant to mark missing / wrong implementation rather than missing dependencies / wrong platforms for which one uses "skip". Especially for larger test suites making this distinction is very helpful. * IO-capturing: output of test functions is captured per-test, by default including any output from sub processes. This works on all platforms and also (now) interacts well with the logging module without importing/using it itself so there are no interferences. * pastebin: new command line option "--pastebin" to send your test session output or individual test failures to the Pocoo pastebin service and prints out URLs. Convenient for quick IRC/messaging communication. * plugins: it is now easy to write plugins by implementing one or more of the 37 hooks which py.test calls to implement the testing process. There are many examples, among them the "oejskit" plugin which integrates testing of javascript code in real-life browsers into a regular test run. Apart from such separately distributed "cross-project" plugins you can also write per-project plugins/extensions that lives with your testing code. cheers & have fun, holger -- Metaprogramming, Python, Testing: http://tetamap.wordpress.com Python, PyPy, pytest contracting: http://merlinux.eu From Samnsparky at gmail.com Tue Aug 4 13:23:10 2009 From: Samnsparky at gmail.com (Sparky) Date: Tue, 4 Aug 2009 10:23:10 -0700 (PDT) Subject: WindowsError: exception: access violation writing 0x00000000 References: <73c6c4f5-a00b-4f95-a85d-0f257b2f001a@c2g2000yqi.googlegroups.com> Message-ID: <26927cc2-2134-46b6-873a-02be9cf829f2@h21g2000yqa.googlegroups.com> On Aug 4, 9:47?am, Philip Semanchuk wrote: > On Aug 4, 2009, at 11:25 AM, Sparky wrote: > > > > > > > On Aug 3, 3:29 pm, Sparky wrote: > >> Hello! I am using cTypes on Windows to interface with a dll and I ? > >> keep > >> getting an error when I execute this method: > > >> def eDigitalIn(self, channel, idNum = None, demo = 0, readD=0): > >> ? ? ? ? """ > >> ? ? ? ? Name: U12.eAnalogIn(channel, idNum = None, demo = 0, readD=0) > >> ? ? ? ? Args: See section 4.4 of the User's Guide > >> ? ? ? ? Desc: This is a simplified version of Counter. Reads & resets > >> the counter (CNT). > >> ? ? ? ? """ > > >> ? ? ? ? if idNum is None: > >> ? ? ? ? ? ? idNum = self.id > > >> ? ? ? ? ljid = ctypes.c_long(idNum) > >> ? ? ? ? state = ctypes.c_long(999) > > >> ? ? ? ? ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, > >> readD, ctypes.byref(state)) > > >> ? ? ? ? if ecode != 0: raise LabJackException(ecode) > >> ? ? ? ? if ljid == -1: raise LabJackException(-1, "LabJack not > >> found.") > > >> ? ? ? ? return {"idnum":ljid.value, "state":state.value} > > >> Here is the error message: > >> Traceback (most recent call last): > >> ? File "", line 1, in > >> ? ? device.eDigitalIn(0) > >> ? File "C:\Documents and Settings\All Users\Documents\Python > >> \LabJackPython_new\u12.py", line 118, in eDigitalIn > >> ? ? ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, ? > >> readD, > >> ctypes.byref(state)) > >> WindowsError: exception: access violation writing 0x00000000 > > >> Here is the signature of the method (which is known to work with C++ > >> programs): > > >> long _stdcall EDigitalIn(long *idnum, > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long demo, > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long channel, > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long readD, > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long *state); > > >> staticLib is declared with staticLib = ctypes.windll.LoadLibrary > >> ("ljackuw"). > > >> Any ideas? > > >> Thanks, > >> Sam > > > One more thing, I seem to be getting back incorrect values for doubles > > passed by reference. Any suggestions? I am on a 64-bit machine but I > > should think that should not make a difference. > > Hi Sam, > ctypes is pretty straightforward, and I wouldn't expect it to break on ? > something simple. I looked over your code (warning -- I am a ctypes ? > novice) and it looks OK to me. If you're getting null pointer writes ? > I'd suspect that the call signature isn't what you think it is, ? > perhaps due to a lack of an extern "C" declaration or something like ? > that. In short, I don't think this is a problem in your Python code or ? > in ctypes. > > But since your Python code is the easiest to change, why not do a ? > quick test of a minimal example? > > def eDigitalIn_test_version(self, channel, idNum = None, demo = 0, ? > readD=0): > ? ? ? ? ?ljid = ctypes.c_long(42) > ? ? ? ? ?state = ctypes.c_long(999) > > ? ? ? ? ?ecode = staticLib.ECount(ctypes.byref(ljid), 0, 0, 0, ? > ctypes.byref(state)) > > ? ? ? ? ?print ecode > > Does that work any better? > > You could also try replacing the byref() calls with pointers created ? > by ctypes.pointer(). But I suspect that all this will do is give you ? > confidence that it isn't your Python code that's wrong. > > You might want to write a minimal C program that invokes ECount. That ? > would help you to prove whether or not you have a working C (not C++!) ? > interface for your function. > > HTH > Philip Hey Philip, Thank you for your response. It turns out I was calling a function that I was not intending on calling, so it was not a Python problem. Thanks, Sam From jay.bird0804 at gmail.com Tue Aug 4 14:15:47 2009 From: jay.bird0804 at gmail.com (Jay Bird) Date: Tue, 4 Aug 2009 11:15:47 -0700 (PDT) Subject: Overlap in python Message-ID: Hi everyone, I've been trying to figure out a simple algorithm on how to combine a list of parts that have 1D locations that overlap into a non- overlapping list. For example, here would be my input: part name location a 5-9 b 7-10 c 3-6 d 15-20 e 18-23 And here is what I need for an output: part name location c.a.b 3-10 d.e 15-23 I've tried various methods, which all fail. Does anyone have an idea how to do this? Thank you very much! Jay From marcusw at cox.net Tue Aug 4 14:31:49 2009 From: marcusw at cox.net (Marcus Wanner) Date: Tue, 4 Aug 2009 11:31:49 -0700 (PDT) Subject: Overlap in python References: Message-ID: <3f11f316-5e9e-4786-8757-edf9ab234bb7@j32g2000yqh.googlegroups.com> On Aug 4, 2:15?pm, Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. ?For example, here would be my input: > > part name ? location > a ? ? ? ? ? ? ? ? ?5-9 > b ? ? ? ? ? ? ? ? ?7-10 > c ? ? ? ? ? ? ? ? ?3-6 > d ? ? ? ? ? ? ? ? ?15-20 > e ? ? ? ? ? ? ? ? ?18-23 > > And here is what I need for an output: > part name ? location > c.a.b ? ? ? ? ? ?3-10 > d.e ? ? ? ? ? ? ? 15-23 > > I've tried various methods, which all fail. ?Does anyone have an idea > how to do this? > > Thank you very much! > Jay Just take all the values, put them in a list, and use min() and max(). For example: import string def makelist(values): values = string.replace(values, ' ', '') listofvaluepairs = string.split(values, ',') listofvalues = [] for pair in listofvaluepairs: twovalues = string.split(pair, '-') listofvalues.append(int(twovalues[0])) listofvalues.append(int(twovalues[1])) return listofvalues values = '5-9, 7-10, 3-6' values = makelist(values) print('Values: %d-%d' %(min(values), max(values)) ) Marcus From anna.konstorum at gmail.com Tue Aug 4 14:46:14 2009 From: anna.konstorum at gmail.com (Ann) Date: Tue, 4 Aug 2009 11:46:14 -0700 (PDT) Subject: Overlap in python References: <3f11f316-5e9e-4786-8757-edf9ab234bb7@j32g2000yqh.googlegroups.com> Message-ID: On Aug 4, 11:31?am, Marcus Wanner wrote: > On Aug 4, 2:15?pm, Jay Bird wrote: > > > > > Hi everyone, > > > I've been trying to figure out a simple algorithm on how to combine a > > list of parts that have 1D locations that overlap into a non- > > overlapping list. ?For example, here would be my input: > > > part name ? location > > a ? ? ? ? ? ? ? ? ?5-9 > > b ? ? ? ? ? ? ? ? ?7-10 > > c ? ? ? ? ? ? ? ? ?3-6 > > d ? ? ? ? ? ? ? ? ?15-20 > > e ? ? ? ? ? ? ? ? ?18-23 > > > And here is what I need for an output: > > part name ? location > > c.a.b ? ? ? ? ? ?3-10 > > d.e ? ? ? ? ? ? ? 15-23 > > > I've tried various methods, which all fail. ?Does anyone have an idea > > how to do this? > > > Thank you very much! > > Jay > > Just take all the values, put them in a list, and use min() and max(). > For example: > > import string > > def makelist(values): > ? ? values = string.replace(values, ' ', '') > ? ? listofvaluepairs = string.split(values, ',') > ? ? listofvalues = [] > ? ? for pair in listofvaluepairs: > ? ? ? ? twovalues = string.split(pair, '-') > ? ? ? ? listofvalues.append(int(twovalues[0])) > ? ? ? ? listofvalues.append(int(twovalues[1])) > ? ? return listofvalues > > values = '5-9, 7-10, 3-6' > values = makelist(values) > print('Values: %d-%d' %(min(values), max(values)) ) > > Marcus Thank you for your help, this is a very nice program but it does not address the issue that I have values that do not overlap, for example 'c' and 'd' do not overlap in the above example and thus I would not want to output 3-20 but the individual positions instead. In addition, my inputs are not ordered from smallest to largest, thus I could have a situation where a=5-9, b=15-20, c=7-10, etc., and I would still want an output of: a.c = 5-10, b=15-20. I apologize for the complication. Thank you again! Jay From aurele.tux at gmail.com Tue Aug 4 14:53:56 2009 From: aurele.tux at gmail.com (aurelien) Date: Tue, 04 Aug 2009 20:53:56 +0200 Subject: Is it possible to have the python color in the terminal ? Message-ID: <1249412036.5765.20.camel@r2d2> Hello, I am under gNewSense, i am a newbbie on Python, i look for how change the color terminal when python run. at the step >>> all is in black and white. Is it possible to have the python color in the terminal ? Thanks for your help. aurelien From marcusw at cox.net Tue Aug 4 14:55:22 2009 From: marcusw at cox.net (Marcus Wanner) Date: Tue, 04 Aug 2009 14:55:22 -0400 Subject: Overlap in python In-Reply-To: References: <3f11f316-5e9e-4786-8757-edf9ab234bb7@j32g2000yqh.googlegroups.com> Message-ID: On 8/4/2009 2:46 PM, Ann wrote: > On Aug 4, 11:31 am, Marcus Wanner wrote: >> On Aug 4, 2:15 pm, Jay Bird wrote: >> >> >> >>> Hi everyone, >>> I've been trying to figure out a simple algorithm on how to combine a >>> list of parts that have 1D locations that overlap into a non- >>> overlapping list. For example, here would be my input: >>> part name location >>> a 5-9 >>> b 7-10 >>> c 3-6 >>> d 15-20 >>> e 18-23 >>> And here is what I need for an output: >>> part name location >>> c.a.b 3-10 >>> d.e 15-23 >>> I've tried various methods, which all fail. Does anyone have an idea >>> how to do this? >>> Thank you very much! >>> Jay >> Just take all the values, put them in a list, and use min() and max(). >> For example: >> >> import string >> >> def makelist(values): >> values = string.replace(values, ' ', '') >> listofvaluepairs = string.split(values, ',') >> listofvalues = [] >> for pair in listofvaluepairs: >> twovalues = string.split(pair, '-') >> listofvalues.append(int(twovalues[0])) >> listofvalues.append(int(twovalues[1])) >> return listofvalues >> >> values = '5-9, 7-10, 3-6' >> values = makelist(values) >> print('Values: %d-%d' %(min(values), max(values)) ) >> >> Marcus > > Thank you for your help, this is a very nice program but it does not > address the issue that I have values that do not overlap, for example > 'c' and 'd' do not overlap in the above example and thus I would not > want to output 3-20 but the individual positions instead. In > addition, my inputs are not ordered from smallest to largest, thus I > could have a situation where a=5-9, b=15-20, c=7-10, etc., and I would > still want an output of: a.c = 5-10, b=15-20. I apologize for the > complication. > > Thank you again! > > Jay That would be a bit more complicated...you might try using tuples of values in a list, or writing your own class for the data handling. Unfortunately that's not something I can just sit down and code in 5 minutes, it would take some careful thought and planning. Marcus From marcusw at cox.net Tue Aug 4 15:00:32 2009 From: marcusw at cox.net (Marcus Wanner) Date: Tue, 04 Aug 2009 15:00:32 -0400 Subject: Is it possible to have the python color in the terminal ? In-Reply-To: <1249412036.5765.20.camel@r2d2> References: <1249412036.5765.20.camel@r2d2> Message-ID: On 8/4/2009 2:53 PM, aurelien wrote: > Hello, > > I am under gNewSense, i am a newbbie on Python, i look for how change > the color terminal when python run. > at the step >>> all is in black and white. > Is it possible to have the python color in the terminal ? > > Thanks for your help. > > aurelien > You might try posting to this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/58df7b77394e4666/f4c13766a1e09380 I don't know much about the question myself, though. Marcus From breamoreboy at yahoo.co.uk Tue Aug 4 15:10:52 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 04 Aug 2009 20:10:52 +0100 Subject: Overlap in python In-Reply-To: References: Message-ID: Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. For example, here would be my input: > > part name location > a 5-9 > b 7-10 > c 3-6 > d 15-20 > e 18-23 > > And here is what I need for an output: > part name location > c.a.b 3-10 > d.e 15-23 > > I've tried various methods, which all fail. Does anyone have an idea > how to do this? > > Thank you very much! > Jay I haven't tried but could you adapt this:- data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] for k, g in groupby(enumerate(data), lambda (i,x):i-x): print map(itemgetter(1), g) found here http://www.python.org/doc/2.6.2/library/itertools.html#module-itertools -- Kindest regards. Mark Lawrence. From kosta.koeman at gmail.com Tue Aug 4 15:13:10 2009 From: kosta.koeman at gmail.com (Kosta) Date: Tue, 4 Aug 2009 12:13:10 -0700 (PDT) Subject: Using Python to automate builds Message-ID: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> I am a Python newbie, tasked with automating (researching) building Windows drivers using the WDK build environment. I've been looking into Python for this (instead of writing a bunch of batch files). What I would like to do, is to open a cmd window, and start a Python script. This script would then (based upon input arguments), build different flavors of the driver (fre, chk, x86, x64) and do some post processing (create cat files, sign, etc.). I was hoping to take advantage as much as possible of exisiting infrastructure from the WDK. I am able to call setenv.bat and provide all the input parameters. One of the things setenv.bat does is change the path environment variable. However, this is not captured by Python. I could duplicate the functionality, but I'd rather not. Is there a way to capture all enviroment variable changes being made by a batch file from Python? Thanks! From aurele.tux at gmail.com Tue Aug 4 15:20:03 2009 From: aurele.tux at gmail.com (aurelien) Date: Tue, 4 Aug 2009 12:20:03 -0700 (PDT) Subject: Is it possible to have the python color in the terminal ? Message-ID: Hello, I am under gNewSense, i am a newbbie on Python, i look for how change the color terminal when python run. at the step >>> all is in black and white. Is it possible to have the python color in the terminal ? Thanks for your help aurelien From aurele.tux at gmail.com Tue Aug 4 15:23:24 2009 From: aurele.tux at gmail.com (aurelien) Date: Tue, 04 Aug 2009 21:23:24 +0200 Subject: Is it possible to have the python color in the terminal ? In-Reply-To: References: <1249412036.5765.20.camel@r2d2> Message-ID: <1249413804.5765.24.camel@r2d2> > You might try posting to this thread: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/58df7b77394e4666/f4c13766a1e09380 > I don't know much about the question myself, though. > > Marcus Thanks for your help ! aurelien From no.email at please.post Tue Aug 4 15:29:00 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 19:29:00 +0000 (UTC) Subject: no-clobber dicts? References: Message-ID: In Steven D'Aprano writes: >On Mon, 03 Aug 2009 21:07:32 +0000, kj wrote: >> I use the term "no-clobber dict" to refer to a dictionary D with the >> especial property that if K is in D, then >> >> D[K] = V >> >> will raise an exception unless V == D[K]. In other words, D[K] can be >> set if K doesn't exist already among D's keys, or if the assigned value >> is equal to the current value of D[K]. All other assignments to D[K] >> trigger an exception. >Coincidentally, I just built something very close to what you ask. Here >it is: >class ConstantNamespace(dict): > """Dictionary with write-once keys.""" > def __delitem__(self, key): > raise TypeError("can't unbind constants") > def __setitem__(self, key, value): > if key in self: > raise TypeError("can't rebind constants") > super(ConstantNamespace, self).__setitem__(key, value) > def clear(self): > raise TypeError('cannot unbind constants') > def pop(self, key, *args): > raise TypeError("cannot pop constants") > def popitem(self): > raise TypeError("cannot pop constants") > def update(self, other): > for key in other: > if key in self: > raise TypeError('cannot update constants') > # If we get here, then we're not modifying anything, > # so okay to proceed. > super(ConstantNamespace, self).update(other) > def copy(self): > c = self.__class__(**self) > return c Thanks. As you note this not quite what I'm looking for, but it's a good template for it. kynn From no.email at please.post Tue Aug 4 15:30:51 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 19:30:51 +0000 (UTC) Subject: no-clobber dicts? References: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> Message-ID: In Chris Rebert writes: >On Mon, Aug 3, 2009 at 2:47 PM, r wrote: >> On Aug 3, 4:07=C2=A0pm, kj wrote: >>> I use the term "no-clobber dict" to refer to a dictionary D with >>> the especial property that if K is in D, then >>> >>> =C2=A0 D[K] =3D V >>> >>> will raise an exception unless V =3D=3D D[K]. =C2=A0In other words, D[K] >>> can be set if K doesn't exist already among D's keys, or if the >>> assigned value is equal to the current value of D[K]. =C2=A0All other >>> assignments to D[K] trigger an exception. >>> >>> The idea here is to detect inconsistencies in the data. >>> >>> This is a data structure I often need. =C2=A0Before I re-invent the >>> wheel, I thought I'd ask: is it already available? >>> >>> TIA! >>> >>> kynn >> >> Not sure if something like this already exists, but it would be >> trivial to implement by overriding dict.__setitem__() >That is, if you don't care about .update() not preserving the >invariant. The implication here is that .update() does not in turn use .__setitem__(), which I find a bit surprising. kynn From r.a.teterin at gmail.com Tue Aug 4 15:54:10 2009 From: r.a.teterin at gmail.com (Roman) Date: Tue, 4 Aug 2009 23:54:10 +0400 Subject: Is it possible to have the python color in the terminal ? In-Reply-To: References: Message-ID: <20090804195410.GA3247@localhost> On 04/08/09 12:20, aurelien wrote: > Hello, > > I am under gNewSense, i am a newbbie on Python, i look for how change > the color terminal when python run. > at the step >>> all is in black and white. > Is it possible to have the python color in the terminal ? > > Thanks for your help > > aurelien > -- > http://mail.python.org/mailman/listinfo/python-list > If you want to get colourful output, you can use IPython (http://ipython.scipy.org/moin/FrontPage), it is an enhanced Python shell. You may also change colour of text by printing appropriate escape sequences (e.g. executing print("\033[0;32m") in Python interpreter should change foreground colour to green. From gregor.lingl at aon.at Tue Aug 4 15:57:40 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 21:57:40 +0200 Subject: Overlap in python In-Reply-To: References: Message-ID: <4a7892c2$0$2297$91cee783@newsreader02.highway.telekom.at> Jay Bird schrieb: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. For example, here would be my input: > > part name location > a 5-9 > b 7-10 > c 3-6 > d 15-20 > e 18-23 > > And here is what I need for an output: > part name location > c.a.b 3-10 > d.e 15-23 > Suppose you have your data given as a dictionary: data = {'a':(5,9), 'b':(7,10), 'c':(3,6), 'd':(15,20), 'e':(18,23)} Then the following not particularly elegant but very simple and straight forward algorithm will solve your problem: def values(key): return set(range(data[key][0], data[key][1]+1)) keys = list(data.keys()) result = [] while keys: k = [keys[0]] keys = keys[1:] v = values(k[0]) for l in keys[:]: if v.intersection(values(l)): v.update(values(l)) k.append(l) keys.remove(l) result.append((k,v)) # print(result) ## if you like for k, v in result: print(".".join(sorted(k)), "%d-%d" % (min(v), max(v))) Regards, Gregor > I've tried various methods, which all fail. Does anyone have an idea > how to do this? > > Thank you very much! > Jay From info at egenix.com Tue Aug 4 15:58:40 2009 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Tue, 04 Aug 2009 21:58:40 +0200 Subject: ANN: eGenix pyOpenSSL Distribution 0.9.0-0.9.8k now also in .egg format Message-ID: <4A7892F0.3080805@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com pyOpenSSL Distribution Version 0.9.0-0.9.8k An easy to install and use repackaged distribution of the pyOpenSSL Python interface for OpenSSL - available on Windows, Mac OS X and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.9.0-0.9.8k-1-Update.html ________________________________________________________________________ INTRODUCTION The eGenix.com pyOpenSSL Distribution includes everything you need to get started with SSL in Python. It comes with an easy to use installer that includes the most recent OpenSSL library versions in pre-compiled form. pyOpenSSL is an open-source Python add-on (http://pyopenssl.sf.net/) that allows writing SSL aware networking applications as well as certificate management tools. OpenSSL is an open-source implementation of the SSL protocol (http://www.openssl.org/). For more information, please see the product page: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ NEWS Due to popular demand, we've added .egg file versions for Windows and Linux to the available download options. This should make things easier for people using e.g. zc.buildout and other egg-file based installers. As always, binaries include both pyOpenSSL and the necessary OpenSSL libraries. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ UPGRADING Before installing this version of pyOpenSSL, please make sure that you uninstall any previously installed pyOpenSSL version. Otherwise, you could end up not using the included OpenSSL libs. _______________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Aug 04 2009) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From no.email at please.post Tue Aug 4 16:01:12 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 20:01:12 +0000 (UTC) Subject: no-clobber dicts? References: Message-ID: In Steven D'Aprano writes: >class ConstantNamespace(dict): >I also have a series of unit tests for it if you're interested in them. Actually, come to think of it, I think I'll take you up on this. I'd love to see those tests. Unit testing in Python is in area I need to work on. TIA! kynn From dickinsm at gmail.com Tue Aug 4 16:03:00 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 4 Aug 2009 13:03:00 -0700 (PDT) Subject: Overlap in python References: Message-ID: <78d86d92-d373-4163-a418-600a3eb36ab3@o15g2000yqm.googlegroups.com> On Aug 4, 7:15?pm, Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. ?For example, here would be my input: > > part name ? location > a ? ? ? ? ? ? ? ? ?5-9 > b ? ? ? ? ? ? ? ? ?7-10 > c ? ? ? ? ? ? ? ? ?3-6 > d ? ? ? ? ? ? ? ? ?15-20 > e ? ? ? ? ? ? ? ? ?18-23 > > And here is what I need for an output: > part name ? location > c.a.b ? ? ? ? ? ?3-10 > d.e ? ? ? ? ? ? ? 15-23 > > I've tried various methods, which all fail. ?Does anyone have an idea > how to do this? Here's an approach that might work. Turning it into a sensible function and parsing input/massaging output properly are left as an exercise. Blocks that just touch (e.g. (3, 6) then (6, 9)) are amalgamated; if this isn't what you want, and they should be treated as separate instead, then replace 'Stop' with 'Finish' (or any other string that sorts before 'Start'). input = [ ('a', (5, 9)), ('b', (7, 10)), ('c', (3, 6)), ('d', (15, 20)), ('e', (18, 23)), ] # create sorted list of points where an interval is entered or left transitions = [] for name, (start, stop) in input: transitions.extend([(start, 'Start', name), (stop, 'Stop', name)]) transitions.sort() # scan list, accumulating blocks along the way. count = 0 for i, (pt, startend, name) in enumerate(transitions): if startend == 'Start': if not count: start = pt names = [] count += 1 names.append(name) else: count -= 1 if not count: print '.'.join(names), "%s--%s" % (start, pt) The output that I get from this under Python 2.6 is: c.a.b 3--10 d.e 15--23 -- Mark From clp2 at rebertia.com Tue Aug 4 16:03:08 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 Aug 2009 13:03:08 -0700 Subject: no-clobber dicts? In-Reply-To: References: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> Message-ID: <50697b2c0908041303ycf7a2f2g47b2b2eebf723d32@mail.gmail.com> On Tue, Aug 4, 2009 at 12:30 PM, kj wrote: > In Chris Rebert writes: > >>On Mon, Aug 3, 2009 at 2:47 PM, r wrote: >>> On Aug 3, 4:07=C2=A0pm, kj wrote: >>>> I use the term "no-clobber dict" to refer to a dictionary D with >>>> the especial property that if K is in D, then >>>> >>>> =C2=A0 D[K] =3D V >>>> >>>> will raise an exception unless V =3D=3D D[K]. =C2=A0In other words, D[K] >>>> can be set if K doesn't exist already among D's keys, or if the >>>> assigned value is equal to the current value of D[K]. =C2=A0All other >>>> assignments to D[K] trigger an exception. >>>> >>>> The idea here is to detect inconsistencies in the data. >>>> >>>> This is a data structure I often need. =C2=A0Before I re-invent the >>>> wheel, I thought I'd ask: is it already available? >>>> >>>> TIA! >>>> >>>> kynn >>> >>> Not sure if something like this already exists, but it would be >>> trivial to implement by overriding dict.__setitem__() > >>That is, if you don't care about .update() not preserving the >>invariant. > > The implication here is that .update() does not in turn use > .__setitem__(), which I find a bit surprising. The builtin types are allowed to take such shortcuts for performance reasons. Cheers, Chris -- http://blog.rebertia.com From dciphercomputing at gmail.com Tue Aug 4 16:05:10 2009 From: dciphercomputing at gmail.com (Simon) Date: Tue, 4 Aug 2009 13:05:10 -0700 (PDT) Subject: Newbie Question regarding __init__() References: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> <01bcf8b8-687c-4bf4-acbb-b059a480d382@f33g2000vbm.googlegroups.com> Message-ID: <20295b74-b630-47bd-b48d-9881bc6453a7@g6g2000vbr.googlegroups.com> On Aug 3, 11:00?pm, Dave Angel wrote: > Simon wrote: > > On Aug 2, 5:51 am, Dave Angel wrote: > > >> > >> I don't understand your comparison to Foxpro. ?read on. > > >> As your code was last posted, you don't need a return value from > >> init_Exec() ?Every function that doesn't have an explicit return will > >> return None. ?And None is interpreted as False in an "and" expression. ? > >> If you had an "if" around the whole thing, then you'd care. > > >> DaveA > > > All I meant by the FoxPro comment was the idea of using the equal sign > > without a variable to throw away the result. ?Also in FoxPro there is > > no such thing as automatically returning None. ?If there is no > > explicit return then True is returned. > > > Thanks I did not know that None is interpreted as False. > > > Simon > > To throw away the result of an expression in Python is even easier. ? > Just don't use it. > ? ? ? ?func1() and func2() > is a valid expression whose result is not used. ?And func2()'s result is > therefore irrelevant. ?But shortcircuiting means that func2() is only > called if func1() returned False (or something equivalent to it, like 0 > or an empty list) Thanks for telling me how Python throws away the result. Secondly my code works perfectly now that I am properly defining my methods using "self". From 1x7y2z9 at gmail.com Tue Aug 4 16:11:18 2009 From: 1x7y2z9 at gmail.com (1x7y2z9) Date: Tue, 4 Aug 2009 13:11:18 -0700 (PDT) Subject: boolean OR gotcha Message-ID: >>> 0 or None is None True >>> None or 0 is None False >>> None or 0 is 0 True Yes, this is explained in the docs: The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned. Another one (also explainable): >>> 0 or None == None or 0 True # Above is same as (operator precedence): >>> 0 or (None == None) or 0 True # Here is something different: >>> (0 or None) == (None or 0) False From python at rcn.com Tue Aug 4 16:14:29 2009 From: python at rcn.com (Raymond Hettinger) Date: Tue, 4 Aug 2009 13:14:29 -0700 (PDT) Subject: no-clobber dicts? References: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> Message-ID: <435e2e2c-6f83-48e0-870e-febdc37c4c5c@x6g2000prc.googlegroups.com> [kj] > The implication here is that .update() does not in turn use > .__setitem__(), which I find a bit surprising. It's never wise to make assumptions about this sort of thing. Every method in a class or type is allowed to directly access or modify its private, internal data. The implementation is free to choose whether to limit that access to a few accessors (i.e. getitem, setitem, delitem, len) or to let all of the methods have direct access to the underlying data structure. Even if accessors were used, the choice would be arbitrary (perhaps delitem() gets implemented in terms of pop() or somesuch). This is a basic for OO programming. Unless the class documentation promises to use particular hooks, the implementation is free to change in any way that doesn't violate the published API (this is one of the benefits of encapsulation and abstract data types). In general, if a subclass is overriding, rather than extending, then it should override *every* method that could be affected. Raymond From mensanator at aol.com Tue Aug 4 16:21:30 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Aug 2009 13:21:30 -0700 (PDT) Subject: Is it possible to have the python color in the terminal ? References: Message-ID: On Aug 4, 1:53?pm, aurelien wrote: > Hello, > > I am under gNewSense, i am a newbbie on Python, i look for how change > the color terminal when python run. > at the step >>> all is in black and white. > Is it possible to have the python color in the terminal ? Depends on whether your terminal supports ANSI codes. For example, Windows does not, but the Cygwin terminal does. So, from Cygwin I can do >>> a = "\x1b[32m" >>> a '\x1b[32m' >>> print a >>> >>> >>> print b Traceback (most recent call last): File "", line 1, in NameError: name 'b' is not defined >>> And everything from the "print a" statement onwards is green. An ANSI code: an escape character (ESC, ASCII value 27, \x1b in hex) followed by the appropriate code sequence: Code: Meaning: \x1b[0m reset; clears all colors and styles (to white on black) \x1b[1m bold on (see below) \x1b[3m italics on \x1b[4m underline on \x1b[7m inverse on; reverses foreground & background colors \x1b[9m strikethrough on \x1b[22m bold off (see below) \x1b[23m italics off \x1b[24m underline off \x1b[27m inverse off \x1b[29m strikethrough off \x1b[30m set foreground color to black \x1b[31m set foreground color to red \x1b[32m set foreground color to green \x1b[33m set foreground color to yellow \x1b[34m set foreground color to blue \x1b[35m set foreground color to magenta (purple) \x1b[36m set foreground color to cyan \x1b[37m set foreground color to white \x1b[39m set foreground color to default (white) \x1b[40m set background color to black \x1b[41m set background color to red \x1b[42m set background color to green \x1b[43m set background color to yellow \x1b[44m set background color to blue \x1b[45m set background color to magenta (purple) \x1b[46m set background color to cyan \x1b[47m set background color to white \x1b[49m set background color to default (black) > > Thanks for your help. > > aurelien From apt.shansen at gmail.com Tue Aug 4 16:24:46 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Tue, 4 Aug 2009 13:24:46 -0700 Subject: boolean OR gotcha In-Reply-To: References: Message-ID: <7a9c25c20908041324l1a589c54q2f0f9666ab4ddd67@mail.gmail.com> > > > # Here is something different: > >>> (0 or None) == (None or 0) > False What is the actual problem? You quoted the docs, it seems very clear. (0 or None) would return None. (None or 0) would return 0. None is not equal to 0, of course. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From zuo at chopin.edu.pl Tue Aug 4 16:25:09 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 04 Aug 2009 22:25:09 +0200 Subject: boolean OR gotcha In-Reply-To: References: Message-ID: 04-08-2009 o 22:11:18 1x7y2z9 <1x7y2z9 at gmail.com> wrote: > Another one (also explainable): >>>> 0 or None == None or 0 > True > # Above is same as (operator precedence): >>>> 0 or (None == None) or 0 > True > # Here is something different: >>>> (0 or None) == (None or 0) > False I don't see any problem here. The last is ok: None != 0. *j -- Jan Kaliszewski (zuo) From kushal.kumaran+python at gmail.com Tue Aug 4 16:25:55 2009 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Wed, 5 Aug 2009 01:55:55 +0530 Subject: Online payment module In-Reply-To: References: Message-ID: <1e364c4e0908041325h5be577dq2363fba4c39af05b@mail.gmail.com> On Tue, Aug 4, 2009 at 12:41 AM, Sam Tregar wrote: > Hello all.? I'm considering building a module to provide a > cross-payment-gatewat API for making online payments.? In the Perl world we > have a module like this called Business::OnlinePayment > (http://search.cpan.org/~jasonk/Business-OnlinePayment-2.01/OnlinePayment.pm). > > Is there anything like this in Python?? My searches so far haven't turned up > anything.? If I don't find one I'll probably build one, covering PayPal and > Authorize.net to start.? If anyone is interested in discussing the project > and/or getting involved shoot me an email. > Not really familiar with this area, but have you seen these? http://code.google.com/p/pypaypal/ http://www.geteasyshop.com/front-page -- kushal From duane.kaufman at gmail.com Tue Aug 4 16:32:32 2009 From: duane.kaufman at gmail.com (DuaneKaufman) Date: Tue, 4 Aug 2009 13:32:32 -0700 (PDT) Subject: Overlap in python References: Message-ID: <2e475887-0e8d-4b34-a918-1af720c166bf@r38g2000yqn.googlegroups.com> On Aug 4, 1:15?pm, Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. ?For example, here would be my input: > > part name ? location > a ? ? ? ? ? ? ? ? ?5-9 > b ? ? ? ? ? ? ? ? ?7-10 > c ? ? ? ? ? ? ? ? ?3-6 > d ? ? ? ? ? ? ? ? ?15-20 > e ? ? ? ? ? ? ? ? ?18-23 > > And here is what I need for an output: > part name ? location > c.a.b ? ? ? ? ? ?3-10 > d.e ? ? ? ? ? ? ? 15-23 > > I've tried various methods, which all fail. ?Does anyone have an idea > how to do this? > > Thank you very much! > Jay Hi, You have gotten some excellent feedback (all without installing anything extra to your Python install), but might I suggest the use of an interval arithmetic package to aid in this? For instance the interval module found at: http://members.cox.net/apoco/interval/ can be put to use: Given your data above: > part name location > a 5-9 > b 7-10 > c 3-6 from interval import Interval >>> a_int=Interval(5,9) >>> b_int=Interval(7,10) >>> c_int=Interval(3,6) >>> a_int.overlaps(b_int) True >>> a_int.overlaps(c_int) True >>> b_int.overlaps(c_int) False Duane From 1x7y2z9 at gmail.com Tue Aug 4 16:35:02 2009 From: 1x7y2z9 at gmail.com (1x7y2z9) Date: Tue, 4 Aug 2009 13:35:02 -0700 (PDT) Subject: boolean OR gotcha References: Message-ID: Did not intend that there was a problem. Just a gotcha or a fun little titbit ... maybe. :) On Aug 4, 1:25?pm, "Jan Kaliszewski" wrote: > 04-08-2009 o 22:11:18 1x7y2z9 <1x7y... at gmail.com> wrote: > > > Another one (also explainable): > >>>> 0 or None == None or 0 > > True > > # Above is same as (operator precedence): > >>>> 0 or (None == None) or 0 > > True > > # Here is something different: > >>>> (0 or None) == (None or 0) > > False > > I don't see any problem here. > > The last is ok: None != 0. > > *j > -- > Jan Kaliszewski (zuo) From maxkhesin at gmail.com Tue Aug 4 16:45:10 2009 From: maxkhesin at gmail.com (xamdam) Date: Tue, 4 Aug 2009 13:45:10 -0700 (PDT) Subject: SDMX format Message-ID: Does anyone know of python libs for writing SDMX XML format? http://www.SDMX.org/resources/SDMXML/schemas/v2_0/common thanks, max. From bearophileHUGS at lycos.com Tue Aug 4 16:54:16 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Tue, 4 Aug 2009 13:54:16 -0700 (PDT) Subject: Overlap in python References: Message-ID: Jay Bird: > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. For example, here would be my input: > > part name location > a 5-9 > b 7-10 > c 3-6 > d 15-20 > e 18-23 > > And here is what I need for an output: > part name location > c.a.b 3-10 > d.e 15-23 That's sometimes known as "The Set Union Problem on Intervals". Knowing the name of a problem is sometimes half the work :-) People have written papers on this. This is a O(N^2) force-brute algorithm, you can try it on your data: data = """part name location a 5-9 b 7-10 c 3-6 d 15-20 e 18-23""" pairs = map(str.split, data.splitlines()[1:]) triples = [map(int, i.split("-")) + [name] for (name, i) in pairs] overlap = lambda x1,y1, x2,y2: y1 >= x2 and x1 <= y2 results = [] for (x1,y1,name) in triples: for i, res in enumerate(results): if overlap(x1,y1, res[0],res[1]): results[i].append(name) results[i][0] = min(x1, res[0]) results[i][1] = max(y1, res[1]) break else: results.append([x1, y1, name]) print results # Output: [[3, 10, 'a', 'b', 'c'], [15, 23, 'd', 'e']] If you have have a lot of data then it will be too much slow, and you have to use a more complex algorithm. If your intervals are many, they are small, and they are spread in a not too much large range of possible values, you can create an integer array of indexes, and you can "paint" intervals on it. Bye, bearophile From gregor.lingl at aon.at Tue Aug 4 16:54:16 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 22:54:16 +0200 Subject: Overlap in python In-Reply-To: <2e475887-0e8d-4b34-a918-1af720c166bf@r38g2000yqn.googlegroups.com> References: <2e475887-0e8d-4b34-a918-1af720c166bf@r38g2000yqn.googlegroups.com> Message-ID: <4a78a005$0$2301$91cee783@newsreader02.highway.telekom.at> DuaneKaufman schrieb: > On Aug 4, 1:15 pm, Jay Bird wrote: ... > For instance the interval module found at: http://members.cox.net/apoco/interval/ > can be put to use: > > Given your data above: >> part name location >> a 5-9 >> b 7-10 >> c 3-6 > > from interval import Interval >>>> a_int=Interval(5,9) >>>> b_int=Interval(7,10) >>>> c_int=Interval(3,6) >>>> a_int.overlaps(b_int) > True >>>> a_int.overlaps(c_int) > True >>>> b_int.overlaps(c_int) > False As my proposed solution shows this approach can be done with on board means of Python (namely the set type). This would be quite different though, if you had floating point boundaries of the intervals. Regards, Gregor > > Duane From gregor.lingl at aon.at Tue Aug 4 16:57:59 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 22:57:59 +0200 Subject: Overlap in python In-Reply-To: <4a78a005$0$2301$91cee783@newsreader02.highway.telekom.at> References: <2e475887-0e8d-4b34-a918-1af720c166bf@r38g2000yqn.googlegroups.com> <4a78a005$0$2301$91cee783@newsreader02.highway.telekom.at> Message-ID: <4a78a0e5$0$2301$91cee783@newsreader02.highway.telekom.at> Gregor Lingl schrieb: > > As my proposed solution shows this approach can > be done with on board means of Python (namely > the set type). This would be quite different though, > if you had floating point boundaries of the intervals. > ... or if the intgers involved were very big :-( > Regards, > Gregor > >> >> Duane From bearophileHUGS at lycos.com Tue Aug 4 17:00:37 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Tue, 4 Aug 2009 14:00:37 -0700 (PDT) Subject: Overlap in python References: <78d86d92-d373-4163-a418-600a3eb36ab3@o15g2000yqm.googlegroups.com> Message-ID: <1f284d33-256e-4a61-a59a-3c84a2cf00e6@18g2000yqa.googlegroups.com> Mark Dickinson: > # create sorted list of points where an interval is entered or left > transitions = [] > for name, (start, stop) in input: > ? ? transitions.extend([(start, 'Start', name), (stop, 'Stop', name)]) > transitions.sort() > > # scan list, accumulating blocks along the way. Oh, right, that's the usual simple solution. Silly me for showing the dumb quadratic solution :-) The "pixelmap" approach may be faster if you have tons of small intervals in a not too much large range. Bye, bearophile From dickinsm at gmail.com Tue Aug 4 17:22:01 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 4 Aug 2009 14:22:01 -0700 (PDT) Subject: Overlap in python References: <78d86d92-d373-4163-a418-600a3eb36ab3@o15g2000yqm.googlegroups.com> Message-ID: <0bf0707a-d053-4481-af26-b2a524ab0964@k19g2000yqn.googlegroups.com> On Aug 4, 9:03?pm, Mark Dickinson wrote: > for i, (pt, startend, name) in enumerate(transitions): Whoops. That line should just be: for pt, startend, name in transitions: The enumerate was accidentally left-over from a more complicated version. -- Mark From davea at ieee.org Tue Aug 4 17:34:23 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 04 Aug 2009 17:34:23 -0400 Subject: Using Python to automate builds In-Reply-To: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> Message-ID: <4A78A95F.9080209@ieee.org> Kosta wrote: > I am a Python newbie, tasked with automating (researching) building > Windows drivers using the WDK build environment. I've been looking > into Python for this (instead of writing a bunch of batch files). > > What I would like to do, is to open a cmd window, and start a Python > script. This script would then (based upon input arguments), build > different flavors of the driver (fre, chk, x86, x64) and do some post > processing (create cat files, sign, etc.). > > I was hoping to take advantage as much as possible of exisiting > infrastructure from the WDK. I am able to call setenv.bat and provide > all the input parameters. One of the things setenv.bat does is change > the path environment variable. However, this is not captured by > Python. I could duplicate the functionality, but I'd rather not. Is > there a way to capture all enviroment variable changes being made by a > batch file from Python? > > Thanks! > > An excellent question. It's been a few years, but last time I remember looking, setenv.bat only changed environment variables, and didn't change current directory, or run any external programs.. If that's still true, I figure you have three options. I don't know of any way to capture them explicitly. So here are the three choices I can come up with: 1) have the first python program invoke a new shell which runs setenv, then runs another python program. This second python program would be where all the work is done, invoking compilers, linkers etc. So the first python program invokes a batch file which looks something like: call setenv.bat arg1 python second.py arg2 arg3 arg4 arg5 This batch file could even be generated on the fly, just to simplify complex argument passing. 2) Have the python program invoke a batch file something like the following, and then analyze the resulting text file call setenv.bat arg1 set > tempfile.txt The contents of that tempfile could then be loaded into a dict similar to the usual environment. Now the Python script can continue, and just use these environment variable instead of the original set 3) Have the python program parse the setenv.bat instead of running it. There was a post on this newsgroup announcing pyKook. It's still in early form, but you might get ideas from it. I haven't looked, I just pasted the announcement to look at later. + I have released pyKook 0.0.2. + http://pypi.python.org/pypi/Kook/0.0.2 + http://www.kuwata-lab.com/kook/ + http://www.kuwata-lab.com/kook/pykook-users-guide.html Other possibilities: + http://pypi.python.org/pypi/vellum/ flexible small 'make' alternative + http://code.google.com/p/waf/ + http://code.google.com/p/fabricate/ DaveA From gdamjan at gmail.com Tue Aug 4 17:40:17 2009 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Tue, 04 Aug 2009 23:40:17 +0200 Subject: Problem in installing PyGreSQL References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> <20090804095547.a5274e22.darcy@druid.net> Message-ID: <1fmmk6-htc.ln1@archaeopteryx.softver.org.mk> >> > By the way, you don't have to be super user to install PyGreSQL. >> > You just need SU if you want to install it system wide. PyGreSQL >> > doesn't require any special privileges to run. >> >> Right, but the packages install system-wide. That's why he could >> compile it himself but not use the package. > > Exactly so don't install the package. Do "python setup.py build" and > put the three files that are built (_pg.so, pg.py and pgdb.py) into > any directory and point PYTHONPATH to it. Or.. with Python 2.6 and up, you can do: python setup.py install --user and it will install the package in users own ~/.local/lib/python2.6/site-packages/ BTW that path is configurable with the PYTHONUSERBASE environment variable. see: http://www.python.org/dev/peps/pep-0370/ -- ?????? ( http://softver.org.mk/damjan/ ) Spammers scratch here with a diamond to find my address: ||||||||||||||||||||||||||||||||||||||||||||||| From kosta.koeman at gmail.com Tue Aug 4 17:40:46 2009 From: kosta.koeman at gmail.com (Kosta) Date: Tue, 4 Aug 2009 14:40:46 -0700 (PDT) Subject: Using Python to automate builds References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> Message-ID: <48e9dcba-5309-4de6-b833-7abec18120e1@d9g2000prh.googlegroups.com> On Aug 4, 2:34?pm, Dave Angel wrote: > Kosta wrote: > > I am a Python newbie, tasked with automating (researching) building > > Windows drivers using the WDK build environment. ?I've been looking > > into Python for this (instead of writing a bunch of batch files). > > > What I would like to do, is to open a cmd window, and start a Python > > script. ?This script would then (based upon input arguments), build > > different flavors of the driver (fre, chk, x86, x64) and do some post > > processing (create cat files, sign, etc.). > > > I was hoping to take advantage as much as possible of exisiting > > infrastructure from the WDK. ?I am able to call setenv.bat and provide > > all the input parameters. ?One of the things setenv.bat does is change > > the path environment variable. ?However, this is not captured by > > Python. ?I could duplicate the functionality, but I'd rather not. ?Is > > there a way to capture all enviroment variable changes being made by a > > batch file from Python? > > > Thanks! > > An excellent question. ?It's been a few years, but last time I remember > looking, setenv.bat only changed environment variables, and didn't > change current directory, or run any external programs.. ?If that's > still true, I figure you have three options. > > I don't know of any way to capture them explicitly. ?So here are the > three choices I can come up with: > > 1) have the first python program invoke a new shell which runs setenv, > then runs another python program. ?This second python program would be > where all the work is done, invoking compilers, linkers etc. ?So the > first python program invokes a batch file which looks something like: > ? ? ? ? ? call setenv.bat ?arg1 > ? ? ? ? ? python second.py ? ?arg2 arg3 ?arg4 ?arg5 > > ?This batch file could even be generated on the fly, just to simplify > complex argument passing. > > 2) Have the python program invoke a batch file something like the > following, and then analyze the resulting text file > ? ? ? ? ? ?call setenv.bat ? arg1 > ? ? ? ? ? ?set > tempfile.txt > > The contents of that tempfile could then be loaded into a dict similar > to the usual environment. ?Now the Python script can continue, and just > use these environment variable instead of the original set > > 3) Have the python program parse the setenv.bat instead of running it. > > There was a post on this newsgroup announcing pyKook. ?It's still in > early form, but you might get ideas from it. ?I haven't looked, I just > pasted the announcement to look at later. > > + I have released pyKook 0.0.2. > +http://pypi.python.org/pypi/Kook/0.0.2 > +http://www.kuwata-lab.com/kook/ > +http://www.kuwata-lab.com/kook/pykook-users-guide.html > > Other possibilities: > + ?http://pypi.python.org/pypi/vellum/? ? ? flexible small 'make' > alternative > > + ?http://code.google.com/p/waf/ > > + ?http://code.google.com/p/fabricate/ > > DaveA- Hide quoted text - > > - Show quoted text - Thanks Dave. I had thought about those three options, and was honestly hoping for a foruth (I know, some people are never satisfied ;). I'll look into pyKook. Thank you for your help. From philip at semanchuk.com Tue Aug 4 17:52:48 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 4 Aug 2009 17:52:48 -0400 Subject: Using Python to automate builds In-Reply-To: <48e9dcba-5309-4de6-b833-7abec18120e1@d9g2000prh.googlegroups.com> References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> <48e9dcba-5309-4de6-b833-7abec18120e1@d9g2000prh.googlegroups.com> Message-ID: On Aug 4, 2009, at 5:40 PM, Kosta wrote: > On Aug 4, 2:34 pm, Dave Angel wrote: >> >> + I have released pyKook 0.0.2. >> +http://pypi.python.org/pypi/Kook/0.0.2 >> +http://www.kuwata-lab.com/kook/ >> +http://www.kuwata-lab.com/kook/pykook-users-guide.html >> >> Other possibilities: >> + http://pypi.python.org/pypi/vellum/ flexible small 'make' >> alternative >> >> + http://code.google.com/p/waf/ >> >> + http://code.google.com/p/fabricate/ >> >> DaveA- Hide quoted text - >> >> - Show quoted text - > > Thanks Dave. I had thought about those three options, and was > honestly hoping for a foruth (I know, some people are never > satisfied ;). I'll look into pyKook. Thank you for your help. Poof! Your wish is granted! =) http://www.scons.org/ Dunno if you'll find it better, worse or different than the alternatives, but there it is. have fun P From no.email at please.post Tue Aug 4 17:57:25 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 21:57:25 +0000 (UTC) Subject: Overlap in python References: Message-ID: In Jay Bird writes: >Hi everyone, >I've been trying to figure out a simple algorithm on how to combine a >list of parts that have 1D locations that overlap into a non- >overlapping list. For example, here would be my input: >part name location >a 5-9 >b 7-10 >c 3-6 >d 15-20 >e 18-23 >And here is what I need for an output: >part name location >c.a.b 3-10 >d.e 15-23 >I've tried various methods, which all fail. Does anyone have an idea >how to do this? This problem is basically isomorphic to the problem of finding connected components in an undirected graph. If your parts are nodes in a graph, there's an edge between them if they overlap. The following is probably overkill, but it works. It uses the module pygraph, which you can download from http://code.google.com/p/python-graph/ The real work is done by its connected_components function. import pygraph from pygraph.algorithms.accessibility import connected_components class Part(object): def __init__(self, name, start, finish): self.name = name if start >= finish: raise ValueError("start must be strictly less than finish") self.start = start self.finish = finish def __str__(self): return self.name def combine_parts(parts): gr = pygraph.graph() gr.add_nodes(parts) # connect the nodes for i in range(len(parts) - 1): part_i = parts[i] for j in range(i + 1, len(parts)): part_j = parts[j] if (part_j.start <= part_i.finish <= part_j.finish or part_i.start <= part_j.finish <= part_i.finish): gr.add_edge(part_i, part_j) cc = connected_components(gr) c2n = {} # build connected components as lists for k, v in cc.items(): c2n.setdefault(v, []).append(k) ret = [] for nodes in c2n.values(): nodes.sort(key=lambda x: x.start) name = '.'.join(x.name for x in nodes) start = min(x.start for x in nodes) finish = max(x.finish for x in nodes) ret.append((name, start, finish)) return ret if __name__ == '__main__': data = [Part('a', 5, 9), Part('b', 7, 10), Part('c', 3, 6), Part('d', 15, 20), Part('e', 18, 23)] print combine_parts(data) When you run the script above, the output is [('c.a.b', 3, 10), ('d.e', 15, 23)] HTH, kynn From python at mrabarnett.plus.com Tue Aug 4 18:09:33 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Aug 2009 23:09:33 +0100 Subject: Overlap in python In-Reply-To: References: Message-ID: <4A78B19D.4020306@mrabarnett.plus.com> Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. For example, here would be my input: > > part name location > a 5-9 > b 7-10 > c 3-6 > d 15-20 > e 18-23 > > And here is what I need for an output: > part name location > c.a.b 3-10 > d.e 15-23 > > I've tried various methods, which all fail. Does anyone have an idea > how to do this? > >>> parts = [(5, 9, "a"), (7, 10, "b"), (3, 6, "c"), (15, 20, "d"), (18, 23, "e")] >>> parts.sort() >>> parts [(3, 6, 'c'), (5, 9, 'a'), (7, 10, 'b'), (15, 20, 'd'), (18, 23, 'e')] >>> # Merge overlapping intervals. >>> pos = 1 >>> while pos < len(parts): # Merge the pair in parts[pos - 1 : pos + 1] if they overlap. p, q = parts[pos - 1 : pos + 1] if p[1] >= q[0]: parts[pos - 1 : pos + 1] = [(p[0], max(p[1], q[1]), p[2] + "." + q[2])] else: # They don't overlap, so try the next pair. pos += 1 >>> parts [(3, 10, 'c.a.b'), (15, 23, 'd.e')] From no.email at please.post Tue Aug 4 18:10:18 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 22:10:18 +0000 (UTC) Subject: Overlap in python References: <78d86d92-d373-4163-a418-600a3eb36ab3@o15g2000yqm.googlegroups.com> Message-ID: In <78d86d92-d373-4163-a418-600a3eb36ab3 at o15g2000yqm.googlegroups.com> Mark Dickinson writes: >On Aug 4, 7:15=A0pm, Jay Bird wrote: >> Hi everyone, >> >> I've been trying to figure out a simple algorithm on how to combine a >> list of parts that have 1D locations that overlap into a non- >> overlapping list. =A0For example, here would be my input: >> >> part name =A0 location >> a =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A05-9 >> b =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A07-10 >> c =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A03-6 >> d =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A015-20 >> e =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A018-23 >> >> And here is what I need for an output: >> part name =A0 location >> c.a.b =A0 =A0 =A0 =A0 =A0 =A03-10 >> d.e =A0 =A0 =A0 =A0 =A0 =A0 =A0 15-23 >> >> I've tried various methods, which all fail. =A0Does anyone have an idea >> how to do this? >Here's an approach that might work. Turning it into a sensible >function and parsing input/massaging output properly are left >as an exercise. Blocks that just touch (e.g. (3, 6) then (6, 9)) >are amalgamated; if this isn't what you want, and they should >be treated as separate instead, then replace 'Stop' with 'Finish' >(or any other string that sorts before 'Start'). >input =3D [ > ('a', (5, 9)), > ('b', (7, 10)), > ('c', (3, 6)), > ('d', (15, 20)), > ('e', (18, 23)), > ] ># create sorted list of points where an interval is entered or left >transitions =3D [] >for name, (start, stop) in input: > transitions.extend([(start, 'Start', name), (stop, 'Stop', name)]) >transitions.sort() ># scan list, accumulating blocks along the way. >count =3D 0 >for i, (pt, startend, name) in enumerate(transitions): > if startend =3D=3D 'Start': > if not count: > start =3D pt > names =3D [] > count +=3D 1 > names.append(name) > else: > count -=3D 1 > if not count: > print '.'.join(names), "%s--%s" % (start, pt) Very cool. kynn From bearophileHUGS at lycos.com Tue Aug 4 18:10:33 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Tue, 4 Aug 2009 15:10:33 -0700 (PDT) Subject: Overlap in python References: Message-ID: kj: > ? ? # connect the nodes > ? ? for i in range(len(parts) - 1): > ? ? ? ? part_i = parts[i] > ? ? ? ? for j in range(i + 1, len(parts)): Note that's O(N^2), see the O(sort) standard solution by Mark Dickinson. Bye, bearophile From ryniek90 at gmail.com Tue Aug 4 18:20:21 2009 From: ryniek90 at gmail.com (ryniek90) Date: Wed, 05 Aug 2009 00:20:21 +0200 Subject: How to write replace string for object which will be substituted? [regexp] In-Reply-To: References: Message-ID: <4A78B425.2010604@gmail.com> Hi. I started learning regexp, and some things goes well, but most of them still not. I've got problem with some regexp. Better post code here: " >>> import re >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> mail '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> print mail name at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = re.sub('^\n|$\n', '', mail) >>> print maail name at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = re.sub(' ', '', maail) >>> print maail name at mail.com name1[at]mail[dot]com name2[$at$]mail[$dot$]com >>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) >>> print maail name at mail.com name1 at mail[dot]com name2 at mail[$dot$]com >>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) >>> print maail name at mail.com name1 at mail.com name2 at mail.com >>> #How must i write the replace string to replace all this regexp's with just ONE command, in string 'mail' ? >>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', *?*, mail) " How must i write that replace pattern (look at question mark), to maek that substituion work? I didn't saw anything helpful while reading Re doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but something gone wrong - didn't wrote it right. Is there more user friendly HowTo for Python Re, than this? I'm new to programming an regexp, sorry for inconvenience. From jay.bird0804 at gmail.com Tue Aug 4 18:21:13 2009 From: jay.bird0804 at gmail.com (Jay Bird) Date: Tue, 4 Aug 2009 15:21:13 -0700 (PDT) Subject: Overlap in python References: <4a7892c2$0$2297$91cee783@newsreader02.highway.telekom.at> Message-ID: Hi everyone, I wanted to thank you all for your help and *excellent* discussion. I was able to utilize and embed the script by Grigor Lingl in the 6th post of this discussion to get my program to work very quickly (I had to do about 20 comparisons per data bin, with over 40K bins in total). I am involved in genomic analysis research and this problem comes up a lot and I was surprised to not have been able to find a clear way to solve it. I will also look through all the tips in this thread, I have a feeling they may come in handy for future use! Thank you again, Jay From mensanator at aol.com Tue Aug 4 18:47:16 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Aug 2009 15:47:16 -0700 (PDT) Subject: Overlap in python References: <4a7892c2$0$2297$91cee783@newsreader02.highway.telekom.at> Message-ID: <99c721fe-57fa-4508-9acb-2399ac81b9bf@k19g2000yqn.googlegroups.com> On Aug 4, 2:57?pm, Gregor Lingl wrote: > Jay Bird schrieb: > > > > > > > Hi everyone, > > > I've been trying to figure out a simple algorithm on how to combine a > > list of parts that have 1D locations that overlap into a non- > > overlapping list. ?For example, here would be my input: > > > part name ? location > > a ? ? ? ? ? ? ? ? ?5-9 > > b ? ? ? ? ? ? ? ? ?7-10 > > c ? ? ? ? ? ? ? ? ?3-6 > > d ? ? ? ? ? ? ? ? ?15-20 > > e ? ? ? ? ? ? ? ? ?18-23 > > > And here is what I need for an output: > > part name ? location > > c.a.b ? ? ? ? ? ?3-10 > > d.e ? ? ? ? ? ? ? 15-23 > > Suppose you have your data given as a dictionary: > > data = {'a':(5,9), > ? ? ? ? ?'b':(7,10), > ? ? ? ? ?'c':(3,6), > ? ? ? ? ?'d':(15,20), > ? ? ? ? ?'e':(18,23)} > > Then the following not particularly elegant > but very simple and straight forward > algorithm will solve your problem: > > def values(key): > ? ? ?return set(range(data[key][0], data[key][1]+1)) > > keys = list(data.keys()) > result = [] > while keys: > ? ? ?k = [keys[0]] > ? ? ?keys = keys[1:] > ? ? ?v = values(k[0]) > ? ? ?for l in keys[:]: > ? ? ? ? ?if v.intersection(values(l)): > ? ? ? ? ? ? ?v.update(values(l)) > ? ? ? ? ? ? ?k.append(l) > ? ? ? ? ? ? ?keys.remove(l) > ? ? ?result.append((k,v)) > > # print(result) ## if you like > > for k, v in result: > ? ? ?print(".".join(sorted(k)), "%d-%d" % (min(v), max(v))) > > Regards, > Gregor > > > > > I've tried various methods, which all fail. ?Does anyone have an idea > > how to do this? > > > Thank you very much! > > Jay I was thinking sets, too. import random def overlap(): merge_count = 0 datam.append(data.pop(0)) while len(data)>0: d0 = data.pop(0) dmi = 0 dmtemp = datam[:] while d0: dmtest = d0[1].intersection(dmtemp[dmi][1]) #print(d0,dmtemp[dmi],dmtest) if len(dmtest)>0: # overlap dmtest = d0[1].union(dmtemp[dmi][1]) datam[dmi] = (d0[0]+dmtemp[dmi][0],dmtest) d0 = None dmi = 0 merge_count += 1 else: dmi += 1 if dmi == len(dmtemp): datam.append(d0) d0 = None return merge_count # repeat until 0 returned ## OP data ##data=[] ##data.append(('a',set([i for i in range(5,9+1)]))) ##data.append(('b',set([i for i in range(7,10+1)]))) ##data.append(('c',set([i for i in range(3,6+1)]))) ##data.append(('d',set([i for i in range(15,20+1)]))) ##data.append(('e',set([i for i in range(18,23+1)]))) ##datam = [] ## ##print() ##for j in data: print(j) ##print() ## ## ##overlap() ## ##for i in datam: ## print(i[0],min(i[1]),max(i[1])) ## ## ('a', {8, 9, 5, 6, 7}) ## ('b', {8, 9, 10, 7}) ## ('c', {3, 4, 5, 6}) ## ('d', {15, 16, 17, 18, 19, 20}) ## ('e', {18, 19, 20, 21, 22, 23}) ## ## cba 3 10 ## ed 15 23 ## special case - repeat overlap test until no merges data = [('A', {79, 80, 81, 82, 83, 84, 85, 86}), ('B', {96, 89, 90, 91, 92, 93, 94, 95}), ('C', {21, 22, 23, 24, 25, 26, 27, 28}), ('D', {64, 65, 66, 67, 68, 69, 62, 63}), ('E', {72, 73, 74, 75, 76, 77, 78, 79}), ('F', {65, 66, 67, 68, 69, 70, 71, 72}), ('G', {11, 12, 13, 14, 15, 16, 17, 18}), ('H', {24, 25, 26, 27, 28, 29, 30, 31}), ('I', {32, 33, 34, 35, 36, 37, 38, 31}), ('J', {81, 82, 83, 84, 85, 86, 87, 88})] datam = [] ## ('A', {55, 56, 57, 58, 59, 60, 61, 62}) ## ('B', {64, 57, 58, 59, 60, 61, 62, 63}) ## ('C', {10, 11, 12, 13, 14, 15, 16, 17}) ## ('D', {32, 25, 26, 27, 28, 29, 30, 31}) ## ('E', {54, 55, 56, 57, 58, 59, 60, 61}) ## ('F', {64, 65, 66, 59, 60, 61, 62, 63}) ## ('G', {41, 42, 43, 44, 45, 46, 47, 48}) ## ('H', {67, 68, 69, 70, 71, 72, 73, 74}) ## ('I', {55, 56, 57, 58, 59, 60, 61, 62}) ## ('J', {64, 65, 66, 67, 68, 69, 62, 63}) ## ## JIFEBA 54 69 ## C 10 17 ## D 25 32 ## G 41 48 ## H 67 74 <--- NFG overlaps JIFEBA print() for j in data: print(j) print() merges = 1 # corrects above while merges > 0: merges = overlap() print(merges) if merges>0: data = datam[:] datam = [] for i in datam: print(i[0],min(i[1]),max(i[1])) ## corrected ## ## ('A', {79, 80, 81, 82, 83, 84, 85, 86}) ## ('B', {96, 89, 90, 91, 92, 93, 94, 95}) ## ('C', {21, 22, 23, 24, 25, 26, 27, 28}) ## ('D', {64, 65, 66, 67, 68, 69, 62, 63}) ## ('E', {72, 73, 74, 75, 76, 77, 78, 79}) ## ('F', {65, 66, 67, 68, 69, 70, 71, 72}) ## ('G', {11, 12, 13, 14, 15, 16, 17, 18}) ## ('H', {24, 25, 26, 27, 28, 29, 30, 31}) ## ('I', {32, 33, 34, 35, 36, 37, 38, 31}) ## ('J', {81, 82, 83, 84, 85, 86, 87, 88}) ## ## 5 ## 1 ## 0 ## DJFEA 62 88 ## B 89 96 ## IHC 21 38 ## G 11 18 # random sequences data = [] for j in range(12): q = random.randint(0,90) r = q+12 data.append((chr(j+65),set([x for x in range(q,r)]))) datam = [] print() for j in data: print(j) print() merges = 1 # corrects above while merges > 0: merges = overlap() print(merges) if merges>0: data = datam[:] datam = [] for i in datam: print(i[0],min(i[1]),max(i[1])) ## ('A', {3, 4, 5, 6, 7, 8, 9, 10}) ## ('B', {76, 77, 78, 79, 80, 81, 82, 83}) ## ('C', {43, 44, 45, 46, 47, 48, 49, 50}) ## ('D', {42, 43, 44, 45, 46, 47, 48, 49}) ## ('E', {23, 24, 25, 26, 27, 28, 29, 30}) ## ('F', {49, 50, 51, 52, 53, 54, 55, 56}) ## ('G', {76, 77, 78, 79, 80, 81, 82, 83}) ## ('H', {1, 2, 3, 4, 5, 6, 7, 8}) ## ('I', {37, 38, 39, 40, 41, 42, 43, 44}) ## ('J', {83, 84, 85, 86, 87, 88, 89, 90}) ## ## 6 ## 0 ## HA 1 10 ## JGB 76 90 ## IFDC 37 56 ## E 23 30 ## ('A', {64, 65, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63}) ## ('B', {34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45}) ## ('C', {16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27}) ## ('D', {70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81}) ## ('E', {64, 65, 66, 67, 56, 57, 58, 59, 60, 61, 62, 63}) ## ('F', {34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45}) ## ('G', {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}) ## ('H', {64, 65, 66, 55, 56, 57, 58, 59, 60, 61, 62, 63}) ## ('I', {44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55}) ## ('J', {64, 65, 66, 67, 68, 57, 58, 59, 60, 61, 62, 63}) ## ('K', {96, 97, 98, 99, 88, 89, 90, 91, 92, 93, 94, 95}) ## ('L', {96, 97, 98, 99, 100, 89, 90, 91, 92, 93, 94, 95}) ## ## 6 ## 1 ## 0 ## FBJIHEA 34 68 ## C 16 27 ## D 70 81 ## G 0 11 ## LK 88 100 From python at mrabarnett.plus.com Tue Aug 4 18:55:36 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Aug 2009 23:55:36 +0100 Subject: How to write replace string for object which will be substituted? [regexp] In-Reply-To: <4A78B425.2010604@gmail.com> References: <4A78B425.2010604@gmail.com> Message-ID: <4A78BC68.2020601@mrabarnett.plus.com> ryniek90 wrote: > Hi. > I started learning regexp, and some things goes well, but most of them > still not. > > I've got problem with some regexp. Better post code here: > > " > >>> import re > >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > mail [$dot$] com\n' > >>> mail > '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > com\n' > >>> print mail > > name at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > >>> maail = re.sub('^\n|$\n', '', mail) > >>> print maail > name at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > >>> maail = re.sub(' ', '', maail) > >>> print maail > name at mail.com > name1[at]mail[dot]com > name2[$at$]mail[$dot$]com > >>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > >>> print maail > name at mail.com > name1 at mail[dot]com > name2 at mail[$dot$]com > >>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > >>> print maail > name at mail.com > name1 at mail.com > name2 at mail.com > >>> #How must i write the replace string to replace all this regexp's > with just ONE command, in string 'mail' ? > >>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', > *?*, mail) > " > > How must i write that replace pattern (look at question mark), to maek > that substituion work? I didn't saw anything helpful while reading Re > doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but > something gone wrong - didn't wrote it right. > Is there more user friendly HowTo for Python Re, than this? > > I'm new to programming an regexp, sorry for inconvenience. > I don't think you can do it in one regex, nor would I want to. Just use the string's replace() method. >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> mail '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> print mail name at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = mail.strip() name at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = maail.replace(' ', '') >>> print maail name at mail.com name1[at]mail[dot]com name2[$at$]mail[$dot$]com >>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') >>> print maail name at mail.com name1 at mail[dot]com name2 at mail[$dot$]com >>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') >>> print maail name at mail.com name1 at mail.com name2 at mail.com From sam at tregar.com Tue Aug 4 19:50:29 2009 From: sam at tregar.com (Sam Tregar) Date: Tue, 4 Aug 2009 19:50:29 -0400 Subject: Online payment module In-Reply-To: <1e364c4e0908041325h5be577dq2363fba4c39af05b@mail.gmail.com> References: <1e364c4e0908041325h5be577dq2363fba4c39af05b@mail.gmail.com> Message-ID: On Tue, Aug 4, 2009 at 4:25 PM, Kushal Kumaran < kushal.kumaran+python at gmail.com > wrote: > > Not really familiar with this area, but have you seen these? > > http://code.google.com/p/pypaypal/ > http://www.geteasyshop.com/front-page > Thanks, but neither of these are remotely what I'm looking for! The first is an API for accessing PayPal, but not the one I'll be using - this one has only one release and hasn't been updated in over a year, looks basically useless. The other is a full-fledged e-commerce application, not a code library. -sam -------------- next part -------------- An HTML attachment was scrubbed... URL: From alex at moreati.org.uk Tue Aug 4 20:30:05 2009 From: alex at moreati.org.uk (Alex Willmer) Date: Tue, 4 Aug 2009 17:30:05 -0700 (PDT) Subject: New implementation of re module References: Message-ID: <380ee69c-b498-4f99-8bca-2f680dd0171b@b14g2000yqd.googlegroups.com> On Jul 27, 5:34?pm, MRAB wrote: > Hi all, > > I've been working on a new implementation of the re module. The details > are athttp://bugs.python.org/issue2636, specifically fromhttp://bugs.python.org/issue2636#msg90954. I've included a .pyd file for > Python 2.6 on Windows if you want to try it out. Firstly Matthew, thank you for all your work on this. It brings some very nice regex features to Python. I've used Christopher Arndt's post as a basis and created a package from you latest upload (issue2636-20090804.zip), which builds for Python 2.5 and 2.6. I'd like to see this on PyPI, so it's easier to install the module and your work gets wider exposure. Would this be alright and would you prefer to have control of the upload, as this is your work? Below is the setup.py, the unicodedata_db.h files are taken from the appropriate branches on svn.python.org #!/usr/bin/env python import shutil import sys from distutils.core import setup, Extension MAJOR, MINOR = sys.version_info[:2] # Copy appropriate unicodedata_db.h, not found in published includes if (MAJOR, MINOR) == (2, 6): shutil.copy('Python26/unicodedata_db.h', './') elif (MAJOR, MINOR) == (2, 5): shutil.copy('Python25/unicodedata_db.h', './') else: print "WARNING: No unicodedata_db.h prepared." setup( name='regex', version='20080804', description='Alternate regular expression module, to replace re.', author='Matthew Barnett', author_email='python at mrabarnett.nospam.plus.com', # Obsfucated url='http://bugs.python.org/issue2636', py_modules = ['regex'], ext_modules=[Extension('_regex', ['_regex.c'])], ) Sincerely, Alex Willmer From missive at hotmail.com Tue Aug 4 21:01:14 2009 From: missive at hotmail.com (Lee Harr) Date: Wed, 5 Aug 2009 05:31:14 +0430 Subject: [ANNC] pybotwar-0.4 Message-ID: pybotwar is a fun and educational game where players create computer programs to control simulated robots to compete in a battle arena. http://pybotwar.googlecode.com/ pybotwar uses pybox2d for the physical simulation, and uses pygame and pygsear for the visualization. pybotwar is released under GPLv3. Changes in pybotwar-0.4: - added display of robot status - added configuration file for easier testing of various options - remove / don't remove dead robots - robot max health - physics values (force, torque, mass, bullet speed) - add non graphics mode (for much faster resolution of battles) - fixed cannon heating going below zero _________________________________________________________________ Drag n? drop?Get easy photo sharing with Windows Live? Photos. http://www.microsoft.com/windows/windowslive/products/photos.aspx From koranthala at gmail.com Tue Aug 4 21:29:17 2009 From: koranthala at gmail.com (koranthala) Date: Tue, 4 Aug 2009 18:29:17 -0700 (PDT) Subject: My first wxPython App with Twisted Message-ID: Hi, I am creating the first GUI app (wxPython based) using Twisted. I am facing an issue which I cannot seem to solve/understand due to lack of trace or anything. I had a big app written on twisted and now I am creating a login screen to the app. The app used to work without any issues. I added the login screen and the login screen comes up. But then everything freezes up. I have to force quit the python application to get anything back. Can anyone help me solve it? The code is as follows: import wx import os import logging from twisted.internet import wxreactor wxreactor.install() from twisted.internet import reactor #Called only after wxreactor.install() from twisted.internet.task import LoopingCall import clientapp def opj(path): """ Convert paths to the platform-specific separator """ st = apply(os.path.join, tuple(path.split('/'))) if path.startswith('/'): st = '/' + st return st class APPApp(wx.App): def OnInit(self): self.frame = APPFrame(None, -1, " APP Login", size=(200, 150)) self.panel = APPPanel(self.frame,-1) #client.run method does the verification etc along with other items client = clientapp.setup_app() call = LoopingCall(client.run) call.start(.51) return True def main(): app = APPApp(0) reactor.registerWxApp(app) try: reactor.run() except StandardError: raise class APPPanel(wx.Panel): """ APP GUI PANEL The panel in which the user name and password is typed. @var ID_LOGIN: Login buttons id. When this button is clicked, the data is stored for logging. """ ID_LOGIN = wx.NewId() def __init__(self, parent, id): self.parent = parent wx.Panel.__init__(self, parent, id, size=(200,150)) self.quote = wx.StaticText(self, -1, "APP Login",wx.Point(60, 10)) wx.StaticText(self, wx.ID_ANY, "User Name ", wx.Point(20, 33)) wx.StaticText(self, wx.ID_ANY, "Password ", wx.Point(20, 58)) self.usernameBox = wx.TextCtrl(self, wx.ID_ANY, "", wx.Point(80, 31), wx.Size(100, wx.ID_ANY)) self.usernameBox.SetFocus() self.passwordBox = wx.TextCtrl(self, wx.ID_ANY, "", wx.Point(80, 56), wx.Size(100, wx.ID_ANY), style=wx.TE_PASSWORD) self.button =wx.Button(self, self.ID_LOGIN, "Login", wx.Point (60, 88)) wx.EVT_BUTTON(parent, self.ID_LOGIN, self.on_login) def on_login(self, event): username = self.usernameBox.GetString(0, 128) password = self.passwordBox.GetString(0, 128) if username and password: self.parent.on_login_click(username, password) class APPTaskBarIcon(wx.TaskBarIcon): ''' TaskBar Icon So that the application is always alive on the taskbar. 3 operations are possible, DoubleClick on the taskbar would bring up the window, right click will bring up options to restore or exit the tool. ''' TBMENU_RESTORE = wx.NewId() TBMENU_CLOSE = wx.NewId() def __init__(self, frame): wx.TaskBarIcon.__init__(self) self.frame = frame # Set the image icon = self.MakeIcon(self.frame.get_image()) self.SetIcon(icon, "APP") self.imgidx = 1 # bind some events self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarActivate) self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=self.TBMENU_RESTORE) self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=self.TBMENU_CLOSE) def CreatePopupMenu(self): """ Right Click Popup Menu This method is called by the base class when it needs to popup the menu for the default EVT_RIGHT_DOWN event. """ menu = wx.Menu() menu.Append(self.TBMENU_RESTORE, "Restore Window") menu.Append(self.TBMENU_CLOSE, "Exit APP") return menu def MakeIcon(self, img): """ Return the generated Icon. This function is required because various platforms have different requirements for the icon size. """ if "wxMSW" in wx.PlatformInfo: img = img.Scale(16, 16) elif "wxGTK" in wx.PlatformInfo: img = img.Scale(22, 22) icon = wx.IconFromBitmap(img.ConvertToBitmap() ) return icon def OnTaskBarActivate(self, evt): ''' Activation code - say DoubleClick etc. It raises the window ''' if self.frame.IsIconized(): self.frame.Iconize(False) if not self.frame.IsShown(): self.frame.Show(True) self.frame.Raise() def OnTaskBarClose(self, evt): ''' On right click and close, the frame itself is closed ''' wx.CallAfter(self.frame.Close) class APPFrame(wx.Frame): def __init__(self, parent, id, title, size=None): wx.Frame.__init__(self, parent, id, title, size=size, pos=wx.Point(400, 300)) icon = self.get_icon() self.SetIcon(icon) self.tbicon = APPTaskBarIcon(self) self.Show(True) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self.Bind(wx.EVT_ICONIZE, self.OnIconify) def on_login_click(self, username, password): self.Hide() def OnCloseWindow(self, event): if self.tbicon is not None: self.tbicon.Destroy() event.Skip() def OnIconify(self, event): self.Hide() def get_image(self): img= wx.Image(opj('client.ico'), wx.BITMAP_TYPE_ICO) return img def get_icon(self): img = self.get_image() icon = wx.IconFromBitmap(img.ConvertToBitmap() ) return icon if __name__ == '__main__': main() -------------- If somebody can help me out, I would be much obliged. From koranthala at gmail.com Tue Aug 4 21:39:49 2009 From: koranthala at gmail.com (koranthala) Date: Tue, 4 Aug 2009 18:39:49 -0700 (PDT) Subject: My first wxPython App with Twisted References: Message-ID: <15ec22f4-7bcf-4a7f-81e0-ad98004adde4@p36g2000prn.googlegroups.com> On Aug 5, 6:29?am, koranthala wrote: > Hi, > ? ?I am creating the first GUI app (wxPython based) using Twisted. > ? ?I am facing an issue which I cannot seem to solve/understand due > to lack of trace or anything. > > ? ?I had a big app written on twisted and now I am creating a login > screen to the app. > ? ?The app used to work without any issues. I added the login screen > and the login screen comes up. > ? ? But then everything freezes up. I have to force quit the python > application to get anything back. Can anyone help me solve it? > > ? ?The code is as follows: > > import wx > import os > import logging > > from twisted.internet import wxreactor > wxreactor.install() > from twisted.internet import reactor #Called only after > wxreactor.install() > from twisted.internet.task import LoopingCall > > import clientapp > > def opj(path): > ? ?""" Convert paths to the platform-specific separator """ > ? ?st = apply(os.path.join, tuple(path.split('/'))) > ? ?if path.startswith('/'): > ? ? ? ?st = '/' + st > ? ?return st > > class APPApp(wx.App): > ? ?def OnInit(self): > ? ? ? ?self.frame = APPFrame(None, -1, " APP Login", size=(200, 150)) > ? ? ? ?self.panel = APPPanel(self.frame,-1) > ? ? ? ?#client.run method does the verification etc along with other > items > ? ? ? ?client = clientapp.setup_app() > ? ? ? ?call = LoopingCall(client.run) > ? ? ? ?call.start(.51) > ? ? ? ?return True > > def main(): > ? ?app = APPApp(0) > ? ?reactor.registerWxApp(app) > ? ?try: > ? ? ? ?reactor.run() > ? ?except StandardError: > ? ? ? ?raise > > class APPPanel(wx.Panel): > ? ?""" APP GUI PANEL > > ? ?The panel in which the user name and password is typed. > ? ?@var ID_LOGIN: Login buttons id. When this button is clicked, the > data > ? ? ? ?is stored for logging. > > ? ?""" > ? ?ID_LOGIN = wx.NewId() > > ? ?def __init__(self, parent, id): > ? ? ? ?self.parent = parent > ? ? ? ?wx.Panel.__init__(self, parent, id, size=(200,150)) > ? ? ? ?self.quote = wx.StaticText(self, -1, "APP Login",wx.Point(60, > 10)) > ? ? ? ?wx.StaticText(self, wx.ID_ANY, "User Name ", wx.Point(20, 33)) > ? ? ? ?wx.StaticText(self, wx.ID_ANY, "Password ", wx.Point(20, 58)) > ? ? ? ?self.usernameBox = wx.TextCtrl(self, wx.ID_ANY, "", > wx.Point(80, 31), wx.Size(100, wx.ID_ANY)) > ? ? ? ?self.usernameBox.SetFocus() > ? ? ? ?self.passwordBox = wx.TextCtrl(self, wx.ID_ANY, "", > wx.Point(80, 56), wx.Size(100, wx.ID_ANY), style=wx.TE_PASSWORD) > ? ? ? ?self.button =wx.Button(self, self.ID_LOGIN, "Login", wx.Point > (60, 88)) > ? ? ? ?wx.EVT_BUTTON(parent, self.ID_LOGIN, self.on_login) > > ? ?def on_login(self, event): > ? ? ? ?username = self.usernameBox.GetString(0, 128) > ? ? ? ?password = self.passwordBox.GetString(0, 128) > ? ? ? ?if username and password: > ? ? ? ? ? ?self.parent.on_login_click(username, password) > > class APPTaskBarIcon(wx.TaskBarIcon): > ? ?''' TaskBar Icon > > ? ?So that the application is always alive on the taskbar. > ? ?3 operations are possible, DoubleClick on the taskbar would bring > up the > ? ?window, right click will bring up options to restore or exit the > tool. > > ? ?''' > ? ?TBMENU_RESTORE = wx.NewId() > ? ?TBMENU_CLOSE ? = wx.NewId() > > ? ?def __init__(self, frame): > ? ? ? ?wx.TaskBarIcon.__init__(self) > ? ? ? ?self.frame = frame > ? ? ? ?# Set the image > ? ? ? ?icon = self.MakeIcon(self.frame.get_image()) > ? ? ? ?self.SetIcon(icon, "APP") > ? ? ? ?self.imgidx = 1 > ? ? ? ?# bind some events > ? ? ? ?self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarActivate) > ? ? ? ?self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, > id=self.TBMENU_RESTORE) > ? ? ? ?self.Bind(wx.EVT_MENU, self.OnTaskBarClose, > id=self.TBMENU_CLOSE) > > ? ?def CreatePopupMenu(self): > ? ? ? ?""" Right Click Popup Menu > > ? ? ? ?This method is called by the base class when it needs to popup > ? ? ? ?the menu for the default EVT_RIGHT_DOWN event. > > ? ? ? ?""" > ? ? ? ?menu = wx.Menu() > ? ? ? ?menu.Append(self.TBMENU_RESTORE, "Restore Window") > ? ? ? ?menu.Append(self.TBMENU_CLOSE, "Exit APP") > ? ? ? ?return menu > > ? ?def MakeIcon(self, img): > ? ? ? ?""" Return the generated Icon. > > ? ? ? ?This function is required because various platforms have > different > ? ? ? ?requirements for the icon size. > > ? ? ? ?""" > ? ? ? ?if "wxMSW" in wx.PlatformInfo: > ? ? ? ? ? ?img = img.Scale(16, 16) > ? ? ? ?elif "wxGTK" in wx.PlatformInfo: > ? ? ? ? ? ?img = img.Scale(22, 22) > ? ? ? ?icon = wx.IconFromBitmap(img.ConvertToBitmap() ) > ? ? ? ?return icon > > ? ?def OnTaskBarActivate(self, evt): > ? ? ? ?''' Activation code - say DoubleClick etc. It raises the window > ''' > ? ? ? ?if self.frame.IsIconized(): > ? ? ? ? ? ?self.frame.Iconize(False) > ? ? ? ?if not self.frame.IsShown(): > ? ? ? ? ? ?self.frame.Show(True) > ? ? ? ?self.frame.Raise() > > ? ?def OnTaskBarClose(self, evt): > ? ? ? ?''' On right click and close, the frame itself is closed ''' > ? ? ? ?wx.CallAfter(self.frame.Close) > > class APPFrame(wx.Frame): > ? ?def __init__(self, parent, id, title, size=None): > ? ? ? ?wx.Frame.__init__(self, parent, id, title, > ? ? ? ? ? ? ? ? ? ? ? ? ?size=size, pos=wx.Point(400, 300)) > ? ? ? ?icon = self.get_icon() > ? ? ? ?self.SetIcon(icon) > ? ? ? ?self.tbicon = APPTaskBarIcon(self) > ? ? ? ?self.Show(True) > ? ? ? ?self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) > ? ? ? ?self.Bind(wx.EVT_ICONIZE, self.OnIconify) > > ? ?def on_login_click(self, username, password): > ? ? ? ?self.Hide() > > ? ?def OnCloseWindow(self, event): > ? ? ? ?if self.tbicon is not None: > ? ? ? ? ? ?self.tbicon.Destroy() > ? ? ? ?event.Skip() > > ? ?def OnIconify(self, event): > ? ? ? ?self.Hide() > > ? ?def get_image(self): > ? ? ? ?img= wx.Image(opj('client.ico'), wx.BITMAP_TYPE_ICO) > ? ? ? ?return img > > ? ?def get_icon(self): > ? ? ? ?img = self.get_image() > ? ? ? ?icon = wx.IconFromBitmap(img.ConvertToBitmap() ) > ? ? ? ?return icon > > if __name__ == '__main__': > ? ?main() > > -------------- > If somebody can help me out, I would be much obliged. Please disregard this mail. I will post a barebones version separately. From koranthala at gmail.com Tue Aug 4 21:41:40 2009 From: koranthala at gmail.com (koranthala) Date: Tue, 4 Aug 2009 18:41:40 -0700 (PDT) Subject: My first wxPython App with Twisted - barebones version Message-ID: <735ece44-08f5-4120-966f-28489299c443@o9g2000prg.googlegroups.com> Hi, I am creating the first GUI app (wxPython based) using Twisted. I am facing an issue which I cannot seem to solve/understand due to lack of trace or anything. I had a big app written on twisted and now I am creating a login screen to the app. The app used to work without any issues. I added the login screen and the login screen comes up. But then everything freezes up. I have to force quit the python application to get anything back. Can anyone help me solve it? The code is as follows: import wx import os import logging from twisted.internet import wxreactor wxreactor.install() from twisted.internet import reactor #Called only after wxreactor.install() from twisted.internet.task import LoopingCall import clientapp def opj(path): """ Convert paths to the platform-specific separator """ st = apply(os.path.join, tuple(path.split('/'))) if path.startswith('/'): st = '/' + st return st class APPApp(wx.App): def OnInit(self): self.frame = APPFrame(None, -1, " APP Login", size=(200, 150)) self.panel = APPPanel(self.frame,-1) client = clientapp.setup_app() call = LoopingCall(client.run) call.start(.51) return True def main(): app = APPApp(0) reactor.registerWxApp(app) try: reactor.run() except StandardError: raise class APPFrame(wx.Frame): def __init__(self, parent, id, title, size=None): wx.Frame.__init__(self, parent, id, title, size=size, pos=wx.Point(400, 300)) icon = self.get_icon() self.SetIcon(icon) self.Show(True) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self.Bind(wx.EVT_ICONIZE, self.OnIconify) def on_login_click(self, username, password): self.Hide() def OnCloseWindow(self, event): event.Skip() def OnIconify(self, event): self.Hide() def get_image(self): img= wx.Image(opj('client.ico'), wx.BITMAP_TYPE_ICO) return img def get_icon(self): img = self.get_image() icon = wx.IconFromBitmap(img.ConvertToBitmap() ) return icon if __name__ == '__main__': main() From geomajor56 at gmail.com Tue Aug 4 22:06:27 2009 From: geomajor56 at gmail.com (Michael Savarese) Date: Tue, 4 Aug 2009 22:06:27 -0400 Subject: os.walk() Message-ID: <75c8645a0908041906s138c1499k59cd57d569a5c83e@mail.gmail.com> Greetings Python newbie here, and thanks to all who have helped me previously. Is there a way of grabbing file attributes while traversing with os.walk()? It would be advantageous to have date modified and file size along with the file name. If anyone can point me in the right direction, I'd appreciate it. Thanks in advance Mike S -------------- next part -------------- An HTML attachment was scrubbed... URL: From erikwickstrom at gmail.com Tue Aug 4 22:37:32 2009 From: erikwickstrom at gmail.com (erikcw) Date: Tue, 4 Aug 2009 19:37:32 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? Message-ID: Hi, I'm trying to get multiprocessing to working consistently with my script. I keep getting random tracebacks with no helpful information. Sometimes it works, sometimes it doesn't. Traceback (most recent call last): File "scraper.py", line 144, in print pool.map(scrape, range(10)) File "/usr/lib/python2.6/multiprocessing/pool.py", line 148, in map return self.map_async(func, iterable, chunksize).get() File "/usr/lib/python2.6/multiprocessing/pool.py", line 422, in get raise self._value TypeError: expected string or buffer It's not always the same traceback, but they are always short like this. I'm running Python 2.6.2 on Ubuntu 9.04. Any idea how I can debug this? Thanks! Erik From clp2 at rebertia.com Tue Aug 4 22:48:45 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 Aug 2009 19:48:45 -0700 Subject: os.walk() In-Reply-To: <75c8645a0908041906s138c1499k59cd57d569a5c83e@mail.gmail.com> References: <75c8645a0908041906s138c1499k59cd57d569a5c83e@mail.gmail.com> Message-ID: <50697b2c0908041948q31a30819g29e3d7f196e94074@mail.gmail.com> On Tue, Aug 4, 2009 at 7:06 PM, Michael Savarese wrote: > Greetings > Python newbie here, and thanks to all who have helped me previously. > Is there a way of grabbing file attributes while traversing with os.walk()? > It would be advantageous to have date modified and file size along with the > file name. > If anyone can point me in the right direction, I'd appreciate it. Feed the path to os.stat(), and then use the `stat` module on the result: http://docs.python.org/library/os.html#os.stat http://docs.python.org/library/stat.html#module-stat Cheers, Chris -- http://blog.rebertia.com From koranthala at gmail.com Tue Aug 4 22:51:55 2009 From: koranthala at gmail.com (koranthala) Date: Tue, 4 Aug 2009 19:51:55 -0700 (PDT) Subject: My first wxPython App with Twisted - barebones version References: <735ece44-08f5-4120-966f-28489299c443@o9g2000prg.googlegroups.com> Message-ID: <6b487c43-814f-4130-b104-2b80795ed389@t11g2000prh.googlegroups.com> On Aug 5, 6:41?am, koranthala wrote: > Hi, > ? ?I am creating the first GUI app (wxPython based) using Twisted. > ? ?I am facing an issue which I cannot seem to solve/understand due > to lack of trace or anything. > ? ?I had a big app written on twisted and now I am creating a login > screen to the app. > ? ?The app used to work without any issues. I added the login screen > and the login screen comes up. > ? ? But then everything freezes up. I have to force quit the python > application to get anything back. Can anyone help me solve it? > ? ?The code is as follows: > > import wx > import os > import logging > > from twisted.internet import wxreactor > wxreactor.install() > from twisted.internet import reactor #Called only after > wxreactor.install() > from twisted.internet.task import LoopingCall > > import clientapp > > def opj(path): > ? ? """ Convert paths to the platform-specific separator """ > ? ? st = apply(os.path.join, tuple(path.split('/'))) > ? ? if path.startswith('/'): > ? ? ? ? st = '/' + st > ? ? return st > > class APPApp(wx.App): > ? ? def OnInit(self): > ? ? ? ? self.frame = APPFrame(None, -1, " APP Login", size=(200, 150)) > ? ? ? ? self.panel = APPPanel(self.frame,-1) > ? ? ? ? client = clientapp.setup_app() > ? ? ? ? call = LoopingCall(client.run) > ? ? ? ? call.start(.51) > ? ? ? ? return True > > def main(): > ? ? app = APPApp(0) > ? ? reactor.registerWxApp(app) > ? ? try: > ? ? ? ? reactor.run() > ? ? except StandardError: > ? ? ? ? raise > > class APPFrame(wx.Frame): > ? ? def __init__(self, parent, id, title, size=None): > ? ? ? ? wx.Frame.__init__(self, parent, id, title, > ? ? ? ? ? ? ? ? ? ? ? ? ? size=size, pos=wx.Point(400, 300)) > ? ? ? ? icon = self.get_icon() > ? ? ? ? self.SetIcon(icon) > ? ? ? ? self.Show(True) > ? ? ? ? self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) > ? ? ? ? self.Bind(wx.EVT_ICONIZE, self.OnIconify) > > ? ? def on_login_click(self, username, password): > ? ? ? ? self.Hide() > > ? ? def OnCloseWindow(self, event): > ? ? ? ? event.Skip() > > ? ? def OnIconify(self, event): > ? ? ? ? self.Hide() > > ? ? def get_image(self): > ? ? ? ? img= wx.Image(opj('client.ico'), wx.BITMAP_TYPE_ICO) > ? ? ? ? return img > > ? ? def get_icon(self): > ? ? ? ? img = self.get_image() > ? ? ? ? icon = wx.IconFromBitmap(img.ConvertToBitmap() ) > ? ? ? ? return icon > > if __name__ == '__main__': > ? ? main() Sorry for spamming this group. I found that this was due to a interaction with pyHook and the wxPython GUI. I havent solved it, but atleast it is not due to twisted and wxPython. From steve at REMOVE-THIS-cybersource.com.au Tue Aug 4 23:07:26 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Aug 2009 13:07:26 +1000 Subject: no-clobber dicts? References: Message-ID: <00027aa9$0$2969$c3e8da3@news.astraweb.com> On Wed, 5 Aug 2009 06:01 am kj wrote: > In Steven > D'Aprano writes: > >>class ConstantNamespace(dict): > > >>I also have a series of unit tests for it if you're interested in them. > > Actually, come to think of it, I think I'll take you up on this. > I'd love to see those tests. Unit testing in Python is in area I > need to work on. No problem. Here you go: http://www.cybersource.com.au/users/steve/python/constants.py Comments welcome. -- Steven From sturlamolden at yahoo.no Tue Aug 4 23:46:30 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 4 Aug 2009 20:46:30 -0700 (PDT) Subject: Is python buffer overflow proof? References: <7dnissF2bthr0U1@mid.uni-berlin.de> Message-ID: On Aug 4, 2:27?pm, Tim Chase wrote: > You *can* shoot yourself in the foot with Python, you just have > to aim much more carefully than you do with C/C++. You can e.g. define a class with a __del__ method and make some circular references. That should give you a nice memory leak. From IDOL at il.ibm.com Wed Aug 5 00:24:48 2009 From: IDOL at il.ibm.com (Ido Levy) Date: Wed, 5 Aug 2009 07:24:48 +0300 Subject: How to fetch an XML file using an HTTPS query In-Reply-To: <49b3a7400908040641l5f5daaa8v374041b7fbac442a@mail.gmail.com> References: <49b3a7400908040638h46d4e4dcxe5cd4120e9c2c7a1@mail.gmail.com> <49b3a7400908040641l5f5daaa8v374041b7fbac442a@mail.gmail.com> Message-ID: Hi Tycho, Thank you for your advice. My problem was in the query itself, I replaced every space character with '%20' and it works. You are right, the Python code below does do the work. Ido From: Tycho Andersen To: python-list at python.org Date: 04/08/2009 04:42 PM Subject: Re: How to fetch an XML file using an HTTPS query Blah, forgot to include the list. When is python-list going to get Reply-To? \t On Tue, Aug 4, 2009 at 8:38 AM, Tycho Andersen wrote: > Hi Ido, > > On Tue, Aug 4, 2009 at 6:25 AM, Ido Levy wrote: >> [snip] >> I got the following result in both cases: >> >> >> Invalid filter passed. >> > > To me, this doesn't look like a python problem: the application was > successfully connected to and returned a result. The problem you're > experiencing is that it wasn't the result you expected. Are you sure > you're setting the right headers, posting the right form values, etc. > and giving the app exactly what it wants? > > \t > -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From hjtoi-better-remove-before-reply at comcast.net Wed Aug 5 00:50:31 2009 From: hjtoi-better-remove-before-reply at comcast.net (Heikki Toivonen) Date: Tue, 04 Aug 2009 21:50:31 -0700 Subject: M2Crypto: How to generate subjectKeyIdentifier / authorityKeyIdentifier References: Message-ID: Matthias G?ntert wrote: > I am trying to add the extensions "subjectKeyIdentifier" and > "authorityKeyIdentifier" to a x509v3 certificate. M2Crypto has a couple of bugs open related that, with potential workarounds that I haven't yet deemed polished enough to checkin, but which might help you out: https://bugzilla.osafoundation.org/show_bug.cgi?id=7530 https://bugzilla.osafoundation.org/show_bug.cgi?id=12151 -- Heikki Toivonen - http://heikkitoivonen.net From nick.m.daly at gmail.com Wed Aug 5 01:06:45 2009 From: nick.m.daly at gmail.com (Nick Daly) Date: Wed, 05 Aug 2009 00:06:45 -0500 Subject: The Perils of PyContract (and Generators) Message-ID: <4A791365.50905@gmail.com> So, just in case any body else runs into this strange, strange happening, I thought I might as well document it somewhere Google can find it. Contracts for Python[0] and generators don't necessarily play well together. This mail comes in three parts, first, the example code that didn't work at all, second, a more in-depth view of the situation while you mull over the solution, and third, the answer. The trouble with this example is that even with all the (2 lines of) boilerplate code required to make PyContract work, the entire example is all of about a dozen lines long. The lines after the "post:" directive are executed every time the function returns, and if any one of them is false, PyContract raises an exception, preventing the calling code from acting on bad data: import os def find_files(name, directory="."): """Finds files with the sub-string name in the name. post: forall(__return__, lambda filename: name in filename) """ for root, dirs, files in os.walk(directory): for the_file in files: if name in the_file: yield the_file import contract contract.checkmod(__name__) That's it. We're just walking the directory and returning the next matching item in the generator when it's called. However, if we try executing this simple function in ipy (Interactive Python, not Iron Python), nothing works as you'd expect: In a directory containing 4 files: ["one fish", "two fish", "red fish", "blue fish"] >>> find_files("fish") >>> z = find_files("fish") >>> z.next() StopIteration: ... Apparently our generator object is empty whenever it's returned. When adding a print statement right before the yield, we see: >>> z = find_files("o") "one fish" "two fish" >>> z.next() StopIteration: ... Why are they printing during the function? Why is everything printing before the function even returns?? Has my python croaked? (How actors and serpents could both behave like amphibians is beyond me) The trouble is that when the yield statement is replaced with a return statement, everything works exactly as you might expect. It's perfect. Unit tests don't fail, doctests are happy, and dependent code works exactly as advertised. When you turn it back into a generator though, well, generating empty lists for everything isn't helpful. Getting irritated at it, I eventually just decided to comment out and remove as many lines as possible (11) without actually breaking the example, at which point it started working... What? The problem actually lies in the contract. Generally, the PyContract shouldn't affect the return values or in any way modify the code, which it doesn't, as long as the function returns a list values (the way the code had in fact originally been written). However, the contract mentioned above is actually quite wrong for a generator. PyContract's forall function checks every value in the list (exhausting the list) before returning it, and actually operates on the actual return value, and not a copy. Thus, when the forall function verifies all the values in the list, it's generating every value in the list, emptying the generator before it's returned. Correcting the above example involves doing nothing more than simplifying the contract: post: name in __return__ So, in conclusion, generators and PyContract's forall() function don't mix, and PyContract doesn't operate off of a copy of your parameters unless you explicitly tell it so (I don't think it ever operates off a copy of your return value). Nick 0: http://www.wayforward.net/pycontract/ From sturlamolden at yahoo.no Wed Aug 5 01:21:20 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 4 Aug 2009 22:21:20 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? References: Message-ID: <2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> On Aug 5, 4:37 am, erikcw wrote: > It's not always the same traceback, but they are always short like > this. I'm running Python 2.6.2 on Ubuntu 9.04. > > Any idea how I can debug this? In my experience, multiprocessing is fragile. Scripts tend fo fail for no obvious reason, case processes to be orphaned and linger, system- wide resource leaks, etc. For example, multiprocessing uses os._exit to stop a spawned process, even though it inevitably results in resource leaks on Linux (it should use sys.exit). Ga?l Varoquaux and I noticed this when we implemented shared memory ndarrays for numpy; we consistently got memory leaks with System V IPC for no obvious reason. Even after Jesse Noller was informed of the problem (about half a year ago), the bug still lingers. It is easy edit multiprocessing's forking.py file on you own, but bugs like this is a pain in the ass, and I suspect multiprocessing has many of them. Of course unless you show us you whole script, identifying the source of your bug will be impossible. But it may very likely be in multiprocessing as well. The quality of this module is not impressing. I am beginning to think that multiprocessing should never have made it into the Python standard library. The GIL cannot be that bad! If you can't stand the GIL, get a Unix (or Mac, Linux, Cygwin) and use os.fork. Or simply switch to a non-GIL Python: IronPython or Jython. Allow me to show you something better. With os.fork we can write code like this: class parallel(object): def __enter__(self): # call os.fork def __exit__(self, exc_type, exc_value, traceback): # call sys.exit in the child processes and # os.waitpid in the parent def __call__(self, iterable): # return different sub-subsequences depending on # child or parent status with parallel() as p: # parallel block starts here for item in p(iterable): # whatever # parallel block ends here This makes parallel code a lot cleaner than anything you can do with multiprocessing, allowing you to use constructs similar to OpenMP. Further, if you make 'parallel' a dummy context manager, you can develop and test the algorithms serially. The only drawback is that you have to use Cygwin to get os.fork on Windows, and forking will be less efficient (no copy-on-write optimization). Well, this is just one example of why Windows sucks from the perspective of the programmer. But it also shows that you can do much better by not using multiprocessing at all. The only case I can think of where multiprocessing would be usesful, is I/O bound code on Windows. But here you will almost always resort to C extension modules. For I/O bound code, Python tends to give you a 200x speed penalty over C. If you are resorting to C anyway, you can just use OpenMP in C for your parallel processing. We can thus forget about multiprocessing here as well, given that we have access to the C code. If we don't, it is still very likely that the C code releases the GIL, and we can get away with using Python threads instead of multiprocessing. IMHO, if you are using multiprocessing, you are very likely to have a design problem. Regards, Sturla From wuwei23 at gmail.com Wed Aug 5 01:45:50 2009 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 Aug 2009 22:45:50 -0700 (PDT) Subject: Announcing PythonTurtle References: Message-ID: <80f475f8-e6ea-4960-bdb8-86a90c60d656@y10g2000prf.googlegroups.com> John Posner wrote: > OK, then why the statements "from turtle import *" in the modules > turtleprocess.py and turtlewidget.py? Looking in the source I'd say it's because there's a local turtle.py. From mensanator at aol.com Wed Aug 5 01:49:16 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Aug 2009 22:49:16 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy Message-ID: I hadn't noticed this before, but the overhaul of Turtle Graphics dating back to 2.6 has been broken as far as gmpy is concerned. I hadn't noticed because I usually have tracing turned off (tracing off takes 3-4 seconds, tracing on takes 6-7 minutes). In 3.1, tracing is now a screen attribute, not a turtle atribute. I have no idea why tooter = turtle.Turtle() tooter.tracer(False) doesn't give me an error (I thought silent errors were a bad thing). Had to change to tooter = turtle.Turtle() tooter.screen.tracer(False) # tracer now a screen attribute to turn tracing off in 3.1. Naturally, having tracing on caused my program to crash. The 2.6 version seemed to work, but only because turning off tracing as a turtle attribute works in 2.6. So I turned it back on and it crashed too. 2.5 worked okay. The reason is that code in turtle.py was chabged from v2.5 if self._drawing: if self._tracing: dx = float(x1 - x0) dy = float(y1 - y0) distance = hypot(dx, dy) nhops = int(distance) to v3.1 if self._speed and screen._tracing == 1: diff = (end-start) diffsq = (diff[0]*screen.xscale)**2 + (diff[1] *screen.yscale)**2 nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed) *self._speed)) Unfortunately, that calculation of nhops is illegal if diffsq is an .mpf (gmpy floating point). Otherwise, you get Traceback (most recent call last): File "K:\user_python26\turtle\turtle_xy_Py3.py", line 95, in tooter.goto(the_coord) File "C:\Python31\lib\turtle.py", line 1771, in goto self._goto(Vec2D(*x)) File "C:\Python31\lib\turtle.py", line 3165, in _goto nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed)) ValueError: mpq.pow fractional exponent, inexact-root So when using gmpy, you have to convert the .mpz to int before calling turtle functions. (if tracing is on). demo code (fixed code commented out) import gmpy ## (even) hi----| ## | ## lo (odd) ## or ## ## (even) lo ## | ## | ## ----hi (odd) ## ## ## ## import turtle tooter = turtle.Turtle() tooter.hideturtle() tooter.speed('fast') turtle.update() # make tracer false and it works #tooter.screen.tracer(False) # tracer now a screen attribute tooter.penup() tooter.color('black') s = ['1','0'] while len(s[0])<10000: s = [''.join(s), s[0]] origin = [0,0] if s[0] == '0': tooter.goto(origin) tooter.dot(1) if s[1] == '0': tooter.goto([1,0]) tooter.dot(1) print(len(s[0])) for i,j in enumerate(s[0]): the_coord=[] cur_root = gmpy.sqrt(i) lo__root = gmpy.sqrt(i)**2 hi__root = ((gmpy.sqrt(i)+1)**2) ## cur_root = int(gmpy.sqrt(i)) ## lo__root = int(gmpy.sqrt(i)**2) ## hi__root = int(((gmpy.sqrt(i)+1)**2)) if hi__root%2==0: side = 'northeast' else: side = 'southwest' elbow = (hi__root - lo__root)//2 + lo__root + 1 if i>= elbow: side_len = i - elbow elbow_plus = True else: side_len = elbow - i elbow_plus = False if side == 'northeast': elbow_offset = [(gmpy.sqrt(elbow)-1)//2 +1,-((gmpy.sqrt(elbow)-1)// 2) +1] else: elbow_offset = [-((gmpy.sqrt(elbow)-1)//2 +1),((gmpy.sqrt (elbow)-1)//2 +1)] ## if side == 'northeast': ## elbow_offset = [int((gmpy.sqrt(elbow)-1)//2 +1),-int(((gmpy.sqrt (elbow)-1)//2) +1)] ## else: ## elbow_offset = [-int(((gmpy.sqrt(elbow)-1)//2 +1)),int (((gmpy.sqrt(elbow)-1)//2 +1))] elbow_coord = [origin[0]+elbow_offset[0],origin[1]+elbow_offset[1]] if i != hi__root and i != lo__root: if i == elbow: the_coord = elbow_coord else: if elbow_plus: if side == 'northeast': the_coord = [elbow_coord[0]-side_len,elbow_coord[1]] else: the_coord = [elbow_coord[0]+side_len,elbow_coord[1]] else: if side == 'northeast': the_coord = [elbow_coord[0],elbow_coord[1]+side_len] else: the_coord = [elbow_coord[0],elbow_coord[1]-side_len] else: if i % 2 == 0: # even square n = gmpy.sqrt(i)//2 - 1 ## n = int(gmpy.sqrt(i)//2) - 1 the_coord = [-n, -n-1] else: n = (gmpy.sqrt(i)-1)//2 - 1 ## n = int((gmpy.sqrt(i)-1)//2) - 1 the_coord = [1+n, 1+n] if j == '0': tooter.goto(the_coord) tooter.dot(2) print('done') turtle.update() turtle.done() print('done') From pfeldman at verizon.net Wed Aug 5 02:28:29 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Tue, 4 Aug 2009 23:28:29 -0700 (PDT) Subject: trouble with complex numbers Message-ID: <24821423.post@talk.nabble.com> When I try to compute the phase of a complex number, I get an error message: In [3]: from cmath import * In [4]: x=1+1J In [5]: phase(x) NameError: name 'phase' is not defined AttributeError: 'complex' object has no attribute 'phase' Any advice will be appreciated. -- View this message in context: http://www.nabble.com/trouble-with-complex-numbers-tp24821423p24821423.html Sent from the Python - python-list mailing list archive at Nabble.com. From ryniek90 at gmail.com Wed Aug 5 02:50:08 2009 From: ryniek90 at gmail.com (ryniek) Date: Tue, 4 Aug 2009 23:50:08 -0700 (PDT) Subject: How to write replace string for object which will be substituted? [regexp] References: <4A78B425.2010604@gmail.com> Message-ID: <581a0c92-3117-4712-bfac-a3b9c4f6eb97@26g2000yqk.googlegroups.com> On 5 Sie, 00:55, MRAB wrote: > ryniek90 wrote: > > Hi. > > I started learning regexp, and some things goes well, but most of them > > still not. > > > I've got problem with some regexp. Better post code here: > > > " > > ?>>> import re > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > mail [$dot$] com\n' > > ?>>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > com\n' > > ?>>> print mail > > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > ?>>> maail = re.sub('^\n|$\n', '', mail) > > ?>>> print maail > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > ?>>> maail = re.sub(' ', '', maail) > > ?>>> print maail > > n... at mail.com > > name1[at]mail[dot]com > > name2[$at$]mail[$dot$]com > > ?>>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > > ?>>> print maail > > n... at mail.com > > name1 at mail[dot]com > > name2 at mail[$dot$]com > > ?>>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > > ?>>> print maail > > n... at mail.com > > na... at mail.com > > na... at mail.com > > ?>>> #How must i write the replace string to replace all this regexp's > > with just ONE command, in string 'mail' ? > > ?>>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', > > *?*, mail) > > " > > > How must i write that replace pattern (look at question mark), to maek > > that substituion work? I didn't saw anything helpful while reading Re > > doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but > > something gone wrong - didn't wrote it right. > > Is there more user friendly HowTo for Python Re, than this? > > > I'm new to programming an regexp, sorry for inconvenience. > > I don't think you can do it in one regex, nor would I want to. Just use > the string's replace() method. > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > mail [$dot$] com\n' > ?>>> mail > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > com\n' > ?>>> print mail > > n... at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > ?>>> maail = mail.strip() > n... at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > ?>>> maail = maail.replace(' ', '') > ?>>> print maail > n... at mail.com > name1[at]mail[dot]com > name2[$at$]mail[$dot$]com > ?>>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > ?>>> print maail > n... at mail.com > name1 at mail[dot]com > name2 at mail[$dot$]com > ?>>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > ?>>> print maail > n... at mail.com > na... at mail.com > na... at mail.com Too bad, I thought that the almighty re module could do anything, but it failed with this (or maybe re can do what i want, but only few people knows how to force him to that? :P). But with help of MRAB, i choose The 3rd Point of Python's Zen - "Simple is better than complex." " >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> mail '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> print mail name at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = mail.lstrip().rstrip().replace(' ', '').replace('[dot]', '.').replace('[$dot$]', '.').replace('[at]', '@').replace('[$at$]', '@') >>> print maail name at mail.com name1 at mail.com name2 at mail.com >>> #Did it :) " Thanks again :) From ryniek90 at gmail.com Wed Aug 5 02:53:56 2009 From: ryniek90 at gmail.com (ryniek) Date: Tue, 4 Aug 2009 23:53:56 -0700 (PDT) Subject: How to write replace string for object which will be substituted? [regexp] References: <4A78B425.2010604@gmail.com> Message-ID: <45b7bc73-9c60-4da5-beda-1c2536add738@c1g2000yqi.googlegroups.com> On 5 Sie, 00:55, MRAB wrote: > ryniek90 wrote: > > Hi. > > I started learning regexp, and some things goes well, but most of them > > still not. > > > I've got problem with some regexp. Better post code here: > > > " > > ?>>> import re > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > mail [$dot$] com\n' > > ?>>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > com\n' > > ?>>> print mail > > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > ?>>> maail = re.sub('^\n|$\n', '', mail) > > ?>>> print maail > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > ?>>> maail = re.sub(' ', '', maail) > > ?>>> print maail > > n... at mail.com > > name1[at]mail[dot]com > > name2[$at$]mail[$dot$]com > > ?>>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > > ?>>> print maail > > n... at mail.com > > name1 at mail[dot]com > > name2 at mail[$dot$]com > > ?>>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > > ?>>> print maail > > n... at mail.com > > na... at mail.com > > na... at mail.com > > ?>>> #How must i write the replace string to replace all this regexp's > > with just ONE command, in string 'mail' ? > > ?>>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', > > *?*, mail) > > " > > > How must i write that replace pattern (look at question mark), to maek > > that substituion work? I didn't saw anything helpful while reading Re > > doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but > > something gone wrong - didn't wrote it right. > > Is there more user friendly HowTo for Python Re, than this? > > > I'm new to programming an regexp, sorry for inconvenience. > > I don't think you can do it in one regex, nor would I want to. Just use > the string's replace() method. > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > mail [$dot$] com\n' > ?>>> mail > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > com\n' > ?>>> print mail > > n... at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > ?>>> maail = mail.strip() > n... at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > ?>>> maail = maail.replace(' ', '') > ?>>> print maail > n... at mail.com > name1[at]mail[dot]com > name2[$at$]mail[$dot$]com > ?>>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > ?>>> print maail > n... at mail.com > name1 at mail[dot]com > name2 at mail[$dot$]com > ?>>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > ?>>> print maail > n... at mail.com > na... at mail.com > na... at mail.com Too bad, I thought that the almighty re module could do anything, but it failed with this (or maybe re can do what i want, but only few people knows how to force him to that? :P). But with help of MRAB, i choose The 3rd Point of Python's Zen - "Simple is better than complex." " >>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> mail '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> print mail n... at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = mail.lstrip().rstrip().replace(' ', '').replace('[dot]', '.').replace('[$dot$]', '.').replace('[at]', '@').replace('[$at$]', '@') >>> print maail n... at mail.com na... at mail.com na... at mail.com >>> #Did it :) " Thanks again :) From casevh at gmail.com Wed Aug 5 02:54:12 2009 From: casevh at gmail.com (casevh) Date: Tue, 4 Aug 2009 23:54:12 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy References: Message-ID: On Aug 4, 10:49?pm, Mensanator wrote: > I hadn't noticed this before, but the overhaul of Turtle Graphics > dating > back to 2.6 has been broken as far as gmpy is concerned. > The reason is that code in turtle.py was chabged from > > v2.5 > ? ? ? ? if self._drawing: > ? ? ? ? ? ? if self._tracing: > ? ? ? ? ? ? ? ? dx = float(x1 - x0) > ? ? ? ? ? ? ? ? dy = float(y1 - y0) > ? ? ? ? ? ? ? ? distance = hypot(dx, dy) > ? ? ? ? ? ? ? ? nhops = int(distance) > > to > > v3.1 > ? ? ? ?if self._speed and screen._tracing == 1: > ? ? ? ? ? ? diff = (end-start) > ? ? ? ? ? ? diffsq = (diff[0]*screen.xscale)**2 + (diff[1] > *screen.yscale)**2 > ? ? ? ? ? ? nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed) > *self._speed)) > > Unfortunately, that calculation of nhops is illegal if diffsq is > an .mpf (gmpy > floating point). Otherwise, you get > > Traceback (most recent call last): > ? File "K:\user_python26\turtle\turtle_xy_Py3.py", line 95, in > > ? ? tooter.goto(the_coord) > ? File "C:\Python31\lib\turtle.py", line 1771, in goto > ? ? self._goto(Vec2D(*x)) > ? File "C:\Python31\lib\turtle.py", line 3165, in _goto > ? ? nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed)) > ValueError: mpq.pow fractional exponent, inexact-root > Warning: Completely untested fix ahead! What happens if you change turtle.py to use nhops=1+int((math.sqrt(diffsq)/(3*math.pow(1.1, self._speed) *self._speed)) casevh From steve at REMOVE-THIS-cybersource.com.au Wed Aug 5 03:19:52 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Aug 2009 17:19:52 +1000 Subject: Turtle Graphics are incompatible with gmpy References: Message-ID: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> On Wed, 5 Aug 2009 03:49 pm Mensanator wrote: > In 3.1, tracing is now a screen attribute, not a turtle atribute. > I have no idea why > > tooter = turtle.Turtle() > tooter.tracer(False) > > doesn't give me an error (I thought silent errors were a bad thing). What makes it an error? Do you consider the following an error? >>> class Test: ... pass ... >>> t = Test() >>> t.tracer = 5 >>> Perhaps you mean, it's an API change you didn't know about, and you wish to protest that Turtle Graphics made an incompatible API change without telling you? > Naturally, having tracing on caused my program to crash. It seg faulted or raised an exception? [...] > Unfortunately, that calculation of nhops is illegal if diffsq is > an .mpf (gmpy floating point). Otherwise, you get How does diffsq get to be a mpf? Are gmpy floats supposed to be supported? -- Steven From gregor.lingl at aon.at Wed Aug 5 03:21:44 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Wed, 05 Aug 2009 09:21:44 +0200 Subject: Turtle Graphics are incompatible with gmpy In-Reply-To: References: Message-ID: <4a793315$0$2305$91cee783@newsreader02.highway.telekom.at> Mensanator schrieb: > I hadn't noticed this before, but the overhaul of Turtle Graphics > dating > back to 2.6 has been broken as far as gmpy is concerned. > > I hadn't noticed because I usually have tracing turned off (tracing > off > takes 3-4 seconds, tracing on takes 6-7 minutes). > > In 3.1, tracing is now a screen attribute, not a turtle atribute. > I have no idea why > > tooter = turtle.Turtle() > tooter.tracer(False) > > doesn't give me an error (I thought silent errors were a bad thing). > Hi, on my machine I get: Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import turtle >>> tooter = turtle.Turtle() >>> tooter.tracer(False) Traceback (most recent call last): File "", line 1, in tooter.tracer(False) AttributeError: 'Turtle' object has no attribute 'tracer' >>> I'd like to help with your problem but I'd much better be able to analyze it, if I had a version of your script, which works as you intended with Python 2.5 and the old turtle module. Could you please post it? (The one you posted below uses some commands of the turtle 2.6 module which are not present in 2.5, so it doesn't run with Python 2.5) Regards, Gregor > Had to change to > > tooter = turtle.Turtle() > tooter.screen.tracer(False) # tracer now a screen attribute > > to turn tracing off in 3.1. > > Naturally, having tracing on caused my program to crash. The 2.6 > version > seemed to work, but only because turning off tracing as a turtle > attribute > works in 2.6. > > So I turned it back on and it crashed too. > > 2.5 worked okay. > > The reason is that code in turtle.py was chabged from > > v2.5 > if self._drawing: > if self._tracing: > dx = float(x1 - x0) > dy = float(y1 - y0) > distance = hypot(dx, dy) > nhops = int(distance) > > to > > v3.1 > if self._speed and screen._tracing == 1: > diff = (end-start) > diffsq = (diff[0]*screen.xscale)**2 + (diff[1] > *screen.yscale)**2 > nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed) > *self._speed)) > > Unfortunately, that calculation of nhops is illegal if diffsq is > an .mpf (gmpy > floating point). Otherwise, you get > > Traceback (most recent call last): > File "K:\user_python26\turtle\turtle_xy_Py3.py", line 95, in > > tooter.goto(the_coord) > File "C:\Python31\lib\turtle.py", line 1771, in goto > self._goto(Vec2D(*x)) > File "C:\Python31\lib\turtle.py", line 3165, in _goto > nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed)) > ValueError: mpq.pow fractional exponent, inexact-root > > So when using gmpy, you have to convert the .mpz to int before calling > turtle > functions. (if tracing is on). > > demo code (fixed code commented out) > > import gmpy > > ## (even) hi----| > ## | > ## lo (odd) > ## or > ## > ## (even) lo > ## | > ## | > ## ----hi (odd) > ## > ## > ## > ## > > import turtle > > tooter = turtle.Turtle() > > tooter.hideturtle() > tooter.speed('fast') > turtle.update() > # make tracer false and it works > #tooter.screen.tracer(False) # tracer now a screen attribute > tooter.penup() > tooter.color('black') > > s = ['1','0'] > while len(s[0])<10000: > s = [''.join(s), s[0]] > > > origin = [0,0] > if s[0] == '0': > tooter.goto(origin) > tooter.dot(1) > if s[1] == '0': > tooter.goto([1,0]) > tooter.dot(1) > > print(len(s[0])) > > for i,j in enumerate(s[0]): > the_coord=[] > cur_root = gmpy.sqrt(i) > lo__root = gmpy.sqrt(i)**2 > hi__root = ((gmpy.sqrt(i)+1)**2) > ## cur_root = int(gmpy.sqrt(i)) > ## lo__root = int(gmpy.sqrt(i)**2) > ## hi__root = int(((gmpy.sqrt(i)+1)**2)) > > if hi__root%2==0: > side = 'northeast' > else: > side = 'southwest' > > elbow = (hi__root - lo__root)//2 + lo__root + 1 > > if i>= elbow: > > side_len = i - elbow > elbow_plus = True > else: > side_len = elbow - i > elbow_plus = False > > if side == 'northeast': > elbow_offset = [(gmpy.sqrt(elbow)-1)//2 +1,-((gmpy.sqrt(elbow)-1)// > 2) +1] > else: > elbow_offset = [-((gmpy.sqrt(elbow)-1)//2 +1),((gmpy.sqrt > (elbow)-1)//2 +1)] > ## if side == 'northeast': > ## elbow_offset = [int((gmpy.sqrt(elbow)-1)//2 +1),-int(((gmpy.sqrt > (elbow)-1)//2) +1)] > ## else: > ## elbow_offset = [-int(((gmpy.sqrt(elbow)-1)//2 +1)),int > (((gmpy.sqrt(elbow)-1)//2 +1))] > > elbow_coord = [origin[0]+elbow_offset[0],origin[1]+elbow_offset[1]] > > if i != hi__root and i != lo__root: > if i == elbow: > the_coord = elbow_coord > else: > if elbow_plus: > if side == 'northeast': > the_coord = [elbow_coord[0]-side_len,elbow_coord[1]] > else: > the_coord = [elbow_coord[0]+side_len,elbow_coord[1]] > else: > if side == 'northeast': > the_coord = [elbow_coord[0],elbow_coord[1]+side_len] > else: > the_coord = [elbow_coord[0],elbow_coord[1]-side_len] > else: > if i % 2 == 0: # even square > n = gmpy.sqrt(i)//2 - 1 > ## n = int(gmpy.sqrt(i)//2) - 1 > the_coord = [-n, -n-1] > else: > n = (gmpy.sqrt(i)-1)//2 - 1 > ## n = int((gmpy.sqrt(i)-1)//2) - 1 > the_coord = [1+n, 1+n] > if j == '0': > tooter.goto(the_coord) > tooter.dot(2) > print('done') > > turtle.update() > turtle.done() > print('done') From steve at REMOVE-THIS-cybersource.com.au Wed Aug 5 03:23:29 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Aug 2009 17:23:29 +1000 Subject: The Perils of PyContract (and Generators) References: Message-ID: <0002b6ac$0$2970$c3e8da3@news.astraweb.com> On Wed, 5 Aug 2009 03:06 pm Nick Daly wrote: > The problem actually lies in the contract. Generally, the PyContract > shouldn't affect the return values or in any way modify the code, which > it doesn't, as long as the function returns a list values (the way the > code had in fact originally been written). However, the contract > mentioned above is actually quite wrong for a generator. Yes, because you are conflating the items yielded from the generator with the generator object returned from the generator function "find_files". You can't look inside the generator object without using up whichever items you look at. [...] > Correcting the above example involves doing nothing more than > simplifying the contract: > > post: > name in __return__ That can't be right, not unless PyContract is doing something I don't expect. I expect that would be equivalent of: 'fish' in which should fail: >>> __return__ = find_files('fish') # a generator object >>> 'fish' in __return__ False >>> >>> __return__ = find_files('fish') >>> __return__ = list(__return__) >>> 'fish' in __return__ False >>> __return__ ['one fish', 'two fish', 'red fish', 'blue fish'] Of course, I may be mistaking what PyContract is doing. -- Steven From rays at blue-cove.com Wed Aug 5 03:25:03 2009 From: rays at blue-cove.com (RayS) Date: Wed, 05 Aug 2009 00:25:03 -0700 Subject: Cypress FX2 - py libusb code? Message-ID: <5.2.1.1.2.20090804224315.01c22b60@pop-server.san.rr.com> An HTML attachment was scrubbed... URL: From gregor.lingl at aon.at Wed Aug 5 03:37:08 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Wed, 05 Aug 2009 09:37:08 +0200 Subject: Turtle Graphics are incompatible with gmpy In-Reply-To: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> Message-ID: <4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> Steven D'Aprano schrieb: > On Wed, 5 Aug 2009 03:49 pm Mensanator wrote: > >> In 3.1, tracing is now a screen attribute, not a turtle atribute. >> I have no idea why >> >> tooter = turtle.Turtle() >> tooter.tracer(False) >> >> doesn't give me an error (I thought silent errors were a bad thing). > > What makes it an error? Do you consider the following an error? > >>>> class Test: > ... pass > ... >>>> t = Test() >>>> t.tracer = 5 >>>> > > Perhaps you mean, it's an API change you didn't know about, and you wish to > protest that Turtle Graphics made an incompatible API change without > telling you? > It didn't form 2.5 to 2.6 (at least not intentionally). But with the indroduction of the TurtleScreen class and the Screen class/object (singleton) a few of the turtle methods were also implemented as screen methods and as turtle methods declared deprecated (see docs of Python 2.6). These deprecated turtle methods do not occur as turtle methods any more in Python 3.x. Among them is the tracer method, which in fact does not control single turtle objects but all the turtles on a given screen. So there is an icompatibility beween 2.6 and 3.x But as far as I have understood, this doesn't concern the problem reported by mensator. Regards, Gregor > >> Naturally, having tracing on caused my program to crash. > > It seg faulted or raised an exception? > > > [...] >> Unfortunately, that calculation of nhops is illegal if diffsq is >> an .mpf (gmpy floating point). Otherwise, you get > > How does diffsq get to be a mpf? Are gmpy floats supposed to be supported? > > > From news123 at free.fr Wed Aug 5 03:44:18 2009 From: news123 at free.fr (News123) Date: Wed, 05 Aug 2009 09:44:18 +0200 Subject: merge two png pic In-Reply-To: <72d7aad1-1fb7-4b32-a87f-636505b0faa2@v15g2000prn.googlegroups.com> References: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> <4a77e249$0$2449$426a74cc@news.free.fr> <72d7aad1-1fb7-4b32-a87f-636505b0faa2@v15g2000prn.googlegroups.com> Message-ID: <4a793852$0$19598$426a74cc@news.free.fr> You didn't really tell us why you need one big file, which contains more pixel, than you can probably store in RAM Is it for printing? Not knwoing your goal makes it difficult to suggest solutions. Can't you use other image formats like raw RGB or What other image formats are supported? tiff? Raw? PPM ( http://en.wikipedia.org/wiki/Portable_pixmap )? concatenating raw/ppm files with the same width would be really trivial. so you could use python to create horizontal raw/ppm stripes. then you could concatenate them without having to have the whole image in RAM. Perhaps there's even converters from ppm to png, that don't need the whole image in RAM. cocobear wrote: > On Aug 4, 3:24 pm, News123 wrote: >> Hi, >> >> >> >> >> >> cocobear wrote: >>>>>>> Map = Image.new("RGB", (x,y)) >>>>>>> Map.paste(im, box) >>>>>>> Map.paste(im1,box) >>>>>>> Map = Map.convert("L", optimize=True, palette=Image.ADAPTIVE) >>>>>>> But if thetwopngpicis too big , or if I have tomergemorepic >>>>>>> together, I will get MemoryError: >>>>>>>>>>>>> Image.new("RGB",(44544,38656)) >>>> What do you want to do with such a big image? You will run into the same >>>> limitation when you are trying to display it. >>> I want to download a map from google map with high precision >> For me it sounds strange to handle such big files. >> >> Is the map you download from Google really that big? >> Mostly Google maps uses normally tiles of sizes 256x256 pixel, wich you >> have to compose to get the big image. >> > > The map I downloaded from Google is small(256x256). These small maps > will compose a big image. > > > >> If your problem is to combine tiles with different palettes, then you >> should pobably look at a way to 'unify' the palette of all tiles befor >> combining them. >> > > I think it is impossible to 'unify' all this tiles. > > >> Being no expert of PIL I don't know whether this is easily possible though? >> >> bye >> >> N > From hendrik at microcorp.co.za Wed Aug 5 03:56:33 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 5 Aug 2009 09:56:33 +0200 Subject: Using Python to automate builds In-Reply-To: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> Message-ID: <200908050956.33995.hendrik@microcorp.co.za> On Tuesday 04 August 2009 21:13:10 Kosta wrote: > I am a Python newbie, tasked with automating (researching) building > Windows drivers using the WDK build environment. I've been looking > into Python for this (instead of writing a bunch of batch files). > Why do you not use make and a makefile - it was designed to do exactly this. - Hendrik From fafounet at gmail.com Wed Aug 5 04:08:14 2009 From: fafounet at gmail.com (Fafounet) Date: Wed, 5 Aug 2009 01:08:14 -0700 (PDT) Subject: Special chars with HTMLParser Message-ID: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com> Hello, I am parsing a web page with special chars such as é (which stands for ?). I know I can have the unicode character ? from unicode ("\xe9","iso-8859-1") but with those extra characters I don' t know. I tried to implement handle_charref within HTMLParser without success. Furthermore, if I have the data abécd, handle_data will get "ab", handle_charref will get xe9 and then handle_data doesn't have the end of the string ("cd"). Thank you for your help, Fabien From clp2 at rebertia.com Wed Aug 5 04:40:59 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 5 Aug 2009 01:40:59 -0700 Subject: trouble with complex numbers In-Reply-To: <24821423.post@talk.nabble.com> References: <24821423.post@talk.nabble.com> Message-ID: <50697b2c0908050140g3acd8a8cx9fc87af12ea77c31@mail.gmail.com> On Tue, Aug 4, 2009 at 11:28 PM, Dr. Phillip M. Feldman wrote: > > When I try to compute the phase of a complex number, I get an error message: > > In [3]: from cmath import * > In [4]: x=1+1J > In [5]: phase(x) > > NameError: name 'phase' is not defined > > AttributeError: 'complex' object has no attribute 'phase' I suspect the problem lies in what you snipped away: In [1]: from cmath import phase In [2]: x=1+1J In [3]: phase(x) Out[3]: 0.78539816339744828 Cheers, Chris -- http://blog.rebertia.com From wuwei23 at gmail.com Wed Aug 5 04:43:13 2009 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Aug 2009 01:43:13 -0700 (PDT) Subject: trouble with complex numbers References: Message-ID: On Aug 5, 4:28?pm, "Dr. Phillip M. Feldman" wrote: > When I try to compute the phase of a complex number, I get an error message: > [...] > Any advice will be appreciated. 1. What version of Python are you using, and on what platform? 2. What you snipped is necessary to help debug your problem. 3. Do you have a cmath.py in the folder you're running the interpreter in? From sanu1267 at gmail.com Wed Aug 5 05:03:51 2009 From: sanu1267 at gmail.com (sanju ps) Date: Wed, 5 Aug 2009 14:33:51 +0530 Subject: Launch my application if its not running Message-ID: <2b76be80908050203o5d002a8draf4c8bed564eef2b@mail.gmail.com> How to check whether my gui application is running or not.If its already running i have to quit my program other wise i need to launch my program. Can anybody suggest a solution to this Regards Sanju -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed Aug 5 05:07:14 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 5 Aug 2009 02:07:14 -0700 Subject: Launch my application if its not running In-Reply-To: <2b76be80908050203o5d002a8draf4c8bed564eef2b@mail.gmail.com> References: <2b76be80908050203o5d002a8draf4c8bed564eef2b@mail.gmail.com> Message-ID: <50697b2c0908050207h7f2a866fuf63e843a66a7030d@mail.gmail.com> On Wed, Aug 5, 2009 at 2:03 AM, sanju ps wrote: > How to check whether my gui application is running or not.If its already > running i have to quit my program other wise i need to launch my program. > Can anybody suggest a solution to this Use a lock file? http://en.wikipedia.org/wiki/Lock_file#Lock_files Cheers, Chris -- http://blog.rebertia.com From smpoojary at gmail.com Wed Aug 5 05:11:38 2009 From: smpoojary at gmail.com (Mahesh Poojary S) Date: Wed, 5 Aug 2009 02:11:38 -0700 (PDT) Subject: socket.inet_ntop, and pton question In-Reply-To: <12rpns1tkp0e34@corp.supernews.com> References: <12rpns1tkp0e34@corp.supernews.com> Message-ID: <24823395.post@talk.nabble.com> Martin-298 wrote: > > Hi > > Are these functions (inet_ntop(), inet_pton()) from the socket library > supported on Windows. > > If not is there an equivalent for them using Windows > > Ive seen mention of people creating their own in order to use them > > Appreciate the help > > ty > -- > http://mail.python.org/mailman/listinfo/python-list > > You can use the below code: def inet_ntop(address_family, packed_ip): if address_family != AF_INET: raise socket.error, (97, 'Address family not supported by protocol') lIP = [] for ch in packed_ip: lIP.append(str(ord(ch))) strIP = string.join(lIP,'.') return strIP def inet_pton(address_family, ip_string): if address_family != AF_INET: raise socket.error, (97, 'Address family not supported by protocol') lIP = ip_string.split('.') strHexIP = "" for i in lIP: if i == '': continue strHex = "%x" % int(i) strHex = strHex.zfill(2) strHexIP += "\\x"+strHex return strHexIP -- View this message in context: http://www.nabble.com/socket.inet_ntop%2C-and-pton-question-tp8677935p24823395.html Sent from the Python - python-list mailing list archive at Nabble.com. From lists at cheimes.de Wed Aug 5 05:21:18 2009 From: lists at cheimes.de (Christian Heimes) Date: Wed, 05 Aug 2009 11:21:18 +0200 Subject: trouble with complex numbers In-Reply-To: <24821423.post@talk.nabble.com> References: <24821423.post@talk.nabble.com> Message-ID: Dr. Phillip M. Feldman wrote: > When I try to compute the phase of a complex number, I get an error message: > > In [3]: from cmath import * > In [4]: x=1+1J > In [5]: phase(x) > > NameError: name 'phase' is not defined > > AttributeError: 'complex' object has no attribute 'phase' > > Any advice will be appreciated. phase() has been added to Python 2.6 and 3.0. It's not available in Python 2.5 and earlier. If you'd used cmath.phase() instead of the ugly "from cmath import *" statement you'd have seen the correct error message. You can write your own phase() function. This function is mostly correct unless either the real and/or the imag part is NaN or INF. from math import atan2 def phase(z): z += 1j # convert int, long, float to complex return atan2(z.imag, z.real) From Tribulations at Paralleles.invalid Wed Aug 5 06:13:00 2009 From: Tribulations at Paralleles.invalid (TP) Date: Wed, 05 Aug 2009 12:13:00 +0200 Subject: intricated functions: how to share a variable Message-ID: Hi everybody, See the following example: ######### def tutu(): def toto(): print a a = 4 print a a=2 toto() tutu() ########## I obtain the following error: "UnboundLocalError: local variable 'a' referenced before assignment" This is because Python looks in the local context before looking in the global context. The use of "global a" in toto() does not help because global allows to force Python to look for the variable at the module level. So, how to share a variable between intricated functions? Thanks a lot Julien -- python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\ 9&1+,\'Z4(55l4('])" "When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong." (first law of AC Clarke) From albert at spenarnc.xs4all.nl Wed Aug 5 06:35:18 2009 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 05 Aug 2009 10:35:18 GMT Subject: Overlap in python References: Message-ID: In article , Jay Bird wrote: >Hi everyone, > >I've been trying to figure out a simple algorithm on how to combine a >list of parts that have 1D locations that overlap into a non- >overlapping list. For example, here would be my input: > >part name location >a 5-9 >b 7-10 >c 3-6 >d 15-20 >e 18-23 > >And here is what I need for an output: >part name location >c.a.b 3-10 >d.e 15-23 > >I've tried various methods, which all fail. Does anyone have an idea >how to do this? That is an algorithmic question and has little to do with Python. You could proceed as follows: - Order your data by the lower limit - Combine everything with the same lower limit. - Then combine every pair of consecutive entries that overlap. (In you case the second step is not needed.) > >Thank you very much! >Jay -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From deets at nospam.web.de Wed Aug 5 06:39:54 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Aug 2009 12:39:54 +0200 Subject: intricated functions: how to share a variable References: Message-ID: <7dt5rqF2crv46U1@mid.uni-berlin.de> TP wrote: > Hi everybody, > > See the following example: > > ######### > def tutu(): > > def toto(): > > print a > a = 4 > print a > > a=2 > toto() > > tutu() > ########## > > I obtain the following error: > "UnboundLocalError: local variable 'a' referenced before assignment" > > This is because Python looks in the local context before looking in the > global context. > > The use of "global a" in toto() does not help because global allows to > force Python to look for the variable at the module level. > > So, how to share a variable between intricated functions? You could use a class :) Another often used trick is to have a mutable container-object, like this: def tutu(): a = [2] def toto(): a[0] = 4 toto() Diez From clp2 at rebertia.com Wed Aug 5 06:42:23 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 5 Aug 2009 03:42:23 -0700 Subject: intricated functions: how to share a variable In-Reply-To: References: Message-ID: <50697b2c0908050342t5ae6feaauc757021a71521b2a@mail.gmail.com> On Wed, Aug 5, 2009 at 3:13 AM, TP wrote: > Hi everybody, > > See the following example: > > ######### > def tutu(): > > ? ?def toto(): > nonlocal a #note: this requires a rather recent version of python > ? ? ? ?print a > ? ? ? ?a = 4 > ? ? ? ?print a > > ? ?a=2 > ? ?toto() > > tutu() > ########## > > I obtain the following error: > "UnboundLocalError: local variable 'a' referenced before assignment" > > This is because Python looks in the local context before looking in the > global context. > > The use of "global a" in toto() does not help because global allows to force > Python to look for the variable at the module level. > > So, how to share a variable between intricated functions? Details: http://www.python.org/dev/peps/pep-3104/ Cheers, Chris -- http://blog.rebertia.com From bearophileHUGS at lycos.com Wed Aug 5 06:42:58 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Wed, 5 Aug 2009 03:42:58 -0700 (PDT) Subject: Overlap in python References: Message-ID: <4f5f1301-d160-4b61-926d-782277b064e9@r38g2000yqn.googlegroups.com> Albert van der Horst: >That is an algorithmic question and has little to do with Python.< Yes, but comp.lang.python isn't comp.lang.c, that kind of questions are perfectly fine here. They help keep this place from becoming boring. Bye, bearophile From __peter__ at web.de Wed Aug 5 06:46:28 2009 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Aug 2009 12:46:28 +0200 Subject: intricated functions: how to share a variable References: Message-ID: TP wrote: > Hi everybody, > > See the following example: > > ######### > def tutu(): > > def toto(): > > print a > a = 4 > print a > > a=2 > toto() > > tutu() > ########## > > I obtain the following error: > "UnboundLocalError: local variable 'a' referenced before assignment" > > This is because Python looks in the local context before looking in the > global context. > > The use of "global a" in toto() does not help because global allows to > force Python to look for the variable at the module level. > > So, how to share a variable between intricated functions? This limitation is removed in Python 3 with the 'nonlocal' statement: >>> def outer(): ... def inner(): ... nonlocal a ... print(a) ... a = 4 ... print(a) ... a = 2 ... inner() ... print(a) ... >>> outer() 2 4 4 Peter From bearophileHUGS at lycos.com Wed Aug 5 06:47:19 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Wed, 5 Aug 2009 03:47:19 -0700 (PDT) Subject: intricated functions: how to share a variable References: Message-ID: <9a937d26-2375-4836-9824-d34d9f92d284@o15g2000yqm.googlegroups.com> TP: > def tutu(): > > ? ? def toto(): > > ? ? ? ? print a > ? ? ? ? a = 4 > ? ? ? ? print a > > ? ? a=2 > ? ? toto() > > tutu() > ########## > > I obtain the following error: > "UnboundLocalError: local variable 'a' referenced before assignment" > > This is because Python looks in the local context before looking in the > global context. > > The use of "global a" in toto() does not help because global allows to force > Python to look for the variable at the module level. > > So, how to share a variable between intricated functions? Generally your purpose as a programmer is to write the least intricate code. Because the less tricky it is, the more readable it becomes and also the bug count decreases. So probably a better solution is to just use the normal function semantics: you pass them an argument and you take an argument as return value. Such return value will be the new version of the value you talk about. Python3+ has the "nonlocal" statement that may do what you ask for. But as many other things in Python it must be used with judgment, to avoid writing intricate code. Bye, bearophile From marcusw at cox.net Wed Aug 5 07:13:23 2009 From: marcusw at cox.net (Marcus Wanner) Date: Wed, 05 Aug 2009 07:13:23 -0400 Subject: Overlap in python In-Reply-To: <4A78B19D.4020306@mrabarnett.plus.com> References: <4A78B19D.4020306@mrabarnett.plus.com> Message-ID: On 8/4/2009 6:09 PM, MRAB wrote: > >>> parts = [(5, 9, "a"), (7, 10, "b"), (3, 6, "c"), (15, 20, "d"), > (18, 23, "e")] > >>> parts.sort() > >>> parts > [(3, 6, 'c'), (5, 9, 'a'), (7, 10, 'b'), (15, 20, 'd'), (18, 23, 'e')] > >>> # Merge overlapping intervals. > >>> pos = 1 > >>> while pos < len(parts): > # Merge the pair in parts[pos - 1 : pos + 1] if they overlap. > p, q = parts[pos - 1 : pos + 1] > if p[1] >= q[0]: > parts[pos - 1 : pos + 1] = [(p[0], max(p[1], q[1]), p[2] > + "." + q[2])] > else: > # They don't overlap, so try the next pair. > pos += 1 > > > >>> parts > [(3, 10, 'c.a.b'), (15, 23, 'd.e')] > That's the best solution I've seen so far. It even has input/output formatted as close as is reasonably possible to the format specified. As we would say in googlecode, +1. Marcus From marcusw at cox.net Wed Aug 5 07:21:55 2009 From: marcusw at cox.net (Marcus Wanner) Date: Wed, 05 Aug 2009 07:21:55 -0400 Subject: Using Python to automate builds In-Reply-To: References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> <48e9dcba-5309-4de6-b833-7abec18120e1@d9g2000prh.googlegroups.com> Message-ID: On 8/4/2009 5:52 PM, Philip Semanchuk wrote: > > On Aug 4, 2009, at 5:40 PM, Kosta wrote: > >> On Aug 4, 2:34 pm, Dave Angel wrote: >>> >>> + I have released pyKook 0.0.2. >>> +http://pypi.python.org/pypi/Kook/0.0.2 >>> +http://www.kuwata-lab.com/kook/ >>> +http://www.kuwata-lab.com/kook/pykook-users-guide.html >>> >>> Other possibilities: >>> + http://pypi.python.org/pypi/vellum/ flexible small 'make' >>> alternative >>> >>> + http://code.google.com/p/waf/ >>> >>> + http://code.google.com/p/fabricate/ >>> >>> DaveA- Hide quoted text - >>> >>> - Show quoted text - >> >> Thanks Dave. I had thought about those three options, and was >> honestly hoping for a foruth (I know, some people are never >> satisfied ;). I'll look into pyKook. Thank you for your help. > > Poof! Your wish is granted! =) > > http://www.scons.org/ > > Dunno if you'll find it better, worse or different than the > alternatives, but there it is. > > have fun > P > > I can highly recommend scons. At dolphin-emu, we use it to daily compile a project containing over 500,000 lines of c/c++ code, which is modified very frequently. It works like a charm, and is seamlessly cross- platform (in my experience). However, it might not be exactly the thing you're looking for. Marcus From anthra.norell at bluewin.ch Wed Aug 5 07:28:18 2009 From: anthra.norell at bluewin.ch (Anthra Norell) Date: Wed, 05 Aug 2009 13:28:18 +0200 Subject: How to write replace string for object which will be substituted? [regexp] In-Reply-To: <4A78BC68.2020601@mrabarnett.plus.com> References: <4A78B425.2010604@gmail.com> <4A78BC68.2020601@mrabarnett.plus.com> Message-ID: <4A796CD2.7050009@bluewin.ch> MRAB wrote: > ryniek90 wrote: >> Hi. >> I started learning regexp, and some things goes well, but most of >> them still not. >> >> I've got problem with some regexp. Better post code here: >> >> " >> >>> import re >> >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] >> mail [$dot$] com\n' >> >>> mail >> '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail >> [$dot$] com\n' >> >>> print mail >> >> name at mail.com >> name1 [at] mail [dot] com >> name2 [$at$] mail [$dot$] com >> >> >>> maail = re.sub('^\n|$\n', '', mail) >> >>> print maail >> name at mail.com >> name1 [at] mail [dot] com >> name2 [$at$] mail [$dot$] com >> >>> maail = re.sub(' ', '', maail) >> >>> print maail >> name at mail.com >> name1[at]mail[dot]com >> name2[$at$]mail[$dot$]com >> >>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) >> >>> print maail >> name at mail.com >> name1 at mail[dot]com >> name2 at mail[$dot$]com >> >>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) >> >>> print maail >> name at mail.com >> name1 at mail.com >> name2 at mail.com >> >>> #How must i write the replace string to replace all this >> regexp's with just ONE command, in string 'mail' ? >> >>> maail = re.sub('^\n|$\n| >> |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', *?*, mail) >> " >> >> How must i write that replace pattern (look at question mark), to >> maek that substituion work? I didn't saw anything helpful while >> reading Re doc and HowTo (from Python Doc). I tried with >> 'MatchObject.group()' but something gone wrong - didn't wrote it right. >> Is there more user friendly HowTo for Python Re, than this? >> >> I'm new to programming an regexp, sorry for inconvenience. >> > I don't think you can do it in one regex, nor would I want to. Just use > the string's replace() method. > > >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > mail [$dot$] com\n' > >>> mail > '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > com\n' > >>> print mail > > name at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > >>> maail = mail.strip() > name at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > >>> maail = maail.replace(' ', '') > >>> print maail > name at mail.com > name1[at]mail[dot]com > name2[$at$]mail[$dot$]com > >>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > >>> print maail > name at mail.com > name1 at mail[dot]com > name2 at mail[$dot$]com > >>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > >>> print maail > name at mail.com > name1 at mail.com > name2 at mail.com This is a good learning exercise demonstrating the impracticality of regular expressions in a given situation. In the light of the fascination regular expressions seem to exert in general, one might conclude that knowing regular expressions in essence is knowing when not to use them. There is nothing wrong with cascading substitutions through multiple expressions. The OP's solution wrapped up in a function and streamlined for needless regex overkill might look something like this: def translate (s): s1 = s.strip () # Instead of: s1 = re.sub ('^\n|$\n', '', s) s2 = s1.replace (' ', '') # Instead of: s2 = re.sub (' ', '', s1) s3 = re.sub ('\[at\]|\[\$at\$\]', '@', s2) s4 = re.sub ('\[dot\]|\[\$dot\$\]', '.', s3) return s4 print translate (mail) # Tested MRAB's solution using replace () avoids needless regex complexity, but doesn't simplify tedious coding if the number of substitutions is significant. Some time ago I proposed a little module I made to alleviate the tedium. It would handle this case like this: import SE Translator = SE.SE ( ' (32)= [at]=@ [$at$]=@ [dot]=. [$dot$]=. ' ) print Translator (mail.strip ()) # Tested So SE.SE compiles a string composed of any number of substitution definitions into an object that translates anything given it. In a running speed contest it would surely come in last, although in most cases the disadvantage would be imperceptible. Another matter is coding speed. Here the advantage is obvious, even with a set of substitutions as small as this one, let alone with sets in the tens or even hundreds. One inconspicuous but significant feature of SE is that it handles precedence correctly if targets overlap (upstream over downstream and long over short). As far as I know there's nothing in the Python system handling substitution precedence. It always needs to be hand-coded from one case to the next and that isn't exactly trivial. SE can be downloaded from http://pypi.python.org/pypi/SE/2.3. Frederic From joncle at googlemail.com Wed Aug 5 07:40:05 2009 From: joncle at googlemail.com (Jon Clements) Date: Wed, 5 Aug 2009 04:40:05 -0700 (PDT) Subject: How to write replace string for object which will be substituted? [regexp] References: <4A78B425.2010604@gmail.com> <45b7bc73-9c60-4da5-beda-1c2536add738@c1g2000yqi.googlegroups.com> Message-ID: On 5 Aug, 07:53, ryniek wrote: > On 5 Sie, 00:55, MRAB wrote: > > > > > ryniek90 wrote: > > > Hi. > > > I started learning regexp, and some things goes well, but most of them > > > still not. > > > > I've got problem with some regexp. Better post code here: > > > > " > > > ?>>> import re > > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > > mail [$dot$] com\n' > > > ?>>> mail > > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > > com\n' > > > ?>>> print mail > > > > n... at mail.com > > > name1 [at] mail [dot] com > > > name2 [$at$] mail [$dot$] com > > > > ?>>> maail = re.sub('^\n|$\n', '', mail) > > > ?>>> print maail > > > n... at mail.com > > > name1 [at] mail [dot] com > > > name2 [$at$] mail [$dot$] com > > > ?>>> maail = re.sub(' ', '', maail) > > > ?>>> print maail > > > n... at mail.com > > > name1[at]mail[dot]com > > > name2[$at$]mail[$dot$]com > > > ?>>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > > > ?>>> print maail > > > n... at mail.com > > > name1 at mail[dot]com > > > name2 at mail[$dot$]com > > > ?>>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > > > ?>>> print maail > > > n... at mail.com > > > na... at mail.com > > > na... at mail.com > > > ?>>> #How must i write the replace string to replace all this regexp's > > > with just ONE command, in string 'mail' ? > > > ?>>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', > > > *?*, mail) > > > " > > > > How must i write that replace pattern (look at question mark), to maek > > > that substituion work? I didn't saw anything helpful while reading Re > > > doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but > > > something gone wrong - didn't wrote it right. > > > Is there more user friendly HowTo for Python Re, than this? > > > > I'm new to programming an regexp, sorry for inconvenience. > > > I don't think you can do it in one regex, nor would I want to. Just use > > the string's replace() method. > > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > mail [$dot$] com\n' > > ?>>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > com\n' > > ?>>> print mail > > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > ?>>> maail = mail.strip() > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > ?>>> maail = maail.replace(' ', '') > > ?>>> print maail > > n... at mail.com > > name1[at]mail[dot]com > > name2[$at$]mail[$dot$]com > > ?>>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > > ?>>> print maail > > n... at mail.com > > name1 at mail[dot]com > > name2 at mail[$dot$]com > > ?>>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > > ?>>> print maail > > n... at mail.com > > na... at mail.com > > na... at mail.com > > Too bad, I thought that the almighty re module could do anything, but > it failed with this (or maybe re can do what i want, but only few > people knows how to force him to that? ?:P). > But with help of MRAB, i choose The 3rd Point of Python's Zen - > "Simple is better than complex." > > " > > >>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' > >>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > com\n' > > >>> print mail > > n... at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > >>> maail = mail.lstrip().rstrip().replace(' ', '').replace('[dot]', '.').replace('[$dot$]', '.').replace('[at]', '@').replace('[$at$]', '@') > >>> print maail > > n... at mail.com > na... at mail.com > na... at mail.com > > >>> #Did it ?:) > > " > > Thanks again ? :) Short of writing a dedicated function I might be tempted to write this as: EMAIL_REPLACEMENTS = ( ('[at]', '@'), ('[dot]', '.'), ... ) for src, dest in EMAIL_REPLACEMENTS: mail = mail.replace(src, dest) Apart from taste reasons, it keeps the replaces more obvious (and accessible via a variable rather than embedded in the code), enables swapping the order or adding/removing easier. Jon From cournape at gmail.com Wed Aug 5 08:08:18 2009 From: cournape at gmail.com (David Cournapeau) Date: Wed, 5 Aug 2009 21:08:18 +0900 Subject: Using Python to automate builds In-Reply-To: <200908050956.33995.hendrik@microcorp.co.za> References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> <200908050956.33995.hendrik@microcorp.co.za> Message-ID: <5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> On Wed, Aug 5, 2009 at 4:56 PM, Hendrik van Rooyen wrote: > On Tuesday 04 August 2009 21:13:10 Kosta wrote: >> I am a Python newbie, tasked with automating (researching) building >> Windows drivers using the WDK build environment. ?I've been looking >> into Python for this (instead of writing a bunch of batch files). >> > Why do you not use make and a makefile - it was designed to > do exactly this. Because make is a pain on windows (lack of a proper shell) ? cheers, David From jfine at pytex.org Wed Aug 5 08:17:44 2009 From: jfine at pytex.org (Jonathan Fine) Date: Wed, 05 Aug 2009 13:17:44 +0100 Subject: Do anyone here use Python *embedded* in a database? Message-ID: Hi I'm writing a talk that compares embed and extend, and wondered if anyone here ever used the Python *embedded* in a database server. http://twistedmatrix.com/users/glyph/rant/extendit.html Web frameworks (such as Django) use extend, to import an extension module that makes a connection to a database. If you have used embed, you might have consulted a page such as: http://www.postgresql.org/docs/8.3/interactive/plpython-funcs.html -- Jonathan From ryniek90 at gmail.com Wed Aug 5 08:21:43 2009 From: ryniek90 at gmail.com (ryniek) Date: Wed, 5 Aug 2009 05:21:43 -0700 (PDT) Subject: How to write replace string for object which will be substituted? [regexp] References: <4A78B425.2010604@gmail.com> <4A78BC68.2020601@mrabarnett.plus.com> Message-ID: <0cde7cf6-0365-44da-b044-9066d522fa2d@w41g2000yqb.googlegroups.com> On 5 Sie, 13:28, Anthra Norell wrote: > MRAB wrote: > > ryniek90 wrote: > >> Hi. > >> I started learning regexp, and some things goes well, but most of > >> them still not. > > >> I've got problem with some regexp. Better post code here: > > >> " > >> ?>>> import re > >> ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > >> mail [$dot$] com\n' > >> ?>>> mail > >> '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail > >> [$dot$] com\n' > >> ?>>> print mail > > >> n... at mail.com > >> name1 [at] mail [dot] com > >> name2 [$at$] mail [$dot$] com > > >> ?>>> maail = re.sub('^\n|$\n', '', mail) > >> ?>>> print maail > >> n... at mail.com > >> name1 [at] mail [dot] com > >> name2 [$at$] mail [$dot$] com > >> ?>>> maail = re.sub(' ', '', maail) > >> ?>>> print maail > >> n... at mail.com > >> name1[at]mail[dot]com > >> name2[$at$]mail[$dot$]com > >> ?>>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > >> ?>>> print maail > >> n... at mail.com > >> name1 at mail[dot]com > >> name2 at mail[$dot$]com > >> ?>>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > >> ?>>> print maail > >> n... at mail.com > >> na... at mail.com > >> na... at mail.com > >> ?>>> #How must i write the replace string to replace all this > >> regexp's with just ONE command, in string 'mail' ? > >> ?>>> maail = re.sub('^\n|$\n| > >> |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', *?*, mail) > >> " > > >> How must i write that replace pattern (look at question mark), to > >> maek that substituion work? I didn't saw anything helpful while > >> reading Re doc and HowTo (from Python Doc). I tried with > >> 'MatchObject.group()' but something gone wrong - didn't wrote it right. > >> Is there more user friendly HowTo for Python Re, than this? > > >> I'm new to programming an regexp, sorry for inconvenience. > > > I don't think you can do it in one regex, nor would I want to. Just use > > the string's replace() method. > > > >>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > mail [$dot$] com\n' > > >>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > com\n' > > >>> print mail > > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > >>> maail = mail.strip() > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > >>> maail = maail.replace(' ', '') > > >>> print maail > > n... at mail.com > > name1[at]mail[dot]com > > name2[$at$]mail[$dot$]com > > >>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > > >>> print maail > > n... at mail.com > > name1 at mail[dot]com > > name2 at mail[$dot$]com > > >>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > > >>> print maail > > n... at mail.com > > na... at mail.com > > na... at mail.com > > This is a good learning exercise demonstrating the impracticality of > regular expressions in a given situation. In the light of the > fascination regular expressions seem to exert in general, one might > conclude that knowing regular expressions in essence is knowing when not > to use them. > > There is nothing wrong with cascading substitutions through multiple > expressions. The OP's solution wrapped up in a function and streamlined > for needless regex overkill might look something like this: > > def translate (s): > ? ?s1 = s.strip () ? ? # Instead of: s1 = re.sub ('^\n|$\n', '', s) > ? ?s2 = s1.replace (' ', '') ? ?# Instead of: s2 = re.sub (' ', '', s1) > ? ?s3 = re.sub ('\[at\]|\[\$at\$\]', '@', s2) > ? ?s4 = re.sub ('\[dot\]|\[\$dot\$\]', '.', s3) > ? ?return s4 > > print translate (mail) ? # Tested > > MRAB's solution using replace () avoids needless regex complexity, but > doesn't simplify tedious coding if the number of substitutions is > significant. Some time ago I proposed a little module I made to > alleviate the tedium. It would handle this case like this: > > import SE > Translator = SE.SE ( ' (32)= [at]=@ [$at$]=@ [dot]=. [$dot$]=. ' ) > print Translator (mail.strip ()) ? # Tested > > So SE.SE compiles a string composed of any number of substitution > definitions into an object that translates anything given it. In a > running speed contest it would surely come in last, although in most > cases the disadvantage would be imperceptible. Another matter is coding > speed. Here the advantage is obvious, even with a set of substitutions > as small as this one, let alone with sets in the tens or even hundreds. > One inconspicuous but significant feature of SE is that it handles > precedence correctly if targets overlap (upstream over downstream and > long over short). As far as I know there's nothing in the Python system > handling substitution precedence. It always needs to be hand-coded from > one case to the next and that isn't exactly trivial. > > SE can be downloaded fromhttp://pypi.python.org/pypi/SE/2.3. > > Frederic Thanks again. :) I saw that MRAB is actively developing new implementation of re module. MRAB: You think it'd be good idea adding to Your project some best features of SE module? I didn't seen yet features of Your re module but will try to find time even today, to see what's going on. Greets From ryniek90 at gmail.com Wed Aug 5 08:21:56 2009 From: ryniek90 at gmail.com (ryniek) Date: Wed, 5 Aug 2009 05:21:56 -0700 (PDT) Subject: How to write replace string for object which will be substituted? [regexp] References: <4A78B425.2010604@gmail.com> <4A78BC68.2020601@mrabarnett.plus.com> Message-ID: On 5 Sie, 13:28, Anthra Norell wrote: > MRAB wrote: > > ryniek90 wrote: > >> Hi. > >> I started learning regexp, and some things goes well, but most of > >> them still not. > > >> I've got problem with some regexp. Better post code here: > > >> " > >> ?>>> import re > >> ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > >> mail [$dot$] com\n' > >> ?>>> mail > >> '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail > >> [$dot$] com\n' > >> ?>>> print mail > > >> n... at mail.com > >> name1 [at] mail [dot] com > >> name2 [$at$] mail [$dot$] com > > >> ?>>> maail = re.sub('^\n|$\n', '', mail) > >> ?>>> print maail > >> n... at mail.com > >> name1 [at] mail [dot] com > >> name2 [$at$] mail [$dot$] com > >> ?>>> maail = re.sub(' ', '', maail) > >> ?>>> print maail > >> n... at mail.com > >> name1[at]mail[dot]com > >> name2[$at$]mail[$dot$]com > >> ?>>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > >> ?>>> print maail > >> n... at mail.com > >> name1 at mail[dot]com > >> name2 at mail[$dot$]com > >> ?>>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > >> ?>>> print maail > >> n... at mail.com > >> na... at mail.com > >> na... at mail.com > >> ?>>> #How must i write the replace string to replace all this > >> regexp's with just ONE command, in string 'mail' ? > >> ?>>> maail = re.sub('^\n|$\n| > >> |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', *?*, mail) > >> " > > >> How must i write that replace pattern (look at question mark), to > >> maek that substituion work? I didn't saw anything helpful while > >> reading Re doc and HowTo (from Python Doc). I tried with > >> 'MatchObject.group()' but something gone wrong - didn't wrote it right. > >> Is there more user friendly HowTo for Python Re, than this? > > >> I'm new to programming an regexp, sorry for inconvenience. > > > I don't think you can do it in one regex, nor would I want to. Just use > > the string's replace() method. > > > >>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > mail [$dot$] com\n' > > >>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > com\n' > > >>> print mail > > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > >>> maail = mail.strip() > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > >>> maail = maail.replace(' ', '') > > >>> print maail > > n... at mail.com > > name1[at]mail[dot]com > > name2[$at$]mail[$dot$]com > > >>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > > >>> print maail > > n... at mail.com > > name1 at mail[dot]com > > name2 at mail[$dot$]com > > >>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > > >>> print maail > > n... at mail.com > > na... at mail.com > > na... at mail.com > > This is a good learning exercise demonstrating the impracticality of > regular expressions in a given situation. In the light of the > fascination regular expressions seem to exert in general, one might > conclude that knowing regular expressions in essence is knowing when not > to use them. > > There is nothing wrong with cascading substitutions through multiple > expressions. The OP's solution wrapped up in a function and streamlined > for needless regex overkill might look something like this: > > def translate (s): > ? ?s1 = s.strip () ? ? # Instead of: s1 = re.sub ('^\n|$\n', '', s) > ? ?s2 = s1.replace (' ', '') ? ?# Instead of: s2 = re.sub (' ', '', s1) > ? ?s3 = re.sub ('\[at\]|\[\$at\$\]', '@', s2) > ? ?s4 = re.sub ('\[dot\]|\[\$dot\$\]', '.', s3) > ? ?return s4 > > print translate (mail) ? # Tested > > MRAB's solution using replace () avoids needless regex complexity, but > doesn't simplify tedious coding if the number of substitutions is > significant. Some time ago I proposed a little module I made to > alleviate the tedium. It would handle this case like this: > > import SE > Translator = SE.SE ( ' (32)= [at]=@ [$at$]=@ [dot]=. [$dot$]=. ' ) > print Translator (mail.strip ()) ? # Tested > > So SE.SE compiles a string composed of any number of substitution > definitions into an object that translates anything given it. In a > running speed contest it would surely come in last, although in most > cases the disadvantage would be imperceptible. Another matter is coding > speed. Here the advantage is obvious, even with a set of substitutions > as small as this one, let alone with sets in the tens or even hundreds. > One inconspicuous but significant feature of SE is that it handles > precedence correctly if targets overlap (upstream over downstream and > long over short). As far as I know there's nothing in the Python system > handling substitution precedence. It always needs to be hand-coded from > one case to the next and that isn't exactly trivial. > > SE can be downloaded fromhttp://pypi.python.org/pypi/SE/2.3. > > Frederic Thanks again. :) I saw that MRAB is actively developing new implementation of re module. MRAB: You think it'd be good idea adding to Your project some best features of SE module? I didn't seen yet features of Your re module but will try to find time even today, to see what's going on. Greets From piet at cs.uu.nl Wed Aug 5 08:28:15 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Aug 2009 14:28:15 +0200 Subject: Special chars with HTMLParser References: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com> Message-ID: >>>>> Fafounet (F) wrote: >F> Hello, >F> I am parsing a web page with special chars such as é (which >F> stands for ?). >F> I know I can have the unicode character ? from unicode >F> ("\xe9","iso-8859-1") >F> but with those extra characters I don' t know. >F> I tried to implement handle_charref within HTMLParser without success. >F> Furthermore, if I have the data abécd, handle_data will get "ab", >F> handle_charref will get xe9 and then handle_data doesn't have the end >F> of the string ("cd"). The character references indicate Unicode ordinals, not iso-8859-1 characters. In your example it will give the proper character because iso-8859-1 coincides with the first part of the Unicode ordinals, but for character outside of iso-8859-1 it will fail. This should give you an idea: from htmlentitydefs import name2codepoint ... def handle_charref(self, name): if name.startswith('x'): num = int(name[1:], 16) else: num = int(name, 10) print 'char:', repr(unichr(num)) def handle_entityref(self, name): print 'char:', unichr(name2codepoint[name]) If your HTML may be illegal you should add some exception handling. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From Tribulations at Paralleles.invalid Wed Aug 5 08:33:03 2009 From: Tribulations at Paralleles.invalid (TP) Date: Wed, 05 Aug 2009 14:33:03 +0200 Subject: intricated functions: how to share a variable References: <9a937d26-2375-4836-9824-d34d9f92d284@o15g2000yqm.googlegroups.com> Message-ID: Bearophile wrote: > So probably a better solution is to just use the normal function > semantics: you pass them an argument and you take an argument as > return value. Such return value will be the new version of the value > you talk about. Thanks for your answer. Yes, it is better like this. My problem is that I cannot get the return values of the function and affect it to some variable, because the function is called via a "signal-slot" connection of PyQt4, not by an explicit inline function call. For example: ######### def tutu(): def toto(): print a a = 4 print a a=2 # ... # definition of some graphical QPushButton "button" # ... # ... self.connect( button, SIGNAL( "clicked" ), toto ) tutu() ########## Then, as advised Diez, perhaps the best solution is to have "true" global variables by using a class and defining the variable a as a member self.a of the class. By doing like this, a will be known everywhere. Julien -- python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\ 9&1+,\'Z4(55l4('])" "When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong." (first law of AC Clarke) From piet at cs.uu.nl Wed Aug 5 08:34:31 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Aug 2009 14:34:31 +0200 Subject: trouble with complex numbers References: <24821423.post@talk.nabble.com> Message-ID: >>>>> Christian Heimes (CH) wrote: >CH> You can write your own phase() function. This function is mostly correct >CH> unless either the real and/or the imag part is NaN or INF. >CH> from math import atan2 >CH> def phase(z): >CH> z += 1j # convert int, long, float to complex That should be z += 0j >CH> return atan2(z.imag, z.real) -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From kpalamartchouk at gmail.com Wed Aug 5 08:50:04 2009 From: kpalamartchouk at gmail.com (kpal) Date: Wed, 5 Aug 2009 05:50:04 -0700 (PDT) Subject: Datetime with float seconds Message-ID: Hello Everybody, The standard datetime has 1 microsecond granularity. My application needs finer time resolution, preferably float seconds. Is there an alternative to the out-of-the-box datetime? Timezone support is not essential. Thanks, From nick.m.daly at gmail.com Wed Aug 5 08:56:14 2009 From: nick.m.daly at gmail.com (Nick Daly) Date: Wed, 05 Aug 2009 07:56:14 -0500 Subject: The Perils of PyContract (and Generators) Message-ID: <4A79816E.5050106@gmail.com> On Wed, 5 Aug 2009 03:06 pm Nick Daly wrote: > The problem actually lies in the contract. Generally, the PyContract > shouldn't affect the return values or in any way modify the code, which > it doesn't, as long as the function returns a list values (the way the > code had in fact originally been written). However, the contract > mentioned above is actually quite wrong for a generator. Yes, because you are conflating the items yielded from the generator with the generator object returned from the generator function "find_files". You can't look inside the generator object without using up whichever items you look at. [...] > Correcting the above example involves doing nothing more than > simplifying the contract: > > post: > name in __return__ That can't be right, not unless PyContract is doing something I don't expect. I expect that would be equivalent of: 'fish' in which should fail: >>> __return__ = find_files('fish') # a generator object >>> 'fish' in __return__ False >>> >>> __return__ = find_files('fish') >>> __return__ = list(__return__) >>> 'fish' in __return__ False >>> __return__ ['one fish', 'two fish', 'red fish', 'blue fish'] Of course, I may be mistaking what PyContract is doing. ----- No, you're absolutely right, I realized the error in my email moments after sending it, I was just hoping no one was paying enough attention to notice. I'm essentially asking PyContract to operate outside of the generator (it needs to check the return value of a generator, without changing its internal state), which doesn't seem to have an easy solution unless generators have some fantastic reverse_states function that I haven't heard about. I suppose one could be built, saving off the values of all local variables for later restoration, but that would still be dependent on the state of the rest of the machine and could not guarantee giving the same answer twice in a row. So, the moral of the story seems to be that PyContract's post-return value checking doesn't mix with generators at all. Sort of sad, because they're two neat flavors that would go great together but are instead technically incompatible. A decent set of unit-tests would accomplish the same thing much less destructively anyway. Nick From fafounet at gmail.com Wed Aug 5 09:03:46 2009 From: fafounet at gmail.com (Fafounet) Date: Wed, 5 Aug 2009 06:03:46 -0700 (PDT) Subject: Special chars with HTMLParser References: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com> Message-ID: <69835fa3-c6a0-44d3-bba2-5e3117102590@k30g2000yqf.googlegroups.com> Thank you, now I can get the correct character. Now when I have the string abécd I can get ab then ? thanks to your function and then cd. But how is it possible to know that cd is still the same word ? Fabien > The character references indicate Unicode ordinals, not iso-8859-1 > characters. In your example it will give the proper character because > iso-8859-1 coincides with the first part of the Unicode ordinals, but > for character outside of iso-8859-1 it will fail. > > This should give you an idea: > > from htmlentitydefs import name2codepoint > ... > ? ? def handle_charref(self, name): > ? ? ? ? if name.startswith('x'): > ? ? ? ? ? ? num = int(name[1:], 16) > ? ? ? ? else: > ? ? ? ? ? ? num = int(name, 10) > ? ? ? ? print 'char:', repr(unichr(num)) > > ? ? def handle_entityref(self, name): > ? ? ? ? print 'char:', unichr(name2codepoint[name]) > > If your HTML may be illegal you should add some exception handling. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org From contact at xavierho.com Wed Aug 5 09:15:53 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 5 Aug 2009 23:15:53 +1000 Subject: Datetime with float seconds In-Reply-To: References: Message-ID: <2d56febf0908050615i1d8f5137v3295c1ab574067c5@mail.gmail.com> On Wed, Aug 5, 2009 at 10:50 PM, kpal wrote: > Hello Everybody, > > The standard datetime has 1 microsecond granularity. My application > needs finer time resolution, preferably float seconds. Is there an > alternative to the out-of-the-box datetime? Timezone support is not > essential. This is a little outdated, but: >>>from time import time Usually gets me things like #output Run time: 0.0279998779297 seconds. So... that might be what you want. - Xavier -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuwei23 at gmail.com Wed Aug 5 09:35:19 2009 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Aug 2009 06:35:19 -0700 (PDT) Subject: intricated functions: how to share a variable References: <9a937d26-2375-4836-9824-d34d9f92d284@o15g2000yqm.googlegroups.com> Message-ID: TP wrote: > Then, as advised Diez, perhaps the best solution is to have "true" global > variables by using a class and defining the variable a as a member self.a > of the class. By doing like this, a will be known everywhere. Or, as Bearophile suggested, you could use the standard way of passing arguments into a function: >>> def tutu(): ... a = 2 ... def toto(a=a): ... print 'toto', a ... a = 4 ... print 'toto', a ... print 'tutu', a ... toto() ... print 'tutu', a ... >>> tutu() tutu 2 toto 2 toto 4 tutu 2 You could also just do 'toto(a)', but as you're trying to create a closure here, binding the external scope 'a' to toto via the default argument will (probably) do what you need. From jnoller at gmail.com Wed Aug 5 09:40:57 2009 From: jnoller at gmail.com (Jesse Noller) Date: Wed, 5 Aug 2009 06:40:57 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? References: <2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> Message-ID: <74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> On Aug 5, 1:21?am, sturlamolden wrote: > On Aug 5, 4:37 am, erikcw wrote: > > > It's not always the same traceback, but they are always short like > > this. ?I'm running Python 2.6.2 on Ubuntu 9.04. > > > Any idea how I can debug this? > > In my experience,multiprocessingis fragile. Scripts tend fo fail for > no obvious reason, case processes to be orphaned and linger, system- > wide resource leaks, etc. For example,multiprocessinguses os._exit > to stop a spawned process, even though it inevitably results in > resource leaks on Linux (it should use sys.exit). Ga?l Varoquaux and I > noticed this when we implemented shared memory ndarrays for numpy; we > consistently got memory leaks with System V IPC for no obvious reason. > Even after Jesse Noller was informed of the problem (about half a year > ago), the bug still lingers. It is easy editmultiprocessing's > forking.py file on you own, but bugs like this is a pain in the ass, > and I suspectmultiprocessinghas many of them. Of course unless you > show us you whole script, identifying the source of your bug will be > impossible. But it may very likely be inmultiprocessingas well. The > quality of this module is not impressing. I am beginning to think thatmultiprocessingshould never have made it into the Python standard > library. The GIL cannot be that bad! If you can't stand the GIL, get a > Unix (or Mac, Linux, Cygwin) and use os.fork. Or simply switch to a > non-GIL Python: IronPython or Jython. > > Allow me to show you something better. With os.fork we can write code > like this: > > class parallel(object): > > ? ?def __enter__(self): > ? ? ? ?# call os.fork > > ? ?def __exit__(self, exc_type, exc_value, traceback): > ? ? ? ?# call sys.exit in the child processes and > ? ? ? ?# os.waitpid in the parent > > ? ?def __call__(self, iterable): > ? ? ? ?# return different sub-subsequences depending on > ? ? ? ?# child or parent status > > with parallel() as p: > ? ? # parallel block starts here > > ? ? for item in p(iterable): > ? ? ? ? # whatever > > ? ? # parallel block ends here > > This makes parallel code a lot cleaner than anything you can do withmultiprocessing, allowing you to use constructs similar to OpenMP. > Further, if you make 'parallel' a dummy context manager, you can > develop and test the algorithms serially. The only drawback is that > you have to use Cygwin to get os.fork on Windows, and forking will be > less efficient (no copy-on-write optimization). Well, this is just one > example of why Windows sucks from the perspective of the programmer. > But it also shows that you can do much better by notusingmultiprocessingat all. > > The only case I can think of wheremultiprocessingwould be usesful, > is I/O bound code on Windows. But here you will almost always resort > to C extension modules. For I/O bound code, Python tends to give you a > 200x speed penalty over C. If you are resorting to C anyway, you can > just use OpenMP in C for your parallel processing. We can thus forget > aboutmultiprocessinghere as well, given that we have access to the C > code. If we don't, it is still very likely that the C code releases > the GIL, and we can get away withusingPython threads instead ofmultiprocessing. > > IMHO, if you areusingmultiprocessing, you are very likely to have a > design problem. > > Regards, > Sturla Sturla; That bug was fixed unless I'm missing something. Also, patches and continued bug reports are welcome. jesse From wuwei23 at gmail.com Wed Aug 5 09:41:56 2009 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Aug 2009 06:41:56 -0700 (PDT) Subject: trouble with complex numbers References: <24821423.post@talk.nabble.com> Message-ID: Piet van Oostrum wrote: > That should be z += 0j Pardon my ignorance, but could anyone explain the rationale behind using 'j' to indicate the imaginary number (as opposed to the more intuitive 'i')? (Not that I've had much call to use complex numbers but I'm curious....) From jjposner at optimum.net Wed Aug 5 09:46:16 2009 From: jjposner at optimum.net (John Posner) Date: Wed, 05 Aug 2009 09:46:16 -0400 Subject: Announcing PythonTurtle In-Reply-To: References: Message-ID: <4A798D28.5060004@optimum.net> >> OK, then why the statements "from turtle import *" in the modules >> turtleprocess.py and turtlewidget.py? >> Yes, I see that now (he said meekly, too sheepish to complain about being misled by an unfortunate naming choice). Tx, John From casevh at gmail.com Wed Aug 5 09:50:17 2009 From: casevh at gmail.com (casevh) Date: Wed, 5 Aug 2009 06:50:17 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> Message-ID: <5a4ab236-4cbf-4895-935a-5fdc712f0d08@u38g2000pro.googlegroups.com> On Aug 5, 12:19?am, Steven D'Aprano wrote: > On Wed, 5 Aug 2009 03:49 pm Mensanator wrote: > > > In 3.1, tracing is now a screen attribute, not a turtle atribute. > > I have no idea why > > > ? tooter = turtle.Turtle() > > ? tooter.tracer(False) > > > doesn't give me an error (I thought silent errors were a bad thing). > > What makes it an error? Do you consider the following an error? > > >>> class Test: > > ... ? ? pass > ... > > >>> t = Test() > >>> t.tracer = 5 > > Perhaps you mean, it's an API change you didn't know about, and you wish to > protest that Turtle Graphics made an incompatible API change without > telling you? > > > Naturally, having tracing on caused my program to crash. > > It seg faulted or raised an exception? > > [...] > > > Unfortunately, that calculation of nhops is illegal if diffsq is > > an .mpf (gmpy floating point). Otherwise, you get > > How does diffsq get to be a mpf? Are gmpy floats supposed to be supported? > > -- > Steven The root cause of the error is that GMP, the underlying library for gmpy, provides only the basic floating point operations. gmpy implements a very limited exponentiation function. Python's math library will convert an mpf to a float automatically so I think the revised calculation for nhops should work with either any numerical type that supports __float__. casevh From hendrik at microcorp.co.za Wed Aug 5 10:29:39 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 5 Aug 2009 16:29:39 +0200 Subject: Using Python to automate builds In-Reply-To: <5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> <200908050956.33995.hendrik@microcorp.co.za> <5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> Message-ID: <200908051629.39417.hendrik@microcorp.co.za> On Wednesday 05 August 2009 14:08:18 David Cournapeau wrote: > On Wed, Aug 5, 2009 at 4:56 PM, Hendrik van > > Rooyen wrote: > > On Tuesday 04 August 2009 21:13:10 Kosta wrote: > >> I am a Python newbie, tasked with automating (researching) building > >> Windows drivers using the WDK build environment. ?I've been looking > >> into Python for this (instead of writing a bunch of batch files). > > > > Why do you not use make and a makefile - it was designed to > > do exactly this. > > Because make is a pain on windows (lack of a proper shell) ? Well, you could always use Dosbox - I am doing exactly that on Linux to be able to run some old DOS based assembler tools. It will run on windows too, they claim. And it is very simple to use too - no fancy fidgeting, all you have to do is to point it at a directory that becomes your "C" drive. Bit slow - but hey, nobody's perfect. - Hendrik From contact at xavierho.com Wed Aug 5 10:32:15 2009 From: contact at xavierho.com (Xavier Ho) Date: Thu, 6 Aug 2009 00:32:15 +1000 Subject: Subclassing Python's dict In-Reply-To: References: Message-ID: <2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com> On Thu, Aug 6, 2009 at 11:51 AM, Sergey Simonenko wrote: > I subclass builtin 'dict' in my application and experience some problems > with it. > You should subclass collections.UserDict, and not the default dict class. Refer to the collections module. Also, the ABC MutableMapping might be of your interest. > Another guy have reported me that he experiences similar problems with > subclassing builtin 'list'. Similarly, UserList is what you should subclass. HTH, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From joncle at googlemail.com Wed Aug 5 10:32:37 2009 From: joncle at googlemail.com (Jon Clements) Date: Wed, 5 Aug 2009 07:32:37 -0700 (PDT) Subject: Do anyone here use Python *embedded* in a database? References: Message-ID: <767b6862-065f-480a-82f5-ed3aa35bf84d@n11g2000yqb.googlegroups.com> On 5 Aug, 13:17, Jonathan Fine wrote: > Hi > > I'm writing a talk that compares embed and extend, and wondered if > anyone here ever used the Python *embedded* in a database server. > ? ? ?http://twistedmatrix.com/users/glyph/rant/extendit.html > > Web frameworks (such as Django) use extend, to import an extension > module that makes a connection to a database. > > If you have used embed, you might have consulted a page such as: > ? ? ?http://www.postgresql.org/docs/8.3/interactive/plpython-funcs.html > > -- > Jonathan Yup, have used plpythonu within postgres without too many problems. Although I do recall once that using the CSV module to load and filter external data, did consume a massive amount of memory. Even though the entire procedure was iterator based -- never did work out if it was postgres caching, or some other weird stuff. [That was about 2 years ago though] Jon. From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 5 10:39:52 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 05 Aug 2009 16:39:52 +0200 Subject: Subclassing Python's dict In-Reply-To: References: Message-ID: <4a7999b1$0$306$426a74cc@news.free.fr> Sergey Simonenko a ?crit : > Hi, > > I subclass builtin 'dict' in my application and experience some problems > with it. > > The whole issue is that I should redefine 'setdefault' and 'update' > methods after redefining '__setitem__' or/and '__delitem__', > otherwise 'update' and 'setdefault' ignore redefined '__setitem__' and > use builtin dict's one so dict looks kinda like a black box. > > Another guy have reported me that he experiences similar problems with > subclassing builtin 'list'. I indeed notice this behaviour here (Python 2.6.2). I'm afraid it has to do with some optimization tricks (dict being the very fundamental data structure in Python, it has to be higly optimized). From af1ing at seznam.cz Wed Aug 5 10:41:05 2009 From: af1ing at seznam.cz (Rog) Date: Wed, 5 Aug 2009 07:41:05 -0700 (PDT) Subject: http access produces 503 Message-ID: <3b5ab07c-7b0b-4d23-965b-192dc86cf6ff@a26g2000yqn.googlegroups.com> I am porting a simple code from Perl, the website asks for usr/pwd and the server's side Perl script makes atemp ftp dir for file upload. The original Perl script connects okay, does its job. The same URL stuffed into FF3 performs the same way. My Python script I am sweating out for past four days (noob!) gets consistently "503", even with user agen set to: Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11. Snippets of relevant code below. Please, help me understand how this same code lets me log in into my router usr/pwd running .asp, but this !@#$% perl script returns to me w/503 c*ap? Thank you. Do I need to set any proxy? The server is on intranet and the FF3 is set to proxy. The original Perl script did not use any proxy setting.


url = http://example.com/ftpsetup.pl?username=boofa&nodeid=42
#########################################################
# create a password manager
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of ``None``.
    password_mgr.add_password(None, url, uid, pcode)
    handler = urllib2.HTTPBasicAuthHandler(password_mgr)
    class Mopener(URLopener): version = "Mozilla/5.0 (Windows; U;
Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

    opener = Mopener()

# create "opener" (OpenerDirector instance)

    opener = urllib2.build_opener(handler)
    opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U;
Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11')]

    opener.version = "Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:
1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

    print opener.version
# timeout in seconds
    timeout = 10
    socket.setdefaulttimeout(timeout)

# Install the opener all calls to urllib2.urlopen use our opener.
    urllib2.install_opener(opener)

    try:
        response = opener.open(url)
        # "http://www.useragent.org/" tested okay!!!
        print"ok = 1"
    except:
        print "error 1"
#####################################################################################

output from the above:

Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/
20071127 Firefox/2.0.0.11
error 1
Error code:  503
('Service Unavailable', 'The server cannot process the request due to
a high load')
From michael at stroeder.com Wed Aug 5 10:43:09 2009 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 05 Aug 2009 16:43:09 +0200 Subject: unicode() vs. s.decode() Message-ID: HI! These both expressions are equivalent but which is faster or should be used for any reason? u = unicode(s,'utf-8') u = s.decode('utf-8') # looks nicer Ciao, Michael. From martin.hellwig at dcuktec.org Wed Aug 5 10:46:13 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 05 Aug 2009 15:46:13 +0100 Subject: Parsing Binary Structures; Is there a better way / What is your way? Message-ID: Hi List, On several occasions I have needed (and build) a parser that reads a binary piece of data with custom structure. For example (bogus one): BE +---------+---------+-------------+-------------+------+--------+ | Version | Command | Instruction | Data Length | Data | Filler | +---------+---------+-------------+-------------+------+--------+ Version: 6 bits Command: 4 bits Instruction: 5 bits Data Length: 5 bits Data: 0-31 bits Filler: filling 0 bits to make the packet dividable by 8 what I usually do is read the packet in binary mode, convert the output to a concatenated 'binary string'(i.e. '0101011000110') and then use slice indeces to get the right data portions. Depending on what I need to do with these portions I convert them to whatever is handy (usually an integer). This works out fine for me. Most of the time I also put the ASCII art diagram of this 'protocol' as a comment in the code, making it more readable/understandable. Though there are a couple of things that bothers me with my approach: - This seems such a general problem that I think that there must be already a general pythonic solution. - Using a string for binary representation takes at least 8 times more memory for the packet than strictly necessary. - Seems to need a lot of prep work before doing the actual parsing. Any suggestion is greatly appreciated. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From dp_pearce at hotmail.com Wed Aug 5 10:51:44 2009 From: dp_pearce at hotmail.com (dp_pearce) Date: Wed, 5 Aug 2009 07:51:44 -0700 (PDT) Subject: Is it possible to produce spider plots? Message-ID: I want to be able to use Python to produce Spider plots (perhaps you know them as radar plots or star plots). Does anyone know how to achieve this? Are there existing libraries? Direction to any examples, especially those with tutorials, would be greatly appreciated. Cheers, Dan http://www.answers.com/topic/spider-plot From pruebauno at latinmail.com Wed Aug 5 10:56:35 2009 From: pruebauno at latinmail.com (nn) Date: Wed, 5 Aug 2009 07:56:35 -0700 (PDT) Subject: Overlap in python References: <4A78B19D.4020306@mrabarnett.plus.com> Message-ID: <4c9f81a5-51b9-4487-9df9-d458b327d286@s15g2000yqs.googlegroups.com> On Aug 5, 7:13?am, Marcus Wanner wrote: > On 8/4/2009 6:09 PM, MRAB wrote: > > > ?>>> parts = [(5, 9, "a"), (7, 10, "b"), (3, 6, "c"), (15, 20, "d"), > > (18, 23, "e")] > > ?>>> parts.sort() > > ?>>> parts > > [(3, 6, 'c'), (5, 9, 'a'), (7, 10, 'b'), (15, 20, 'd'), (18, 23, 'e')] > > ?>>> # Merge overlapping intervals. > > ?>>> pos = 1 > > ?>>> while pos < len(parts): > > ? ? ? ? # Merge the pair in parts[pos - 1 : pos + 1] if they overlap. > > ? ? ? ? p, q = parts[pos - 1 : pos + 1] > > ? ? ? ? if p[1] >= q[0]: > > ? ? ? ? ? ? ? ? parts[pos - 1 : pos + 1] = [(p[0], max(p[1], q[1]), p[2] > > + "." + q[2])] > > ? ? ? ? else: > > ? ? ? ? ? ? ? ? # They don't overlap, so try the next pair. > > ? ? ? ? ? ? ? ? pos += 1 > > > ?>>> parts > > [(3, 10, 'c.a.b'), (15, 23, 'd.e')] > > That's the best solution I've seen so far. It even has input/output > formatted as close as is reasonably possible to the format specified. > > As we would say in googlecode, +1. > > Marcus How does it compare to this one? http://groups.google.com/group/comp.lang.python/browse_frm/thread/1a1d2ed9d05d11d0/56684b795fc527cc#56684b795fc527cc From roger_lynx at yahoo.com Wed Aug 5 11:05:38 2009 From: roger_lynx at yahoo.com (roger_lynx) Date: Wed, 05 Aug 2009 15:05:38 -0000 Subject: web access yields "503" Message-ID: Hi, I am porting a simple code from Perl, the website asks for usr/pwd and the server's side Perl script makes a temp ftp dir for a file upload. The original Perl script connects okay, does its job. The same URL stuffed into FF3 performs the same way. My Python script I am sweating over for past four days (noob!) gets consistently "503", even with user agent set to: Mozilla/5.0 (Windows;U; Windows NT 5.1; it; rv:1.8.1.11)Gecko/20071127 Firefox/2.0.0.11. Snippets of relevant code below, heavily copied from this author: http://www.voidspace.org.uk/python/articles/urllib2.shtml Please, help me understand how this same code lets me log in into my router usr/pwd running .asp, but this !@#$% perl script returns to me w/503 c*ap? Thank you. Do I need to set any proxy? The server is on intranet and the FF3 is set to proxy. The original Perl script did not use any proxy setting! LWP::

url = http://bad_example.com/ftpsetup.pl?username=boofa&nodeid=42
#########################################################
# create a password manager
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of ``None``.
    password_mgr.add_password(None, url, uid, pcode)
    handler = urllib2.HTTPBasicAuthHandler(password_mgr)
    class Mopener(URLopener): version = "Mozilla/5.0 (Windows; U;
Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

    opener = Mopener()

# create "opener" (OpenerDirector instance)

    opener = urllib2.build_opener(handler)
    opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U;
Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11')]

    opener.version = "Mozilla/5.0 (Windows; U; 
Windows NT 5.1; it; rv:
1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

    print opener.version
# timeout in seconds
    timeout = 10
    socket.setdefaulttimeout(timeout)

# Install the opener all calls to urllib2.urlopen use our opener.
    urllib2.install_opener(opener)

    try:
        response = opener.open(url)
        # "http://www.useragent.org/" tested okay!!!
        print"ok = 1"
    except:
        print "error 1"
#####################################################################################

output from the above:

Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/
20071127 Firefox/2.0.0.11
error 1
Error code: 503
('Service Unavailable', 'The server cannot process the request due to
a high load')
From Scott.Daniels at Acm.Org Wed Aug 5 11:12:48 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 05 Aug 2009 08:12:48 -0700 Subject: Overlap in python In-Reply-To: References: Message-ID: Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. For example, here would be my input: > > part name location > a 5-9 > b 7-10 > c 3-6 > d 15-20 > e 18-23 > > And here is what I need for an output: > part name location > c.a.b 3-10 > d.e 15-23 > > I've tried various methods, which all fail. Does anyone have an idea > how to do this? > > Thank you very much! > Jay I once had to do this for finding nested block structure. The key for me was a sort order: start, -final. Having not seen it here (though I looked a bit), here's one: class Entry(object): '''An entry is a name and range''' def __init__(self, line): self.name, startstop = line.split() start, stop = startstop.split('-') self.start, self.stop = int(start), int(stop) def combined_ranges(lines): '''Create Entries in "magic order", and produce ranges. The "magic order" makes least element with longest range first, so overlaps show up in head order, with final tail first among equals. ''' # Fill in our table (ignoring blank lines), then sort by magic order elements = [Entry(line) for line in lines if line.strip()] elements.sort(key=lambda e: (e.start, -e.stop)) # Now produce resolved ranges. Grab the start gen = iter(elements) first = gen.next() # For the remainder, combine or produce for v in gen: if v.start <= first.stop: # on overlap, merge in new element (may update stop) first.name += '.' + v.name if first.stop < v.stop: first.stop = v.stop else: yield first first = v # And now produce the last element we covered yield first # Demo: sample = '''part name location a 5-9 b 7-10 c 3-6 d 15-20 e 18-23 ''' source = iter(sample.split('\n')) # source of lines, opened file? ignored = source.next() # discard heading for interval in combined_range(source): print '%s %s-%s' % (interval.name, interval.start, interval.stop) Prints: c.a.b 3-10 d.e 15-23 --Scott David Daniels Scott.Daniels at Acm.Org From wuwei23 at gmail.com Wed Aug 5 11:17:34 2009 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Aug 2009 08:17:34 -0700 (PDT) Subject: trouble with complex numbers References: <24821423.post@talk.nabble.com> Message-ID: <37b97967-ec2e-4c37-a4b9-46e56a6de7bd@p36g2000prn.googlegroups.com> On Aug 6, 1:18?am, Scott David Daniels wrote: > I think it explained in the complex math area, but basically EE types > use j, math types use i for exactly the same thing. ?Since i is so > frequently and index in CS, and there is another strong convention, > why not let the EE types win? That 'i' tends to be used as index did occur to me, I just wasn't aware of what conventions were used in other contexts. Thanks, Scott, much appreciated. From rustompmody at gmail.com Wed Aug 5 11:18:05 2009 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 5 Aug 2009 20:48:05 +0530 Subject: error return from urlopen Message-ID: When I direct urlopen to a non-existent server process I get IOError: [Errno socket error] (10061, 'Connection refused') The connection refused is as expected but whats the 10061? strerror(10061) says 'unknown error' So its like an errno but not quite an errno? Can I find out more about this number like I can about errno? From Scott.Daniels at Acm.Org Wed Aug 5 11:18:55 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 05 Aug 2009 08:18:55 -0700 Subject: trouble with complex numbers In-Reply-To: References: <24821423.post@talk.nabble.com> Message-ID: alex23 wrote: > Piet van Oostrum wrote: >> That should be z += 0j > > Pardon my ignorance, but could anyone explain the rationale behind > using 'j' to indicate the imaginary number (as opposed to the more > intuitive 'i')? > > (Not that I've had much call to use complex numbers but I'm > curious....) I think it explained in the complex math area, but basically EE types use j, math types use i for exactly the same thing. Since i is so frequently and index in CS, and there is another strong convention, why not let the EE types win? --Scott David Daniels Scott.Daniels at Acm.Org From robin at reportlab.com Wed Aug 5 11:18:55 2009 From: robin at reportlab.com (Robin Becker) Date: Wed, 05 Aug 2009 16:18:55 +0100 Subject: Is it possible to produce spider plots? In-Reply-To: References: Message-ID: <4A79A2DF.5010908@chamonix.reportlab.co.uk> dp_pearce wrote: > I want to be able to use Python to produce Spider plots (perhaps you > know them as radar plots or star plots). Does anyone know how to > achieve this? Are there existing libraries? > > Direction to any examples, especially those with tutorials, would be > greatly appreciated. > > Cheers, ...... reportlab has a spider chart in reportlab/graphics/charts/spider.py -- Robin Becker From marduk at letterboxes.org Wed Aug 5 11:28:22 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Wed, 05 Aug 2009 11:28:22 -0400 Subject: error return from urlopen In-Reply-To: References: Message-ID: <1249486102.23428.3.camel@brotherus.corp.redhat.com> On Wed, 2009-08-05 at 20:48 +0530, Rustom Mody wrote: > When I direct urlopen to a non-existent server process I get > > IOError: [Errno socket error] (10061, 'Connection refused') > The connection refused is as expected but whats the 10061? > strerror(10061) says 'unknown error' > > So its like an errno but not quite an errno? > Can I find out more about this number like I can about errno? http://msdn.microsoft.com/en-us/library/ms740668(VS.85).aspx From tim.arnold at sas.com Wed Aug 5 11:30:07 2009 From: tim.arnold at sas.com (Tim Arnold) Date: Wed, 5 Aug 2009 11:30:07 -0400 Subject: oNVDL validation docbook 5 Message-ID: Hi, I'm using the oNVDL java validator for my DocBook 5.0 documents. Otherwise, my doc system is python. I wonder if there is any work going on (or perhaps something I'm missing) to use python to validate DocBook 5 (using the rng files bundled with the DocBook5 distribution) I think the catch with DocBook 5 rng is that it has embedded Schematron rules, which makes lxml not able to validate. I'm out of my depth here, but that's what I've heard. Anyway, I'd sure like to streamline this using python rather than a subprocess call out to that java validator. Any suggestions or pointers welcome. thanks, --Tim Arnold From jkn_gg at nicorp.f9.co.uk Wed Aug 5 11:33:48 2009 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Wed, 5 Aug 2009 08:33:48 -0700 (PDT) Subject: Is it possible to produce spider plots? References: Message-ID: On Aug 5, 3:51?pm, dp_pearce wrote: > I want to be able to use Python to produce Spider plots (perhaps you > know them as radar plots or star plots). Does anyone know how to > achieve this? Are there existing libraries? > The 'wxPython in Action' book has some simple example code which produces this sort of graphic. If you are after a GUI application rather than creating a paper copy it might be worth checking this out. HTH J^n From tack at urandom.ca Wed Aug 5 11:38:13 2009 From: tack at urandom.ca (Jason Tackaberry) Date: Wed, 05 Aug 2009 11:38:13 -0400 Subject: intricated functions: how to share a variable In-Reply-To: <7dt5rqF2crv46U1@mid.uni-berlin.de> References: <7dt5rqF2crv46U1@mid.uni-berlin.de> Message-ID: <1249486693.7120.789.camel@arrakis> On Wed, 2009-08-05 at 12:39 +0200, Diez B. Roggisch wrote: > Another often used trick is to have a mutable container-object, like this: > > def tutu(): > a = [2] > > def toto(): > a[0] = 4 > > toto() When you need a writable bound variable inside a closure, I prefer this idiom: def foo(): def bar(): print bar.a bar.a = 4 print bar.a bar.a = 2 bar() Python 3's nonlocal is obviously much more elegant. Cheers, Jason. From joncle at googlemail.com Wed Aug 5 11:39:07 2009 From: joncle at googlemail.com (Jon Clements) Date: Wed, 5 Aug 2009 08:39:07 -0700 (PDT) Subject: Parsing Binary Structures; Is there a better way / What is your way? References: Message-ID: <9bca27b8-e71d-4b71-a792-d9ca7be18ab3@24g2000yqm.googlegroups.com> On 5 Aug, 15:46, "Martin P. Hellwig" wrote: > Hi List, > > On several occasions I have needed (and build) a parser that reads a > binary piece of data with custom structure. For example (bogus one): > > BE > +---------+---------+-------------+-------------+------+--------+ > | Version | Command | Instruction | Data Length | Data | Filler | > +---------+---------+-------------+-------------+------+--------+ > Version: 6 bits > Command: 4 bits > Instruction: 5 bits > Data Length: 5 bits > Data: 0-31 bits > Filler: filling 0 bits to make the packet dividable by 8 > > what I usually do is read the packet in binary mode, convert the output > to a concatenated 'binary string'(i.e. '0101011000110') and then use > slice indeces to get the right data portions. > Depending on what I need to do with these portions I convert them to > whatever is handy (usually an integer). > > This works out fine for me. Most of the time I also put the ASCII art > diagram of this 'protocol' as a comment in the code, making it more > readable/understandable. > > Though there are a couple of things that bothers me with my approach: > - This seems such a general problem that I think that there must be > already a general pythonic solution. > - Using a string for binary representation takes at least 8 times more > memory for the packet than strictly necessary. > - Seems to need a lot of prep work before doing the actual parsing. > > Any suggestion is greatly appreciated. > > -- > MPHhttp://blog.dcuktec.com > 'If consumed, best digested with added seasoning to own preference.' IIRC (and I have my doubts) the BitVector module may be of use, but it's been about 3 years since I had to look at it. I think it used the C equiv. of short ints to do its work. Otherwise, maybe the array module, the struct module or even possibly ctypes. Not much use, but might give a few pointers. Jon. From kosta.koeman at gmail.com Wed Aug 5 11:39:15 2009 From: kosta.koeman at gmail.com (Kosta) Date: Wed, 5 Aug 2009 08:39:15 -0700 (PDT) Subject: Using Python to automate builds References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> <200908050956.33995.hendrik@microcorp.co.za> <5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> Message-ID: On Aug 5, 7:29?am, Hendrik van Rooyen wrote: > On Wednesday 05 August 2009 14:08:18 David Cournapeau wrote: > > > On Wed, Aug 5, 2009 at 4:56 PM, Hendrik van > > > Rooyen wrote: > > > On Tuesday 04 August 2009 21:13:10 Kosta wrote: > > >> I am a Python newbie, tasked with automating (researching) building > > >> Windows drivers using the WDK build environment. ?I've been looking > > >> into Python for this (instead of writing a bunch of batch files). > > > > Why do you not use make and a makefile - it was designed to > > > do exactly this. > > > Because make is a pain on windows (lack of a proper shell) ? > > Well, you could always use Dosbox - I am doing exactly that > on Linux to be able to run some old DOS based assembler > tools. ?It will run on windows too, they claim. > > And it is very simple to use too - no fancy fidgeting, all you have > to do is to point it at a directory that becomes your "C" drive. > > Bit slow - but hey, nobody's perfect. > > - Hendrik Sorry for not being more clear. The WDK provides build.exe, a utility that calls the compiler & linker with the approprite switches. In essence, it manages all the nmake details away from the developer. For some, this is a bad thing in terms of loss of control. But in reality, this is a great thing, as this is the way Microsoft builds Windows. As far as I can tell, the WDK build environment is dervied from the Microsoft Windows build environment, which is great for developing kernel components in the similar enviornment in which Microsoft builds its OS. It is a requirement to use the WDK. Setenv.bat sets up the path and other environment variables build.exe needs to compile and link (and even binplace) its utilities. So building itself is not the issue. The problem is that if I call setenv.bat from Python and then build.exe, but the modifications to the path (and other environment settings) are not seen by Python, so the attempt to build without a specified path fails. Now I can open up a build window that targets a build type (check or release), an architecture target (x86 or x64) and an OS target (which will be Windows Xp except if in the future, the driver(s) uses some infrastructure introduced in later versions of WDM. However, what I was hoping to do was to have a python script that would allow me to build 4 versions of the driver: x86 check, x86 release, x64 check, and x64 release. I may have to resort to using batch files, but I was hoping as much as possible to use Python. Thanks, Kosta From breamoreboy at yahoo.co.uk Wed Aug 5 11:52:08 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 05 Aug 2009 16:52:08 +0100 Subject: Overlap in python In-Reply-To: References: <4a7892c2$0$2297$91cee783@newsreader02.highway.telekom.at> Message-ID: Jay Bird wrote: > Hi everyone, > > I wanted to thank you all for your help and *excellent* discussion. I > was able to utilize and embed the script by Grigor Lingl in the 6th > post of this discussion to get my program to work very quickly (I had > to do about 20 comparisons per data bin, with over 40K bins in > total). I am involved in genomic analysis research and this problem > comes up a lot and I was surprised to not have been able to find a > clear way to solve it. I will also look through all the tips in this > thread, I have a feeling they may come in handy for future use! > > Thank you again, > Jay I don't know if this is relevant, but http://planet.python.org/ has an entry dated this morning which points here http://www.logarithmic.net/pfh/blog/01249470842. HTH. -- Kindest regards. Mark Lawrence. From tack at urandom.ca Wed Aug 5 11:53:56 2009 From: tack at urandom.ca (Jason Tackaberry) Date: Wed, 05 Aug 2009 11:53:56 -0400 Subject: unicode() vs. s.decode() In-Reply-To: References: Message-ID: <1249487636.7120.798.camel@arrakis> On Wed, 2009-08-05 at 16:43 +0200, Michael Str?der wrote: > These both expressions are equivalent but which is faster or should be used > for any reason? > > u = unicode(s,'utf-8') > > u = s.decode('utf-8') # looks nicer It is sometimes non-obvious which constructs are faster than others in Python. I also regularly have these questions, but it's pretty easy to run quick (albeit naive) benchmarks to see. The first thing to try is to have a look at the bytecode for each: >>> import dis >>> dis.dis(lambda s: s.decode('utf-8')) 1 0 LOAD_FAST 0 (s) 3 LOAD_ATTR 0 (decode) 6 LOAD_CONST 0 ('utf-8') 9 CALL_FUNCTION 1 12 RETURN_VALUE >>> dis.dis(lambda s: unicode(s, 'utf-8')) 1 0 LOAD_GLOBAL 0 (unicode) 3 LOAD_FAST 0 (s) 6 LOAD_CONST 0 ('utf-8') 9 CALL_FUNCTION 2 12 RETURN_VALUE The presence of LOAD_ATTR in the first form hints that this is probably going to be slower. Next, actually try it: >>> import timeit >>> timeit.timeit('"foobarbaz".decode("utf-8")') 1.698289155960083 >>> timeit.timeit('unicode("foobarbaz", "utf-8")') 0.53305888175964355 So indeed, uncode(s, 'utf-8') is faster by a fair margin. On the other hand, unless you need to do this in a tight loop several tens of thousands of times, I'd prefer the slower form s.decode('utf-8') because it's, as you pointed out, cleaner and more readable code. Cheers, Jason. From J.Fine at open.ac.uk Wed Aug 5 12:03:13 2009 From: J.Fine at open.ac.uk (Jonathan Fine) Date: Wed, 05 Aug 2009 17:03:13 +0100 Subject: Do anyone here use Python *embedded* in a database? In-Reply-To: <767b6862-065f-480a-82f5-ed3aa35bf84d@n11g2000yqb.googlegroups.com> References: <767b6862-065f-480a-82f5-ed3aa35bf84d@n11g2000yqb.googlegroups.com> Message-ID: Jon Clements wrote: > On 5 Aug, 13:17, Jonathan Fine wrote: >> Hi >> >> I'm writing a talk that compares embed and extend, and wondered if >> anyone here ever used the Python *embedded* in a database server. >> http://twistedmatrix.com/users/glyph/rant/extendit.html >> >> Web frameworks (such as Django) use extend, to import an extension >> module that makes a connection to a database. >> >> If you have used embed, you might have consulted a page such as: >> http://www.postgresql.org/docs/8.3/interactive/plpython-funcs.html >> >> -- >> Jonathan > > Yup, have used plpythonu within postgres without too many problems. > Although I do recall once that using the CSV module to load and filter > external data, did consume a massive amount of memory. Even though the > entire procedure was iterator based -- never did work out if it was > postgres caching, or some other weird stuff. [That was about 2 years > ago though] Thanks, Jon, for that. -- Jonathan From lawrencew00 at hotmail.com Wed Aug 5 12:07:39 2009 From: lawrencew00 at hotmail.com (Lawrence Wong) Date: Wed, 5 Aug 2009 16:07:39 +0000 Subject: os.system in a service Message-ID: Hi, I wrote a program which runs a .bat file using os.system like: 'os.system(pathToBatFile)' and everything was good. Then I decided to turn my program into a service as opposed to being run with the command prompt showing. When my program became a service, I noticed that the os.system command to run my .bat file was no longer working. By 'not working' I mean no exception is thrown, but it was as if the line with os.system(pathToBatFile) did not exist. I was wondering why this is and if there is a way to fix this or what an alternative to using os.system to run my .bat file was? LW . . . Lawrence _________________________________________________________________ Send and receive email from all of your webmail accounts. http://go.microsoft.com/?linkid=9671356 -------------- next part -------------- An HTML attachment was scrubbed... URL: From rays at blue-cove.com Wed Aug 5 12:21:35 2009 From: rays at blue-cove.com (RayS) Date: Wed, 05 Aug 2009 09:21:35 -0700 Subject: Cypress FX2 - py libusb code? In-Reply-To: <5.2.1.1.2.20090804224315.01c22b60@pop-server.san.rr.com> Message-ID: <5.2.1.1.2.20090805091843.01c76cc8@blue-cove.com> An HTML attachment was scrubbed... URL: -------------- next part -------------- """ To run the single C file USB bulk read program properly, you must provide a source of data to the CY7C68013 FIFO bus, like the Simple dual channel A/D system, otherwise the reading call will time out in one second, you will get a bunch of zeros, and the ninth status number will be something negative instead of 512. """ import sys import os import time import usb def PrintDevInfo(dev): """Print device information.""" print "Device:", dev.filename print " Device class:",dev.deviceClass print " Device sub class:",dev.deviceSubClass print " Device protocol:",dev.deviceProtocol print " Max packet size:",dev.maxPacketSize print " idVendor:",dev.idVendor print " idProduct:",dev.idProduct print " Device Version:",dev.deviceVersion print " Device SerialNumber:",dev.iSerialNumber for config in dev.configurations: print " Configuration:", config.value print " Total length:", config.totalLength print " selfPowered:", config.selfPowered print " remoteWakeup:", config.remoteWakeup print " maxPower:", config.maxPower for intf in config.interfaces: print " Interface:",intf[0].interfaceNumber for alt in intf: print " Alternate Setting:",alt.alternateSetting print " Interface class:",alt.interfaceClass print " Interface sub class:",alt.interfaceSubClass print " Interface protocol:",alt.interfaceProtocol for ep in alt.endpoints: print " Endpoint:",hex(ep.address) print " Type:",ep.type print " Max packet size:",ep.maxPacketSize print " Interval:",ep.interval firmware = [0x90, 0xE6, 0x0B, 0x74, 0x03, 0xF0, ##REVCTL = 0x03 0x90, 0xE6, 0x04, 0x74, 0x80, 0xF0, ##FIFORESET = 0x80 0x74, 0x08, 0xF0, ##FIFORESET = 0x08 0xE4, 0xF0, ##FIFORESET = 0x00 0x90, 0xE6, 0x01, 0x74, 0xCB, 0xF0, ##IFCONFIG = 0xCB 0x90, 0xE6, 0x1B, 0x74, 0x0D, 0xF0, ##EP8FIFOCFG = 0x0D #0x90, 0xE6, 0x09, 0x74, 0x10, 0xF0, ##FIFOPINPOLAR = 0x10 TRUST!!! 0x80, 0xFE] ##while (1) {} reset = 0x01 er = [] endpoint = 8 # find all of the USB busses busses = usb.busses() #print busses # Find one device rdev = None for bus in busses: for dev in bus.devices: if dev.idVendor == 0x04B4 and dev.idProduct == 0x8613: rdev = dev if rdev==None: print "Could not find a CY7C68013\ndev.idVendor == 0x04B4 and dev.idProduct == 0x8613" sys.exit() else: dev = rdev #PrintDevInfo(dev) endpoint=8 current_handle = dev.open() requestType = 0x40 request = 0xa0 #buffer = ''.zfill(4096) value=0 index=0 timeout=1000 er.append(('RESET', current_handle.controlMsg(requestType, request, reset, value, index, timeout) ))##RESET time.sleep(0.1) for i in range(len(firmware)): #er.append(('ctrlMsg', i, current_handle.controlMsg(0x40, 0xa0, firmware[i], value=i, index=0))) er.append(('ctrlMsg', i, len(current_handle.controlMsg(0x40, 0xa0, firmware[i], value=i, index=0)))) er.append(('UNRESET', current_handle.controlMsg(requestType, request, reset+1, value, index, timeout))) ##UNRESET time.sleep(0.1) # we know that there's one config, one interface, and one endpoint conf = dev.configurations[0] er.append(( "confs", len(dev.configurations))) er.append(conf.interfaces.count(0))#, conf.interfaces.index(1) iface = conf.interfaces[0][1] er.append( ("ifaces[0]", len(conf.interfaces[0]))) endpoint = iface.endpoints[1] er.append(( "endpoints", len(iface.endpoints))) er.append(( "iin", iface.interfaceNumber)) er.append( current_handle.setConfiguration(conf)) er.append( current_handle.claimInterface(iface)) er.append( current_handle.setAltInterface(iface)) try: er.append( current_handle.bulkRead(endpoint.address, 512, 1000)) except usb.USBError, e: print ' bulkRead error: ', e.args print ' return data:' for e in er: print ' ', e PrintDevInfo(dev) sys.exit() for i in range(512): print " %02x " % buffer[i], current_handle.releaseInterface(0) dev.close() print "\n status: ", er[-1] From breamoreboy at yahoo.co.uk Wed Aug 5 12:30:24 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 05 Aug 2009 17:30:24 +0100 Subject: Is it possible to produce spider plots? In-Reply-To: References: Message-ID: dp_pearce wrote: > I want to be able to use Python to produce Spider plots (perhaps you > know them as radar plots or star plots). Does anyone know how to > achieve this? Are there existing libraries? > > Direction to any examples, especially those with tutorials, would be > greatly appreciated. > > Cheers, > Dan > > http://www.answers.com/topic/spider-plot How about http://matplotlib.sourceforge.net/examples/api/radar_chart.html?highlight=spider -- Kindest regards. Mark Lawrence. From tim.arnold at sas.com Wed Aug 5 12:34:18 2009 From: tim.arnold at sas.com (Tim Arnold) Date: Wed, 5 Aug 2009 12:34:18 -0400 Subject: Using Python to automate builds References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> Message-ID: "Kosta" wrote in message news:84d9ae10-3aee-40a8-97ac-05799da0de64 at f18g2000prf.googlegroups.com... >I am a Python newbie, tasked with automating (researching) building > Windows drivers using the WDK build environment. I've been looking > into Python for this (instead of writing a bunch of batch files). > > What I would like to do, is to open a cmd window, and start a Python > script. This script would then (based upon input arguments), build > different flavors of the driver (fre, chk, x86, x64) and do some post > processing (create cat files, sign, etc.). > > I was hoping to take advantage as much as possible of exisiting > infrastructure from the WDK. I am able to call setenv.bat and provide > all the input parameters. One of the things setenv.bat does is change > the path environment variable. However, this is not captured by > Python. I could duplicate the functionality, but I'd rather not. Is > there a way to capture all enviroment variable changes being made by a > batch file from Python? > > Thanks! It sounds like you know what you're doing. I just wanted to point out that you can specify environment dictionaries in the subprocess.Popen module. You can set a different dictionary for each call you make to the system. Not sure if that helps, --Tim From martin.hellwig at dcuktec.org Wed Aug 5 13:05:08 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 05 Aug 2009 18:05:08 +0100 Subject: Parsing Binary Structures; Is there a better way / What is your way? In-Reply-To: <9bca27b8-e71d-4b71-a792-d9ca7be18ab3@24g2000yqm.googlegroups.com> References: <9bca27b8-e71d-4b71-a792-d9ca7be18ab3@24g2000yqm.googlegroups.com> Message-ID: Jon Clements wrote: > IIRC (and I have my doubts) the BitVector module may be of use, but > it's been about 3 years since I had to look at it. I think it used the > C equiv. of short ints to do its work. Otherwise, maybe the array > module, the struct module or even possibly ctypes. > > Not much use, but might give a few pointers. > > Jon. I tried struct before (it seemed logical) but it didn't really do what I expected: >>> import struct >>> struct.unpack('?','x') (True,) I expected a list like (False, True, True, True, True, False, False, False). But it is (actually I hope) just an error of my side, so if somebody knows how to achieve what I want, with this module, please enlighten me :-) The array module doesn't seem to have an option for boolean values. BitVector does look very promising, but after peeking in the source it does more or less the same as what I do with converting back and forth of 'bitstrings'. I haven't thought about using ctypes for this, excellent suggestion! Thank you for your feedback. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From deets at nospam.web.de Wed Aug 5 13:16:54 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Aug 2009 19:16:54 +0200 Subject: access string data from within cython Message-ID: <7dtt46F2e5osvU1@mid.uni-berlin.de> Hi, I'm trying to wrap a C-API which has a call that takes a void* and a size_t as arguments. void foo(void *data, size_t length) The wrapper is supposed to be called with a python (byte)string instance, which might contain more than one '\0'-character. So how do I access the raw data of a string? I tried looking into the buffer-protocol, but to be honest - that's beyond me, I don't see where that is actually giving me access to the real data. Diez From bearophileHUGS at lycos.com Wed Aug 5 13:17:29 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Wed, 5 Aug 2009 10:17:29 -0700 (PDT) Subject: Parsing Binary Structures; Is there a better way / What is your way? References: Message-ID: <50e27473-926b-458a-84f2-927ad02a0ed8@c14g2000yqm.googlegroups.com> Martin P. Hellwig: > On several occasions I have needed (and build) a parser that reads a > binary piece of data with custom structure. For example (bogus one): > > BE > +---------+---------+-------------+-------------+------+--------+ > | Version | Command | Instruction | Data Length | Data | Filler | > +---------+---------+-------------+-------------+------+--------+ > Version: 6 bits > Command: 4 bits > Instruction: 5 bits > Data Length: 5 bits > Data: 0-31 bits > Filler: filling 0 bits to make the packet dividable by 8 Have you tried Hachoir? (I think its name may be changed to Fusil, I don't know). Bye, bearophile From masklinn at masklinn.net Wed Aug 5 13:22:42 2009 From: masklinn at masklinn.net (Masklinn) Date: Wed, 5 Aug 2009 19:22:42 +0200 Subject: Parsing Binary Structures; Is there a better way / What is your way? In-Reply-To: References: Message-ID: <934952CA-AC59-415C-A5D8-AEF74A0033FD@masklinn.net> On 5 Aug 2009, at 16:46 , Martin P. Hellwig wrote: > Hi List, > > On several occasions I have needed (and build) a parser that reads a > binary piece of data with custom structure. For example (bogus one): > > BE > +---------+---------+-------------+-------------+------+--------+ > | Version | Command | Instruction | Data Length | Data | Filler | > +---------+---------+-------------+-------------+------+--------+ > Version: 6 bits > Command: 4 bits > Instruction: 5 bits > Data Length: 5 bits > Data: 0-31 bits > Filler: filling 0 bits to make the packet dividable by 8 > > what I usually do is read the packet in binary mode, convert the > output to a concatenated 'binary string'(i.e. '0101011000110') and > then use slice indeces to get the right data portions. > Depending on what I need to do with these portions I convert them to > whatever is handy (usually an integer). > > This works out fine for me. Most of the time I also put the ASCII > art diagram of this 'protocol' as a comment in the code, making it > more readable/understandable. > > Though there are a couple of things that bothers me with my approach: > - This seems such a general problem that I think that there must be > already a general pythonic solution. > - Using a string for binary representation takes at least 8 times > more memory for the packet than strictly necessary. > - Seems to need a lot of prep work before doing the actual parsing. > > Any suggestion is greatly appreciated. The gold standard for binary parsing (and serialization) is probably Erlang's bit syntax, but as far as Python goes you might be interested by Hachoir (http://hachoir.org/ but it seems down right now). It's not going to match your second point, but it can probably help with the rest (caveat: I haven't used hachoir personally). From masklinn at masklinn.net Wed Aug 5 13:26:53 2009 From: masklinn at masklinn.net (Masklinn) Date: Wed, 5 Aug 2009 19:26:53 +0200 Subject: Parsing Binary Structures; Is there a better way / What is your way? In-Reply-To: <50e27473-926b-458a-84f2-927ad02a0ed8@c14g2000yqm.googlegroups.com> References: <50e27473-926b-458a-84f2-927ad02a0ed8@c14g2000yqm.googlegroups.com> Message-ID: <7120B941-0C12-47ED-9505-08914EBD9CFB@masklinn.net> On 5 Aug 2009, at 19:17 , Bearophile wrote: > Have you tried Hachoir? (I think its name may be changed to Fusil, I > don't know). Name hasn't been changed (I think fusil is a subproject, something like that) on the other hand the hachoir.org site is dead. But apparently Hachoir was moved to bitbucket (http://bitbucket.org/haypo/hachoir/wiki/Home ) just in time so? From mensanator at aol.com Wed Aug 5 13:33:07 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 5 Aug 2009 10:33:07 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> <4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> Message-ID: > It didn't form 2.5 to 2.6 (at least not intentionally). But with the > indroduction of the TurtleScreen class and the Screen class/object > (singleton) a few of the turtle methods were also implemented as screen > methods and as turtle methods declared deprecated (see docs of Python > 2.6). These deprecated turtle methods do not occur as turtle methods any > more in Python 3.x. More info. Yes, there is no tracer attribute...when the object is created. But watch this (Python 3.1): >>> import turtle >>> tooter = turtle.Turtle() >>> tooter.tracer Traceback (most recent call last): File "", line 1, in tooter.tracer AttributeError: 'Turtle' object has no attribute 'tracer' >>> tooter.hideturtle() >>> tooter.speed('fast') >>> turtle.update() >>> turtle.tracer Now, after setting hide, speed, update, a tracer exists. Is that supposed to happen? That explains why there was no error when I set the turtle attribute instead of the screen attribute. And, of course, setting the turtle attribute accomplishes nothing, as actual tracing is controlled by the screen attribute as you say. > > Among them is the tracer method, which in fact does not control single > turtle objects but all the turtles on a given screen. > > So there is an icompatibility beween 2.6 and 3.x > > But as far as I have understood, this doesn't concern the problem > reported by mensator. Only that the problem is hidden when tracing is off, as the nhops variable is never evaluated when trace is off. > > Regards, > Gregor From gregor.lingl at aon.at Wed Aug 5 13:56:50 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Wed, 05 Aug 2009 19:56:50 +0200 Subject: Turtle Graphics are incompatible with gmpy In-Reply-To: References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> <4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> Message-ID: <4A79C7E2.3000406@aon.at> Mensanator schrieb: >> It didn't form 2.5 to 2.6 (at least not intentionally). But with the >> indroduction of the TurtleScreen class and the Screen class/object >> (singleton) a few of the turtle methods were also implemented as screen >> methods and as turtle methods declared deprecated (see docs of Python >> 2.6). These deprecated turtle methods do not occur as turtle methods any >> more in Python 3.x. > > More info. > > Yes, there is no tracer attribute...when the object is created. > > But watch this (Python 3.1): > >>>> import turtle >>>> tooter = turtle.Turtle() >>>> tooter.tracer > Traceback (most recent call last): > File "", line 1, in > tooter.tracer > AttributeError: 'Turtle' object has no attribute 'tracer' >>>> tooter.hideturtle() >>>> tooter.speed('fast') >>>> turtle.update() >>>> turtle.tracer > > > Now, after setting hide, speed, update, a tracer exists. No, >>> import turtle >>> turtle.tracer >>> help(turtle.tracer) Help on function tracer in module turtle: tracer(n=None, delay=None) Turns turtle animation on/off and set delay for update drawings. Optional arguments: n -- nonnegative integer delay -- nonnegative integer If n is given, only each n-th regular screen update is really performed. (Can be used to accelerate the drawing of complex graphics.) Second arguments sets delay value.) Example: >>> tracer(8, 25) >>> dist = 2 >>> for i in range(200): fd(dist) rt(90) dist += 2 >>> The reason for this is, that the turtle module (the new one as well as the old one) has a vers special design: The methods of class Turtle are also available as functions (which are in fact methods calls of an anonymous turtle). The same holds for the methods of TurtleScreen. The intention behind this design is that you can use the module in an OOP way as well as with procedural programming (especially for beginners). When using objects I normally use from turtle import Turtle, Screen screen = Screen() # that creates singleton object, the screen the turtle acts on and I create as many turtles as I need from the Turtle class So turtle.tracer() doesn't make sense anymore > Is that supposed to happen? That explains why there was no error > when I set the turtle attribute instead of the screen attribute. You do not 'set the turtle attribute', you call the tracer function of the turtle module > And, of course, setting the turtle attribute accomplishes nothing, > as actual tracing is controlled by the screen attribute as you say. > >> Among them is the tracer method, which in fact does not control single >> turtle objects but all the turtles on a given screen. >> >> So there is an icompatibility beween 2.6 and 3.x >> >> But as far as I have understood, this doesn't concern the problem >> reported by mensator. > > Only that the problem is hidden when tracing is off, as the nhops > variable is never evaluated when trace is off. Nevertheless I'd like to see a working Python 2.5 version of your script. Regards, Gregor From http Wed Aug 5 14:12:05 2009 From: http (Paul Rubin) Date: 05 Aug 2009 11:12:05 -0700 Subject: Parsing Binary Structures; Is there a better way / What is your way? References: Message-ID: <7x3a86gmfe.fsf@ruckus.brouhaha.com> "Martin P. Hellwig" writes: > what I usually do is read the packet in binary mode, convert the > output to a concatenated 'binary string'(i.e. '0101011000110') and Something wrong with reading the data words as an integer and using old fashioned shifts and masks to get at the bit fields? From 1x7y2z9 at gmail.com Wed Aug 5 14:12:45 2009 From: 1x7y2z9 at gmail.com (1x7y2z9) Date: Wed, 5 Aug 2009 11:12:45 -0700 (PDT) Subject: unicode() vs. s.decode() References: Message-ID: unicode() has LOAD_GLOBAL which s.decode() does not. Is it generally the case that LOAD_ATTR is slower than LOAD_GLOBAL that lead to your intuition that the former would probably be slower? Or some other intuition? Of course, the results from timeit are a different thing - I ask about the intuition in the disassembler output. Thanks. > > The presence of LOAD_ATTR in the first form hints that this is probably > going to be slower. ? Next, actually try it: > From piet at cs.uu.nl Wed Aug 5 14:20:47 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Aug 2009 20:20:47 +0200 Subject: Special chars with HTMLParser References: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com> <69835fa3-c6a0-44d3-bba2-5e3117102590@k30g2000yqf.googlegroups.com> Message-ID: >>>>> Fafounet (F) wrote: >F> Thank you, now I can get the correct character. >F> Now when I have the string abécd I can get ab then ? thanks to >F> your function and then cd. But how is it possible to know that cd is >F> still the same word ? That depends on your definition of `word'. And that is language-dependent. What you normally do is collect the text in a (unicode) string variable. This happens in handle_data, handle_charref and handle_entityref. Then you check that the previously collected stuff was a word (e.g. consisting of Unicode letters), and that the new stuff also consists of letters. If your language has additional word constituents like - or ' you have to add this. You can do this with unicodedata.category or with a regular expression. If your locale is correct \w in a regular expression may be helpful. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From dp_pearce at hotmail.com Wed Aug 5 14:21:50 2009 From: dp_pearce at hotmail.com (Devon_Dan) Date: Wed, 5 Aug 2009 11:21:50 -0700 (PDT) Subject: Is it possible to produce spider plots? References: Message-ID: <2481d12e-6af9-4dbb-991d-fb636c3b6831@k6g2000yqn.googlegroups.com> > reportlab has a spider chart in reportlab/graphics/charts/spider.py > How about > http://matplotlib.sourceforge.net/examples/api/radar_chart.html?highl... Both exactly what I was after. Thanks very much. > The 'wxPython in Action' book has some simple example code which > produces this sort of graphic. If you are after a GUI application > rather than creating a paper copy it might be worth checking this out. Thanks for this one jkn. I actually have this book and went through it looking to see if it had an answer before posting. Completely missed it! Clearly I need to RTFM more closely next time. From philip at semanchuk.com Wed Aug 5 14:25:27 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 5 Aug 2009 14:25:27 -0400 Subject: access string data from within cython In-Reply-To: <7dtt46F2e5osvU1@mid.uni-berlin.de> References: <7dtt46F2e5osvU1@mid.uni-berlin.de> Message-ID: On Aug 5, 2009, at 1:16 PM, Diez B. Roggisch wrote: > Hi, > > I'm trying to wrap a C-API which has a call that takes a void* and a > size_t > as arguments. > > void foo(void *data, size_t length) > > > The wrapper is supposed to be called with a python (byte)string > instance, > which might contain more than one '\0'-character. > > So how do I access the raw data of a string? I tried looking into the > buffer-protocol, but to be honest - that's beyond me, I don't see > where > that is actually giving me access to the real data. Hi Diez, Would ctypes.create_string_buffer() work for you? bye P From jeremy.cowles at gmail.com Wed Aug 5 14:31:38 2009 From: jeremy.cowles at gmail.com (Jeremy Cowles) Date: Wed, 5 Aug 2009 11:31:38 -0700 Subject: Install setup tools for 2.6 Message-ID: <373cf0740908051131gacaf77apba48fa40e929f491@mail.gmail.com> Ok, I feel like this is a really stupid question, but how do you install setup tools for Python 2.6 under windows? The only format is .egg which requires setup tools to install, doesn't it? Thanks, Jeremy -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin.hellwig at dcuktec.org Wed Aug 5 14:46:12 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 05 Aug 2009 19:46:12 +0100 Subject: Parsing Binary Structures; Is there a better way / What is your way? In-Reply-To: <7x3a86gmfe.fsf@ruckus.brouhaha.com> References: <7x3a86gmfe.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Martin P. Hellwig" writes: >> what I usually do is read the packet in binary mode, convert the >> output to a concatenated 'binary string'(i.e. '0101011000110') and > > Something wrong with reading the data words as an integer and using > old fashioned shifts and masks to get at the bit fields? No not at all of course, I just found it more readable to slice it instead of shifting and masking; i.e. if the ASCII art schematics of the protocol are included as a comment it is almost an 1 to 1 implementation. Is there an advantage using shifts and masks over my kitchen type solution? -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From ihatespam at hotmail.com Wed Aug 5 14:47:58 2009 From: ihatespam at hotmail.com (Just Another Victim of the Ambient Morality) Date: Wed, 5 Aug 2009 14:47:58 -0400 Subject: Confessions of a Python fanboy References: <008e82e8$0$9756$c3e8da3@news.astraweb.com><4a72d7cf$0$25239$426a34cc@news.free.fr><008eef29$0$9756$c3e8da3@news.astraweb.com><4a77eb69$0$22600$426a74cc@news.free.fr> Message-ID: "Steven D'Aprano" wrote in message news:pan.2009.08.04.09.28.49 at REMOVE.THIS.cybersource.com.au... > On Tue, 04 Aug 2009 10:03:53 +0200, Bruno Desthuilliers wrote: > >>> Disadvantages: your code is filled with line noise. It's an arbitrary >>> choice between @@ meaning instance attribute and @@ meaning class >>> attribute -- there's no logical reason for choosing one over the other, >>> so you have to memorise which is which. It's easy to get it wrong. >> >> So far that's something I have no difficulty living with. > > I don't like arbitrary symbols. Most people don't -- that's why "line > noise" is unpopular. It's hard to read, hard to write, hard to maintain, > and hard to talk about. The more line-noise, the worse the language. It's not "line noise" if it conveys information... > Of course, *ultimately* every symbol is arbitrary. There's no reason why > "2" should mean the integer two, or "list" should mean a sequence type, > but some symbols have such a long history, or have some other connection > (say, with human languages), that the arbitrariness is lost. For > instance, "+" is the obvious, non-arbitrary choice for the addition > operator in any programming language using Latin symbols, and probably > any programming language on Earth. (Not the *only* choice, but the > obvious one.) > > I have a similar dislike for decorator syntax, because "@" ("at" in > English) has nothing to do with decorations. It's an arbitrary symbol. > One might argue that "$" would have been a more logical choice, because > we turn numerals into currency by decorating it with a $ sign. (At least > in the US, Canada, Australia, and a few other countries.) I use > decorators all the time, and they are a fantastic invention, but the > arbitrariness of the @ syntax is a negative. Oh well, one negative out of > a whole lot of positives isn't too bad. You can think of "@" as describing something being "at" the instance or the class. "$" is totally arbitrary to me 'cause I don't thnk of my code as currency... > At least I only have to deal with *one* such arbitrary symbol that needs > memorizing. There's no need to distinguish between @@function_decorator > and @class_decorator (or should it be the other way around?). Similarly, > Python's choice of syntax for attributes is consistent: object.attribute > works for everything, whether object is a class, an instance, a module, > and whether attribute is callable or not. You can even use it on ints, > provided you are clever about it: You can think of "@" as being at an instance or "@@" to be more emphatically (as the Japanese do in their language) integrated with a class, being available to all instances... or you can simply understand that instance vairables are more common than class variables so the shorter notation is used for the more common case... You want to talk about arbitrariness? Why is len() a function you pass objects into while objects can have methods that describe themselves to you? At least Ruby defines operators using the actual name of the operator instead of you having to remember an arbitrary magic incantation that corresponds to the operator... class Test attr_reader :data def initialize(data) @data = data end # This is the operator part... def + right Test.new @data + right.data end end >>>>> Somebody who knows more Ruby than me should try writing the Zen of >>>>> Ruby. Something like: >>>> (snip childish parody of Python Zen) >>>> >>>> Steven, is that any useful ? >>> >>> It made me feel good. >> >> Why ??? >> >> You don't like Ruby ? Fine, don't use it. Period. I can't see the point >> of all these pissing contests. > > Criticism of a language is a pissing contest? > > Yeah, okay, I was a tad dismissive. I un-apologetically jump to strong > impressions about languages based on minimal use -- but I'm also willing > to change my mind. Ruby certainly looks to me like it has some nice > features. Syntax that looks like Perl isn't one of them though. Yeah, that would be the "pissing contest" part. You could simply have gone to the Ruby newsgroup and posted some criticisms to see what was behind those decisions. However, that would have avoided the pissing contest and perhaps you wanted one... >>> Just because Smalltalk had a particular (mis?)feature >> >> You can drop the 'mis' part IMHO. The point of code blocks in Smalltalk >> is that once you have something as powerful as the message+code blocks >> combo, you just don't need any other 'special form' for control flow. > > Well, maybe, but remember, programming languages are only partly for > communication to the compiler. They also have the requirement to > communicate with human programmers as well, and that's even more > important, because > > (1) humans spent a lot more time working with code than compilers do; > > (2) human programmers charge much more money than compilers do; > > (3) and you can modify the compiler to suit human needs much more easily > than you can modify programmers to suit the compiler's needs. > > So I'd ask, does Smalltalk's message passing model match the way human > beings think? If not, then that's a good sign it might be a misfeature. I think this is overstated. Not all humans think in exactly the same way so it's very presumptuous. It also ignores our intellect. We can change the way we think and we can use this versatility to our advantage. We can increase our productivity in certain tasks by changing the way we think to some other paradigm that better serves a given purpose... >>> doesn't mean that >>> other languages should copy it. >> >> Nope. But OTHO, Python is famous for all the features it copied from >> other languages !-) > > Absolutely! There's nothing wrong with copying *good* features :) The trick, of course, is figuring out which features are good! From http Wed Aug 5 14:51:06 2009 From: http (Paul Rubin) Date: 05 Aug 2009 11:51:06 -0700 Subject: Parsing Binary Structures; Is there a better way / What is your way? References: <7x3a86gmfe.fsf@ruckus.brouhaha.com> Message-ID: <7xr5vqw0v9.fsf@ruckus.brouhaha.com> "Martin P. Hellwig" writes: > Is there an advantage using shifts and masks over my kitchen type solution? Weren't you complaining about the 8-to-1 expansion from turning each bit to an ascii char? From gdamjan at gmail.com Wed Aug 5 15:05:30 2009 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Wed, 05 Aug 2009 21:05:30 +0200 Subject: String to valid Python identifier Message-ID: Is there any easy function in the stdlib to convert any random string in a valid Python identifier .. possibly by replacing non-valid characters with _ ? Python 2.x only, so no need to do Unicode. -- ?????? ( http://softver.org.mk/damjan/ ) Religion ends and philosophy begins, just as alchemy ends and chemistry begins and astrology ends, and astronomy begins. From pdlemper at earthlink.net Wed Aug 5 15:18:26 2009 From: pdlemper at earthlink.net (pdlemper at earthlink.net) Date: Wed, 05 Aug 2009 14:18:26 -0500 Subject: trouble with complex numbers References: <24821423.post@talk.nabble.com> Message-ID: <7gmj75lbijq2k8d8lk6kff7itt76n8ij13@4ax.com> On Wed, 05 Aug 2009 08:18:55 -0700, Scott David Daniels wrote: >I think it explained in the complex math area, but basically EE types >use j, math types use i for exactly the same thing. Since i is so >frequently and index in CS, and there is another strong convention, >why not let the EE types win? > >--Scott David Daniels >Scott.Daniels at Acm.Org i represents current Dave WB3DWE From sturlamolden at yahoo.no Wed Aug 5 15:23:16 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 5 Aug 2009 12:23:16 -0700 (PDT) Subject: access string data from within cython References: <7dtt46F2e5osvU1@mid.uni-berlin.de> Message-ID: <88384285-0147-470d-943f-14cfaa79219f@t13g2000yqt.googlegroups.com> On 5 Aug, 19:16, "Diez B. Roggisch" wrote: > void foo(void *data, size_t length) > > The wrapper is supposed to be called with a python (byte)string instance, > which might contain more than one '\0'-character. > > So how do I access the raw data of a string? cdef extern void foo(void *data, int length) cdef char *data cdef int length bytestring = ... #whatever rawdata = bytestring length = len(bytestring) foo(data, length) From joshua at joshuakugler.com Wed Aug 5 15:23:31 2009 From: joshua at joshuakugler.com (Joshua Kugler) Date: Wed, 05 Aug 2009 11:23:31 -0800 Subject: Subclassing Python's dict References: <2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com> Message-ID: Xavier Ho wrote: > On Thu, Aug 6, 2009 at 11:51 AM, Sergey Simonenko > wrote: > >> I subclass builtin 'dict' in my application and experience some problems >> with it. >> > > You should subclass collections.UserDict, and not the default dict class. > Refer to the collections module. Are you referring to Python 3.0? Python 2.6 does not have collections.UserDict j From sturlamolden at yahoo.no Wed Aug 5 15:25:42 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 5 Aug 2009 12:25:42 -0700 (PDT) Subject: access string data from within cython References: <7dtt46F2e5osvU1@mid.uni-berlin.de> <88384285-0147-470d-943f-14cfaa79219f@t13g2000yqt.googlegroups.com> Message-ID: <99c677b4-75eb-4a33-a1be-eecbc61c14fc@k19g2000yqn.googlegroups.com> On 5 Aug, 21:23, sturlamolden wrote: > foo(data, length) Oops, that would be foo( data, length) From joshua at joshuakugler.com Wed Aug 5 15:26:48 2009 From: joshua at joshuakugler.com (Joshua Kugler) Date: Wed, 05 Aug 2009 11:26:48 -0800 Subject: Do anyone here use Python *embedded* in a database? References: Message-ID: Jonathan Fine wrote: > Hi > > I'm writing a talk that compares embed and extend, and wondered if > anyone here ever used the Python *embedded* in a database server. > http://twistedmatrix.com/users/glyph/rant/extendit.html > > Web frameworks (such as Django) use extend, to import an extension > module that makes a connection to a database. > > If you have used embed, you might have consulted a page such as: > http://www.postgresql.org/docs/8.3/interactive/plpython-funcs.html > Yes, I've used plpython. We had a web application that had account creation logic with salting, encryption, etc, on the passwords. We then wanted to use the same accounts to log in to a Drupal site. Instead of trying to replicate the logic in PHP, I just created a stored procedure with plpython, and we overrode the drupal login check to call something like "SELECT check_account(user, pass)" which would return 1 or 0 on success or failure, respectively. Worked great. j From mensanator at aol.com Wed Aug 5 15:31:05 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 5 Aug 2009 12:31:05 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> Message-ID: On Aug 5, 2:19?am, Steven D'Aprano wrote: > On Wed, 5 Aug 2009 03:49 pm Mensanator wrote: > > > In 3.1, tracing is now a screen attribute, not a turtle atribute. > > I have no idea why > > > ? tooter = turtle.Turtle() > > ? tooter.tracer(False) > > > doesn't give me an error (I thought silent errors were a bad thing). > > What makes it an error? Do you consider the following an error? > > >>> class Test: > > ... ? ? pass > ... > > >>> t = Test() > >>> t.tracer = 5 Come on, even _I_ know this: >>> class Test: pass >>> t = Test() >>> t.tracer Traceback (most recent call last): File "", line 1, in t.tracer AttributeError: 'Test' object has no attribute 'tracer' >>> t.tracer = False >>> t.tracer False > > Perhaps you mean, it's an API change you didn't know about, and you wish to > protest that Turtle Graphics made an incompatible API change without > telling you? What does this mean? >>> import turtle >>> tooter = turtle.Turtle() >>> tooter.tracer Traceback (most recent call last): File "", line 1, in tooter.tracer AttributeError: 'Turtle' object has no attribute 'tracer' >>> tooter.hideturtle() >>> tooter.speed('fast') >>> turtle.update() >>> turtle.tracer How did the tracer attribute appear out of thin air? And more importantly, why, if has been deprecated and dropped from 3.x? > > > Naturally, having tracing on caused my program to crash. > > It seg faulted or raised an exception? Why did you snip it? Should I not refer to this as a crash? Traceback (most recent call last): File "K:\user_python26\turtle\turtle_xy_Py3.py", line 95, in tooter.goto(the_coord) File "C:\Python31\lib\turtle.py", line 1771, in goto self._goto(Vec2D(*x)) File "C:\Python31\lib\turtle.py", line 3165, in _goto nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed)) ValueError: mpq.pow fractional exponent, inexact-root > > [...] > > > Unfortunately, that calculation of nhops is illegal if diffsq is > > an .mpf (gmpy floating point). Otherwise, you get > > How does diffsq get to be a mpf? No idea. I neglected to mention I'm using the new gmpy 1.10. Don't know if that has any bearing. > Are gmpy floats supposed to be supported? Apparently not, as gmpy has only limited exponential capability. Looks like I need to change turtle.py to use math.sqrt(diffsq) or float(diffsq)**0.5. Or not pass turtle.py any .mpz since it can't handle them. > > -- > Steven From sturlamolden at yahoo.no Wed Aug 5 15:36:11 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 5 Aug 2009 12:36:11 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? References: <2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> <74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> Message-ID: <6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> On 5 Aug, 15:40, Jesse Noller wrote: > Sturla; > > That bug was fixed unless I'm missing something. It is still in SVN. Change every call to os._exit to sys.exit please. :) http://svn.python.org/view/python/branches/release26-maint/Lib/multiprocessing/forking.py?revision=66717&view=markup http://svn.python.org/view/python/branches/release31-maint/Lib/multiprocessing/forking.py?revision=73579&view=markup From sturlamolden at yahoo.no Wed Aug 5 15:40:40 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 5 Aug 2009 12:40:40 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? References: <2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> <74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> <6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> Message-ID: On 5 Aug, 21:36, sturlamolden wrote: > http://svn.python.org/view/python/branches/release26-maint/Lib/multip... > > http://svn.python.org/view/python/branches/release31-maint/Lib/multip... http://svn.python.org/view/python/trunk/Lib/multiprocessing/forking.py?revision=65864&view=markup From martin.hellwig at dcuktec.org Wed Aug 5 15:41:26 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 05 Aug 2009 20:41:26 +0100 Subject: Parsing Binary Structures; Is there a better way / What is your way? In-Reply-To: <7xr5vqw0v9.fsf@ruckus.brouhaha.com> References: <7x3a86gmfe.fsf@ruckus.brouhaha.com> <7xr5vqw0v9.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Martin P. Hellwig" writes: >> Is there an advantage using shifts and masks over my kitchen type solution? > > Weren't you complaining about the 8-to-1 expansion from turning each bit > to an ascii char? Yes you are (of course) right, my 'dream' solution would be something that accepts slice indeces on bit level. Your reasoning did reveal some flaws in my approach though ;-) -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From rylesny at gmail.com Wed Aug 5 15:48:24 2009 From: rylesny at gmail.com (ryles) Date: Wed, 5 Aug 2009 12:48:24 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? References: Message-ID: On Aug 4, 10:37?pm, erikcw wrote: > Traceback (most recent call last): > ? File "scraper.py", line 144, in > ? ? print pool.map(scrape, range(10)) > ? File "/usr/lib/python2.6/multiprocessing/pool.py", line 148, in map > ? ? return self.map_async(func, iterable, chunksize).get() > ? File "/usr/lib/python2.6/multiprocessing/pool.py", line 422, in get > ? ? raise self._value > TypeError: expected string or buffer This is almost certainly due to your scrape call raising an exception. In the parent process, multiprocessing will detect if one of its workers have terminated with an exception and then re-raise it. However, only the exception and not the original traceback is made available, which is making debugging more difficult for you. Here's a simple example which demonstrates this behavior: *** from multiprocessing import Pool *** def evil_on_8(x): ... if x == 8: raise ValueError("I DONT LIKE THE NUMBER 8") ... return x + 1 ... *** pool = Pool(processes=4) >>> pool.map(evil_on_8, range(5)) [1, 2, 3, 4, 5] *** pool.map(evil_on_8, range(10)) # 8 will cause evilness. Traceback (most recent call last): File "", line 1, in File "/bb/real/3ps/lib/python2.6/multiprocessing/pool.py", line 148, in map return self.map_async(func, iterable, chunksize).get() File "/bb/real/3ps/lib/python2.6/multiprocessing/pool.py", line 422, in get raise self._value ValueError: I DONT LIKE THE NUMBER 8 *** My recommendation is that you wrap your scrape code inside a try/ except and log any exception. I usually do this with logging.exception (), or if logging is not in use, the traceback module. After that you can simply re-raise it. From no.email at please.post Wed Aug 5 15:58:39 2009 From: no.email at please.post (kj) Date: Wed, 5 Aug 2009 19:58:39 +0000 (UTC) Subject: no-clobber dicts? References: <00027aa9$0$2969$c3e8da3@news.astraweb.com> Message-ID: In <00027aa9$0$2969$c3e8da3 at news.astraweb.com> Steven D'Aprano writes: >No problem. Here you go: >http://www.cybersource.com.au/users/steve/python/constants.py Extremely helpful. Thanks! kynn From wolfram.hinderer at googlemail.com Wed Aug 5 16:00:07 2009 From: wolfram.hinderer at googlemail.com (Wolfram Hinderer) Date: Wed, 5 Aug 2009 13:00:07 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> Message-ID: <214e2b0a-15c9-4d2b-a836-9ad75a13fc6c@r38g2000yqn.googlegroups.com> On 5 Aug., 21:31, Mensanator wrote: > > >>> import turtle > >>> tooter = turtle.Turtle() > >>> tooter.tracer > > Traceback (most recent call last): > ? File "", line 1, in > ? ? tooter.tracer > AttributeError: 'Turtle' object has no attribute 'tracer'>>> tooter.hideturtle() > >>> tooter.speed('fast') > >>> turtle.update() > >>> turtle.tracer > > > > How did the tracer attribute appear out of thin air? You seem to confuse the "tooter" Turtle object and the "turtle" module when talking about "the tracer attribute". From piet at cs.uu.nl Wed Aug 5 16:07:29 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Aug 2009 22:07:29 +0200 Subject: Is this a bug in multiprocessing or in my script? References: <2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> <74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> <6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> Message-ID: >>>>> sturlamolden (s) wrote: >s> On 5 Aug, 15:40, Jesse Noller wrote: >>> Sturla; >>> >>> That bug was fixed unless I'm missing something. >s> It is still in SVN. Change every call to os._exit to sys.exit >s> please. :) Calling os.exit in a child process may be dangerous. It can cause unflushed buffers to be flushed twice: once in the parent and once in the child. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From ethan at stoneleaf.us Wed Aug 5 16:08:00 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 05 Aug 2009 13:08:00 -0700 Subject: Turtle Graphics are incompatible with gmpy In-Reply-To: References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> Message-ID: <4A79E6A0.5040404@stoneleaf.us> Mensanator wrote: > > What does this mean? > > >>>>import turtle >>>>tooter = turtle.Turtle() >>>>*tooter*.tracer > > Traceback (most recent call last): > File "", line 1, in > tooter.tracer > AttributeError: 'Turtle' object has no attribute 'tracer' > >>>>tooter.hideturtle() >>>>tooter.speed('fast') >>>>turtle.update() >>>>*turtle*.tracer > > > > How did the tracer attribute appear out of thin air? Perhaps I am missing something (wouldn't surprise me!) but it seems that the first time you are looking for a tracer on 'tooter', and the second time you are looking for a tracer on 'turtle'. After *turtle.tracer* succeeds, does *tooter.tracer*? ~Ethan~ From no.email at please.post Wed Aug 5 16:09:25 2009 From: no.email at please.post (kj) Date: Wed, 5 Aug 2009 20:09:25 +0000 (UTC) Subject: How to combine regexps? Message-ID: One of the nice things one can do with Perl's regexp's is illustrated in the following example: my $gly = qr/gg[ucag]/i my $ala = qr/gc[ucag]/i; my $val = qr/gu[ucag]/i; my $leu = qr/uu[ag]|cu[ucag]/i; my $ile = qr/au[uca]/i; my $aliphatic = qr/$gly|$ala|$val|$leu|$ile/; In other words, one can build regular expressions by re-combining other regular expressions. Is there a way to do this with Python's regexps? TIA! kynn From aahz at pythoncraft.com Wed Aug 5 16:11:37 2009 From: aahz at pythoncraft.com (Aahz) Date: 5 Aug 2009 13:11:37 -0700 Subject: Printing with colors in a portable way References: <33e19169-19b4-497a-b262-2bcf7b5637d5@r38g2000yqn.googlegroups.com> <19e16923-b200-498b-9ab2-f7d316b568a6@d32g2000yqh.googlegroups.com> Message-ID: In article <19e16923-b200-498b-9ab2-f7d316b568a6 at d32g2000yqh.googlegroups.com>, r wrote: >On Aug 2, 9:52=A0pm, a... at pythoncraft.com (Aahz) wrote: > >> Much as I hate to say, use a cross-platform GUI -- Tkinter comes with >> Python, > >Why is Tkinter such a whipping boy of the Python community? Can you explain what the connection is between my post and yours? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From piet at cs.uu.nl Wed Aug 5 16:14:04 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Aug 2009 22:14:04 +0200 Subject: http access produces 503 References: <3b5ab07c-7b0b-4d23-965b-192dc86cf6ff@a26g2000yqn.googlegroups.com> Message-ID: >>>>> Rog (R) wrote: >R> I am porting a simple code from Perl, the website asks for usr/pwd and >R> the server's side Perl script makes atemp ftp dir for file upload. >R> The original Perl script connects okay, does its job. The same URL >R> stuffed into FF3 performs the same way. >R> My Python script I am sweating out for past four days (noob!) gets >R> consistently "503", even with user agen set to: Mozilla/5.0 (Windows; >R> U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11. >R> Snippets of relevant code below. >R> Please, help me understand how this same code lets me log in into my >R> router usr/pwd running .asp, but this !@#$% perl script returns to me >R> w/503 c*ap? >R> Thank you. Which perl script? >R> Do I need to set any proxy? The server is on intranet and the FF3 is >R> set to proxy. The original Perl script did not use any proxy setting. >R>

>R> url = http://example.com/ftpsetup.pl?username=boofa&nodeid=42
>R> #########################################################
>R> # create a password manager
>R>     password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
>R> # Add the username and password.
>R> # If we knew the realm, we could use it instead of ``None``.
>R>     password_mgr.add_password(None, url, uid, pcode)
>R>     handler = urllib2.HTTPBasicAuthHandler(password_mgr)
>R>     class Mopener(URLopener): version = "Mozilla/5.0 (Windows; U;
>R> Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

>R>     opener = Mopener()

>R> # create "opener" (OpenerDirector instance)

>R>     opener = urllib2.build_opener(handler)
>R>     opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U;
>R> Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11')]

>R>     opener.version = "Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:
>R> 1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

>R>     print opener.version
>R> # timeout in seconds
>R>     timeout = 10
>R>     socket.setdefaulttimeout(timeout)

>R> # Install the opener all calls to urllib2.urlopen use our opener.
>R>     urllib2.install_opener(opener)

>R>     try:
>R>         response = opener.open(url)
>R>         # "http://www.useragent.org/" tested okay!!!
>R>         print"ok = 1"
>R>     except:
>R>         print "error 1"
>R> #####################################################################################

This code is a mess. The indentation is wrong so it can't be your real
code. Imports are missing. And there is a lot of garbage that doen't do
anything. E.g. The Mopener business is not used. install_opener is not
used.

Please make a minimal examples and check if that fails to. Like:

import urllib2
import socket

url = 'http://example.com/ftpsetup.pl?username=boofa&nodeid=42'
uid = ...
pcode = ...

# create a password manager
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of ``None``.
password_mgr.add_password(None, url, uid, pcode)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib2.build_opener(handler)

# timeout in seconds
timeout = 10
socket.setdefaulttimeout(timeout)

try:
    response = opener.open(url)
    print response.read()
    print"ok = 1"
except:
    print "error 1"



>R> output from the above:

>R> Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/
>R> 20071127 Firefox/2.0.0.11
>R> error 1
>R> Error code:  503
>R> ('Service Unavailable', 'The server cannot process the request due to
>R> a high load')

That suggests that there is a real problem in the server. Or that your
url causes some problems.

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From pfeldman at verizon.net  Wed Aug  5 16:16:31 2009
From: pfeldman at verizon.net (Dr. Phillip M. Feldman)
Date: Wed, 5 Aug 2009 13:16:31 -0700 (PDT)
Subject: trouble with complex numbers
In-Reply-To: 
References: <24821423.post@talk.nabble.com> 
Message-ID: <24835436.post@talk.nabble.com>


I am using Python 2.5, and most of the cmath functions are not yet available
in this version.  Thanks!

Phillip

P.S. In your code, that should be x+= 0J

P.P.S. I wish that the documentation indicated anything that is new.


Christian Heimes-2 wrote:
> 
> 
> 
> phase() has been added to Python 2.6 and 3.0. It's not available in 
> Python 2.5 and earlier. If you'd used cmath.phase() instead of the ugly 
> "from cmath import *" statement you'd have seen the correct error message.
> 
> You can write your own phase() function. This function is mostly correct 
> unless either the real and/or the imag part is NaN or INF.
> 
> from math import atan2
> 
> def phase(z):
>      z += 1j # convert int, long, float to complex
>      return atan2(z.imag, z.real)
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

-- 
View this message in context: http://www.nabble.com/trouble-with-complex-numbers-tp24821423p24835436.html
Sent from the Python - python-list mailing list archive at Nabble.com.



From gagsl-py2 at yahoo.com.ar  Wed Aug  5 16:18:02 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Wed, 05 Aug 2009 17:18:02 -0300
Subject: Python configuration question when python scripts are executed
	using Appweb as web server.
References: 
	
	
Message-ID: 

En Tue, 04 Aug 2009 10:15:24 -0300, IronyOfLife 
escribi?:
> On Aug 3, 8:42?pm, "Gabriel Genellina"  wrote:
>> En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife   
>> escribi?:
>>
>> > I have installed python 2.6.2 in windows xp professional machine. I
>> > have set the following environment variables -- PYTHONPATH. It points
>> > to following windows folders: python root folder, the lib folder and
>> > lib-tk folder.
>>
>> Why? Did you read it somewhere? Usually there is no need to set the ?
>> PYTHONPATH variable at all; remove it.
>
> Setting PYTHONPATH environment variables is mentioned in Python docs.

Could you provide a link please? Setting PYTHONPATH should not be
necesary, and in fact it's a very bad idea. Environment variables are
global, but Python modules may depend on the Python version, architecture,
install location... By example, you may install a 64 bits Python 3.1
version *and* a 32 bits Python 2.5 version and they both can coexist
peacefully - but an extension module compiled for the former cannot be
used in the later version. You must build a separate library for each
version, and install them in two separate directories. But since the
PYTHONPATH variable is shared by all installations, which directory should
contain?
It's best not to use PYTHONPATH at all and rely on other alternatives
(like .pth files, that are searched relative to the current Python
executable, so different versions use different configuration files)

> I solved the issue temporarily by copying the gnutls related dlls to
> the path searched by python.exe

Glad to see you could finally fix it!

-- 
Gabriel Genellina



From robert.kern at gmail.com  Wed Aug  5 16:27:51 2009
From: robert.kern at gmail.com (Robert Kern)
Date: Wed, 05 Aug 2009 15:27:51 -0500
Subject: trouble with complex numbers
In-Reply-To: <24835436.post@talk.nabble.com>
References: <24821423.post@talk.nabble.com> 
	<24835436.post@talk.nabble.com>
Message-ID: 

On 2009-08-05 15:16, Dr. Phillip M. Feldman wrote:
> I am using Python 2.5, and most of the cmath functions are not yet available
> in this version.  Thanks!
>
> Phillip
>
> P.S. In your code, that should be x+= 0J
>
> P.P.S. I wish that the documentation indicated anything that is new.

It does.

http://docs.python.org/library/cmath#cmath.phase

"New in version 2.6."

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From malc0de.encrypt at gmail.com  Wed Aug  5 16:28:30 2009
From: malc0de.encrypt at gmail.com (MalC0de)
Date: Wed, 5 Aug 2009 13:28:30 -0700 (PDT)
Subject: Error on Attaching to the process while debugging
Message-ID: <21dbc649-2f82-4e4c-9777-c8a58c25a9e0@r2g2000yqm.googlegroups.com>

Hello there, I'm writting a debugger,
the problem is there no good interpretation ...

here's the codes:

my_debugger.py :

#!/usr/bin/env python
from ctypes import *
from my_debugger_defines import *
kernel32 = windll.kernel32
class debugger():
    def __init__(self):
	  self.h_process = None
	  self.pid = None
	  self.debugger_active = False
          pass
    def load(self,path_to_exe):
        creation_flags = DEBUG_PROCESS
        startupinfo = STARTUPINFO()
        process_information = PROCESSINFORMATION()
        startupinfo.dwFlags = 0x1
        startupinfo.wShowWindow = 0x0
        startupinfo.cb = sizeof(startupinfo)
        if kernel32.CreateProcessA(path_to_exe,
                                    None,
                                    None,
                                    None,
                                    None,
                                    creation_flags,
                                    None,
                                    None,
                                    byref(startupinfo),
                                    byref(process_information)):
                  print "[*]we have sucessfully launched the process"
                  print "[*]PID %d" % process_information.dwProcessId
                  self.h_process = self.open_process
(process_information.dwProcessId)
        else:
            print"[*]Error 0x%08x." % kernel32.GetLastError()

def Open_process(self,pid):
    h_process = kernel32.OpenProcess(PROCESS_ALL_ACCESS,pid,False)
    return h_process
def attach(self,pid):
        self.h_process = self.open_process(pid)
        # We attempt to attach to the process
        # if this fails we exit the call
        if kernel32.DebugActiveProcess(pid):
            self.debugger_active = True
            self.pid             = int(pid)

        else:
            print "[*] Unable to attach to the process."

def run(self):
    while self.debugger_active == True:
        self.get_debug_event()
def get_debug_event(self):
    debug_event = DEBUG_EVENT()
    continue_status = DBG_CONTINUE
    if kernel32.WaitForDebugEvent(byref(debug_event),INFINITE):
        raw_input("Press a key to continue ...")
    self.debugger_active = False
    kernel32.ContinueDebugEvent
(debug_event.dwProdcessid,debug_event.dwThreadId,continue_status)
    def detach(self):
        if kernel32.DeugActiveProcessStop(self.pid):
            print "[*]Finished debugging. exiting ..."
            return True
        else:
            print "there was an error"
            return false

it's already have a method named : Attach ...

ok, the next source ,
my_test.py which lead python to launching the calc.exe for testing
purpose .

my_test.py :

#!/usr/bin/python
import my_debugger
debugger = my_debugger.debugger()
pid = raw_input("Enter the PID of the process to attach to :")
debugger.attach(int(pid))
debugger.detach()

and finally the essential definitions into my_debugger_defines.py

#!/usr/bin/env python
from ctypes import *
WORD = c_ushort
DWORD = c_ulong
LPBYTE = POINTER(c_ubyte)
LPTSTR = POINTER(c_char)
HANDLE = c_void_p
DEBUG_PROCESS = 0x00000001
CREATE_NEW_CONSOLE = 0x00000010
class STARTUPINFO(Structure):
    _fielnds_ = [
        ("cb",                                  DWORD),
        ("lpReserved",                          LPTSTR),
        ("lpDesktop",                           LPTSTR),
        ("lpTitle",                             LPTSTR),
        ("dwX",                                 DWORD),
        ("dwY",                                 DWORD),
        ("dwXSize",                             DWORD),
        ("dwYSize",                             DWORD),
        ("dwXCountChars",                       DWORD),
        ("dwFillAttribute",                     DWORD),
        ("dwFlags",                             DWORD),
        ("wShowWindow",                          WORD),
        ("cbReserved2",                          WORD),
        ("lpReserved2",                        LPBYTE),
        ("hStdInput",                          HANDLE),
        ("hStdOutput",                         HANDLE),
        ("hStdError",                          HANDLE),
    ]
class PROCESSINFORMATION(Structure):
    _fields_ = [
        ("hProcess",                           HANDLE),
        ("hThread",                            HANDLE),
        ("dwProcessId",                         DWORD),
        ("dwThreadId",                          DWORD),
    ]

when you type : python my_test.py it must run without any problem, but
seems errors occures while interpretation :

Enter the PID of the process to attach to :212
Traceback (most recent call last):
  File "C:\python25\2\my_Test.py", line 5, in 
    debugger.attach(int(pid))
AttributeError: debugger instance has no attribute 'attach'

it's nasty shit !
the my_debugger is already has a definition for attach() ,

please help me up,

thanks ...


From jnoller at gmail.com  Wed Aug  5 16:28:45 2009
From: jnoller at gmail.com (Jesse Noller)
Date: Wed, 5 Aug 2009 13:28:45 -0700 (PDT)
Subject: Is this a bug in multiprocessing or in my script?
References: 
	<2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> 
	<74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> 
	<6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> 
	
Message-ID: <4a238650-45b0-4478-884f-257fa2d3e9ba@o32g2000yqm.googlegroups.com>

On Aug 5, 3:40?pm, sturlamolden  wrote:
> On 5 Aug, 21:36, sturlamolden  wrote:
>
> >http://svn.python.org/view/python/branches/release26-maint/Lib/multip...
>
> >http://svn.python.org/view/python/branches/release31-maint/Lib/multip...
>
> http://svn.python.org/view/python/trunk/Lib/multiprocessing/forking.p...

Since the bug was never filed in the tracker (it was sent to my
personal mail box, and I dropped it - sorry), I've filed a new one:

http://bugs.python.org/issue6653

In the future please use the bug tracker to file and track bugs with,
so things are not as lossy.

jesse


From massi_srb at msn.com  Wed Aug  5 16:30:27 2009
From: massi_srb at msn.com (Massi)
Date: Wed, 5 Aug 2009 13:30:27 -0700 (PDT)
Subject: Web page data and urllib2.urlopen
Message-ID: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>

Hi everyone, I'm using the urllib2 library to get the html source code
of web pages. In general it works great, but I'm having to do with a
financial web site which does not provide the souce code I expect. As
a matter of fact if you try:

import urllib2
res = urllib2.urlopen("http://www.marketwatch.com/story/mondays-
biggest-gaining-and-declining-stocks-2009-07-27")
page = res.read()
print page

you will see that the printed code is very different from the one
given, for example, by mozilla. Since I have really little knowledge
in html I can't even understand if this is a python or html problem.
Can anyone give me some help?
Thanks in advance.


From sturlamolden at yahoo.no  Wed Aug  5 16:35:02 2009
From: sturlamolden at yahoo.no (sturlamolden)
Date: Wed, 5 Aug 2009 13:35:02 -0700 (PDT)
Subject: Is this a bug in multiprocessing or in my script?
References: 
	<2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> 
	<74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> 
	<6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> 
	
Message-ID: <8d19bdd2-ac70-4fd0-bea3-56ab520048de@z31g2000yqd.googlegroups.com>

On 5 Aug, 22:07, Piet van Oostrum  wrote:

> Calling os.exit in a child process may be dangerous. It can cause
> unflushed buffers to be flushed twice: once in the parent and once in
> the child.

I assume you mean sys.exit. If this is the case, multiprocessing needs
a mechanism to chose between os._exit and sys.exit for child
processes. Calling os._exit might also be dangerous because it could
prevent necessary clean-up code from executing  (e.g. in C
extensions). I had a case where shared memory on Linux (System V IPC)
leaked due to os._exit. The deallocator for my extension type never
got to execute in child processes. The deallocator was needed to
release the shared segment when its reference count dropped to 0.
Changing to sys.exit solved the problem. On Windows there was no leak,
because the kernel did the reference counting.




From pavlovevidence at gmail.com  Wed Aug  5 16:35:23 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Wed, 5 Aug 2009 13:35:23 -0700 (PDT)
Subject: How to combine regexps?
References: 
Message-ID: 

On Aug 5, 1:09?pm, kj  wrote:
> One of the nice things one can do with Perl's regexp's is illustrated
> in the following example:
>
> my $gly = qr/gg[ucag]/i
> my $ala = qr/gc[ucag]/i;
> my $val = qr/gu[ucag]/i;
> my $leu = qr/uu[ag]|cu[ucag]/i;
> my $ile = qr/au[uca]/i;
>
> my $aliphatic = qr/$gly|$ala|$val|$leu|$ile/;
>
> In other words, one can build regular expressions by re-combining
> other regular expressions.
>
> Is there a way to do this with Python's regexps?

Your example is just string manipulation.

You're not combining regexps here, you are combining strings which you
(evidently) will soon use to create a regexp.

Yes, you can do that in Python as well, in exactly the same way, using
Python's string manipulation capabilities.


Carl Banks


From no.email at please.post  Wed Aug  5 16:36:07 2009
From: no.email at please.post (kj)
Date: Wed, 5 Aug 2009 20:36:07 +0000 (UTC)
Subject: How to combine regexps?
References: 
Message-ID: 

In  kj  writes:



>One of the nice things one can do with Perl's regexp's is illustrated
>in the following example:

>my $gly = qr/gg[ucag]/i
>my $ala = qr/gc[ucag]/i;
>my $val = qr/gu[ucag]/i;
>my $leu = qr/uu[ag]|cu[ucag]/i;
>my $ile = qr/au[uca]/i;

>my $aliphatic = qr/$gly|$ala|$val|$leu|$ile/;


>In other words, one can build regular expressions by re-combining
>other regular expressions.

>Is there a way to do this with Python's regexps?


OK, answering my own question here, it looks like the only way to
do this is to leave the "component" expressions as regular strings,
and combine those, before compiling them into regexps.

Easy enough.

kynn


From joncle at googlemail.com  Wed Aug  5 16:39:33 2009
From: joncle at googlemail.com (Jon Clements)
Date: Wed, 5 Aug 2009 13:39:33 -0700 (PDT)
Subject: Parsing Binary Structures; Is there a better way / What is your 
	way?
References: 
	<7x3a86gmfe.fsf@ruckus.brouhaha.com> 
	
	<7xr5vqw0v9.fsf@ruckus.brouhaha.com> 
	
Message-ID: <1211ccf7-1147-42de-ab62-3e5b33b09011@k19g2000yqn.googlegroups.com>

On 5 Aug, 20:41, "Martin P. Hellwig" 
wrote:
> Paul Rubin wrote:
> > "Martin P. Hellwig"  writes:
> >> Is there an advantage using shifts and masks over my kitchen type solution?
>
> > Weren't you complaining about the 8-to-1 expansion from turning each bit
> > to an ascii char?
>
> Yes you are (of course) right, my 'dream' solution would be something
> that accepts slice indeces on bit level. Your reasoning did reveal some
> flaws in my approach though ;-)
>
> --
> MPHhttp://blog.dcuktec.com
> 'If consumed, best digested with added seasoning to own preference.'

Ahh huh -- found it...

ID: DLT119
Desc: datasyzygy misc. development, production and accounts.
Date: 2008-12-09
File: pybits.py
"""
Implements a python level interface to reading bit fields with an
associated type. Fields are accessed via __getitem__ and must be a
valid python name. eg:

class MyStructure:
    a = BitField(4, int)
    b = BitField(6, int)
    c = BitField(2, int)
    d = BitField(36, str)
"""

Ummm, seems I left the rest pretty vague, but I'm guessing that's what
you're after, and I'm fairly curious to see what I wrote... mind you,
not too hard to write again now that's jogged my memory! (although
after a couple at the pub, not going to do it tonight!)

Cheers,

Jon.



From mensanator at aol.com  Wed Aug  5 16:40:28 2009
From: mensanator at aol.com (Mensanator)
Date: Wed, 5 Aug 2009 13:40:28 -0700 (PDT)
Subject: Turtle Graphics are incompatible with gmpy
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	
	
Message-ID: <87b655e8-937b-4f62-ad1e-5165d547a7bd@v20g2000yqm.googlegroups.com>

On Aug 5, 3:08?pm, Ethan Furman  wrote:
> Mensanator wrote:
>
> 
>
>
>
>
>
>
>
> > What does this mean?
>
> >>>>import turtle
> >>>>tooter = turtle.Turtle()
> >>>>*tooter*.tracer
>
> > Traceback (most recent call last):
> > ? File "", line 1, in 
> > ? ? tooter.tracer
> > AttributeError: 'Turtle' object has no attribute 'tracer'
>
> >>>>tooter.hideturtle()
> >>>>tooter.speed('fast')
> >>>>turtle.update()
> >>>>*turtle*.tracer
>
> > 
>
> > How did the tracer attribute appear out of thin air?
>
> Perhaps I am missing something (wouldn't surprise me!) but it seems that
> the first time you are looking for a tracer on 'tooter', and the second
> time you are looking for a tracer on 'turtle'. ?

Duh. I could have looked at that from now til the sun don't shine and
not seen it. And I even retyped it, no cut/paste.

> After *turtle.tracer*
> succeeds, does *tooter.tracer*?

No, that was my mistake. Too late now as the record is gone, but I
could have sworn I had the math exception first. That's what made
me go realize the tracing wasn't off which led me to add .screen.

Sounds like I should have gotten the attribute error first.

Maybe I did and am mis-remembering it. Usually, I don't start keeping
notes at first because I'm not expecting failure.

>
> ~Ethan~



From sturlamolden at yahoo.no  Wed Aug  5 16:41:53 2009
From: sturlamolden at yahoo.no (sturlamolden)
Date: Wed, 5 Aug 2009 13:41:53 -0700 (PDT)
Subject: Is this a bug in multiprocessing or in my script?
References: 
	<2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> 
	<74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> 
	<6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> 
	 
	<4a238650-45b0-4478-884f-257fa2d3e9ba@o32g2000yqm.googlegroups.com>
Message-ID: <54cdf823-7b2c-4ff8-b1f2-b8091a7daeb8@d32g2000yqh.googlegroups.com>

On 5 Aug, 22:28, Jesse Noller  wrote:

> http://bugs.python.org/issue6653
>
> In the future please use the bug tracker to file and track bugs with,
> so things are not as lossy.

Ok, sorry :)

Also see Piet's comment here. He has a valid case against sys.exit in
some cases. Thus it appears that both ways of shutting down child
processes might be dangerous: If we don't want buffers to flush we
have to use os._exit. If we want clean-up code to execute we have to
use sys.exit. If we want both we are screwed. :(






From netgraviton at gmail.com  Wed Aug  5 16:42:40 2009
From: netgraviton at gmail.com (WordStream)
Date: Wed, 5 Aug 2009 13:42:40 -0700 (PDT)
Subject: [ATTN] Sr. Software Development Engineer
Message-ID: 

Postion Title - Sr. Software Development Engineer

Job Responsibilities
The Sr. Software Development Engineer will be responsible for the
design, development and implementation of the award-winning WordStream
suite of products.

Development is presently done primarily using Python on the server and
Adobe Flex/HTML/AJAX as a Rich Internet Application (RIA) frontend.
However, like everything in the computing industry, we're constantly
evolving how we work.  We're always on the lookout for newer and
better technologies, and as a result, the technologies we use tomorrow
are likely to be different.

This is a full-time telecommute position.  The Sr. Software
Development Engineer can choose to work in our Boston office, or they
can choose to work from at home or from any location in the world.

Qualifications
The Sr. Software Development Engineer will be an individual who has
top-notch coding skills, and can demonstrate an aptitude to learn new
technologies.

Prior experience with any specific technologies (e.g., Python or Adobe
Flex) is not a requirement; we're looking for people with a history of
leveraging any technology to create masterpieces.

Prior experience working on web analytics applications, search
engines, content management systems or other Web publishing systems is
a plus.

Please note, only candidates with a bachelor's degree in computer
science or engineering, or, a very substantial amount of related
technical coursework and work experience in a related field will be
considered.

Related Skills
Python, Adobe Flex, Structured Query Language (SQL), Object-Oriented
Programming, SQLite, Open-Source software development, Git, Object-
Relational Mapping (ORM), Postgres SQL, AJAX, HTML, Search Engine
Optimization (SEO) or Search Engine Marketing (SEM)

Compensation
?	Full-time salaried position, with competitive salary.
?	Position includes equity participation and comprehensive benefits
(healthcare, vision and dental).
?	Flexibility to work from any location, worldwide.

About WordStream
Founded in August 2008 by experienced search marketers and software
experts, WordStream has developed the first database-driven Keyword
Management Software solution for pay-per-click advertisers and
agencies. With the decline in print and traditional media, companies
of every size are flocking to the Internet, search engine marketing
and, specifically, Google AdWords to advertise their products and
services. But mastering even the basics of search engine marketing
isn?t easy ? until now! From keyword discovery to ad group creation,
WordStream helps pay-per-click advertisers build the solid keyword
foundation required for PPC success. WordStream is backed by Sigma +
Partners. For more information please visit: http://www.wordstream.com

How To Apply
To apply for the Sr. Software Development Engineer position, send a
resume to jobs at WordStream dot com.


From rogerb at rogerbinns.com  Wed Aug  5 16:45:09 2009
From: rogerb at rogerbinns.com (Roger Binns)
Date: Wed, 05 Aug 2009 13:45:09 -0700
Subject: Do anyone here use Python *embedded* in a database?
In-Reply-To: 
References: 
Message-ID: 

Jonathan Fine wrote:
> anyone here ever used the Python *embedded* in a database server.

There is also the case of using SQLite where it shares the same process as
your Python code (and nothing else) and is a standard part of the Python
library.

You can add your own functions and collations and if using APSW then you can
also go way further than a regular database and add virtual tables and
virtual storage.

SQLite generally outperforms database servers since there is no cross
process or network communication until you get to larger workloads and/or
concurrent database access which database servers are more tuned for.

Roger



From jnoller at gmail.com  Wed Aug  5 16:50:03 2009
From: jnoller at gmail.com (Jesse Noller)
Date: Wed, 5 Aug 2009 13:50:03 -0700 (PDT)
Subject: Is this a bug in multiprocessing or in my script?
References: 
	<2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> 
	<74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> 
	<6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> 
	 
	<4a238650-45b0-4478-884f-257fa2d3e9ba@o32g2000yqm.googlegroups.com> 
	<54cdf823-7b2c-4ff8-b1f2-b8091a7daeb8@d32g2000yqh.googlegroups.com>
Message-ID: 

On Aug 5, 4:41?pm, sturlamolden  wrote:
> On 5 Aug, 22:28, Jesse Noller  wrote:
>
> >http://bugs.python.org/issue6653
>
> > In the future please use the bug tracker to file and track bugs with,
> > so things are not as lossy.
>
> Ok, sorry :)
>
> Also see Piet's comment here. He has a valid case against sys.exit in
> some cases. Thus it appears that both ways of shutting down child
> processes might be dangerous: If we don't want buffers to flush we
> have to use os._exit. If we want clean-up code to execute we have to
> use sys.exit. If we want both we are screwed. :(

Comments around this bug should go in the bug report - again, so we
don't loose them. I do not personally subscribe to this group , so
it's very easy to miss things.

jesse


From mensanator at aol.com  Wed Aug  5 17:03:05 2009
From: mensanator at aol.com (Mensanator)
Date: Wed, 5 Aug 2009 14:03:05 -0700 (PDT)
Subject: Turtle Graphics are incompatible with gmpy
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> 
	 
	<4A79C7E2.3000406@aon.at>
Message-ID: 

On Aug 5, 12:56?pm, Gregor Lingl  wrote:
> Mensanator schrieb:
>
>
>
>
>
> >> It didn't form 2.5 to 2.6 (at least not intentionally). But with the
> >> indroduction of the TurtleScreen class and the Screen class/object
> >> (singleton) a few of the turtle methods were also implemented as screen
> >> methods and as turtle methods declared deprecated (see docs of Python
> >> 2.6). These deprecated turtle methods do not occur as turtle methods any
> >> more in Python 3.x.
>
> > More info.
>
> > Yes, there is no tracer attribute...when the object is created.
>
> > But watch this (Python 3.1):
>
> >>>> import turtle
> >>>> tooter = turtle.Turtle()
> >>>> tooter.tracer
> > Traceback (most recent call last):
> > ? File "", line 1, in 
> > ? ? tooter.tracer
> > AttributeError: 'Turtle' object has no attribute 'tracer'
> >>>> tooter.hideturtle()
> >>>> tooter.speed('fast')
> >>>> turtle.update()
> >>>> turtle.tracer
> > 
>
> > Now, after setting hide, speed, update, a tracer exists.
>
> No,

Yeah, I mistyped my example, sorry about that. I thought sure
it was the math error that lead me to the tracer issue, but that
might have been a mistake.

>
> Nevertheless I'd like to see a working Python 2.5 version of your script.

I've commented out the parts that v2.5 doesn't have.
So the pen is still down and I have no .dot function,
but the gotos appear to still work as evidenced by
the large black square it now draws.

With tracing on in 2.5, I see the turtle move around
the square. With tracing off, I still the the square
outined, but without a turtle and much faster.

With 3.1, the screen is completely blank for 3-4 seconds and appears
all at once when it's done.

import gmpy

##   (even) hi----|
##                |
##                lo (odd)
## or
##
##   (even) lo
##           |
##           |
##           ----hi (odd)
##
##
##
##

import turtle

tooter = turtle.Turtle()

#tooter.hideturtle()
tooter.speed('fast')
#turtle.update()
tooter.tracer(False)
#tooter.penup()
tooter.color('black')

s = ['1','0']
while len(s[0])<10000:
    s = [''.join(s), s[0]]


origin = [0,0]
if s[0] == '0':
  tooter.goto(origin)
  #tooter.dot(1)
if s[1] == '0':
  tooter.goto([1,0])
  #tooter.dot(1)

print len(s[0])

for i,j in enumerate(s[0]):
  the_coord=[]
  cur_root = gmpy.sqrt(i)
  lo__root = gmpy.sqrt(i)**2
  hi__root = (gmpy.sqrt(i)+1)**2

  if hi__root%2==0:
    side = 'northeast'
  else:
    side = 'southwest'

  elbow = (hi__root - lo__root)/2 + lo__root + 1

  if i>= elbow:
    side_len = i - elbow
    elbow_plus = True
  else:
    side_len = elbow - i
    elbow_plus = False

  if side == 'northeast':
    elbow_offset = [(gmpy.sqrt(elbow)-1)/2 +1,-((gmpy.sqrt(elbow)-1)/2
+1)]
  else:
    elbow_offset = [-((gmpy.sqrt(elbow)-1)/2 +1),((gmpy.sqrt(elbow)-1)/
2 +1)]

  elbow_coord = [origin[0]+elbow_offset[0],origin[1]+elbow_offset[1]]

  if i != hi__root and i != lo__root:
    if i == elbow:
      the_coord = elbow_coord
    else:
      if elbow_plus:
        if side == 'northeast':
          the_coord = [elbow_coord[0]-side_len,elbow_coord[1]]
        else:
          the_coord = [elbow_coord[0]+side_len,elbow_coord[1]]
      else:
        if side == 'northeast':
          the_coord = [elbow_coord[0],elbow_coord[1]+side_len]
        else:
          the_coord = [elbow_coord[0],elbow_coord[1]-side_len]
  else:
    if i % 2 == 0:  # even square
      n = gmpy.sqrt(i)/2 - 1
      the_coord = [-n, -n-1]
    else:
      n = (gmpy.sqrt(i)-1)/2 - 1
      the_coord = [1+n, 1+n]
  if j == '0':
    tooter.goto(the_coord)
    #tooter.dot(2)
print 'done'

#turtle.update()
turtle.done()
print 'done'


>
> Regards,
> Gregor


From deets at nospam.web.de  Wed Aug  5 17:19:20 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Wed, 05 Aug 2009 23:19:20 +0200
Subject: access string data from within cython
In-Reply-To: 
References: <7dtt46F2e5osvU1@mid.uni-berlin.de>
	
Message-ID: <7dubaoF2e96rfU2@mid.uni-berlin.de>

Philip Semanchuk schrieb:
> 
> On Aug 5, 2009, at 1:16 PM, Diez B. Roggisch wrote:
> 
>> Hi,
>>
>> I'm trying to wrap a C-API which has a call that takes a void* and a 
>> size_t
>> as arguments.
>>
>> void foo(void *data, size_t length)
>>
>>
>> The wrapper is supposed to be called with a python (byte)string instance,
>> which might contain more than one '\0'-character.
>>
>> So how do I access the raw data of a string? I tried looking into the
>> buffer-protocol, but to be honest - that's beyond me, I don't see where
>> that is actually giving me access to the real data.
> 
> Hi Diez,
> Would ctypes.create_string_buffer() work for you?

I'm not using ctypes because I want a distributable egg with static 
linkage. ctypes can't help there afaik.

Diez


From contact at xavierho.com  Wed Aug  5 17:22:44 2009
From: contact at xavierho.com (Xavier Ho)
Date: Thu, 6 Aug 2009 07:22:44 +1000
Subject: Subclassing Python's dict
In-Reply-To: 
References: 
	<2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com>
	
Message-ID: <2d56febf0908051422h2cd0e58p1afce376895d5d1e@mail.gmail.com>

On Thu, Aug 6, 2009 at 5:23 AM, Joshua Kugler wrote:

> Are you referring to Python 3.0?  Python 2.6 does not have
> collections.UserDict
>
> j
>

Yes, I was.... sometimes it's hard to keep track what's not in 2.6 and in
3.1 for me, sorry. And thanks.

The ABC MutableMapping is still valid, though. I hope he gets it sorted out.


With a morning yawn,
Xavier
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From deets at nospam.web.de  Wed Aug  5 17:22:56 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Wed, 05 Aug 2009 23:22:56 +0200
Subject: access string data from within cython
In-Reply-To: <88384285-0147-470d-943f-14cfaa79219f@t13g2000yqt.googlegroups.com>
References: <7dtt46F2e5osvU1@mid.uni-berlin.de>
	<88384285-0147-470d-943f-14cfaa79219f@t13g2000yqt.googlegroups.com>
Message-ID: <7dubhgF2e96rfU3@mid.uni-berlin.de>

sturlamolden schrieb:
> On 5 Aug, 19:16, "Diez B. Roggisch"  wrote:
> 
>> void foo(void *data, size_t length)
>>
>> The wrapper is supposed to be called with a python (byte)string instance,
>> which might contain more than one '\0'-character.
>>
>> So how do I access the raw data of a string?
> 
> cdef extern void foo(void *data, int length)
> cdef char *data
> cdef int length
> bytestring = ... #whatever
> 
> rawdata =  bytestring
> length =  len(bytestring)

And that gives me the *full* bytestring, not only until the first zero? 
I can't try that right now (not at work anymore), but if it's that easy, 
that would be great.

Diez


From philip at semanchuk.com  Wed Aug  5 17:30:22 2009
From: philip at semanchuk.com (Philip Semanchuk)
Date: Wed, 5 Aug 2009 17:30:22 -0400
Subject: access string data from within cython
In-Reply-To: <7dubaoF2e96rfU2@mid.uni-berlin.de>
References: <7dtt46F2e5osvU1@mid.uni-berlin.de>
	
	<7dubaoF2e96rfU2@mid.uni-berlin.de>
Message-ID: <84411DCB-CD09-4EE1-B50E-51D005748BE1@semanchuk.com>


On Aug 5, 2009, at 5:19 PM, Diez B. Roggisch wrote:

> Philip Semanchuk schrieb:
>> On Aug 5, 2009, at 1:16 PM, Diez B. Roggisch wrote:
>>> Hi,
>>>
>>> I'm trying to wrap a C-API which has a call that takes a void* and  
>>> a size_t
>>> as arguments.
>>>
>>> void foo(void *data, size_t length)
>>>
>>>
>>> The wrapper is supposed to be called with a python (byte)string  
>>> instance,
>>> which might contain more than one '\0'-character.
>>>
>>> So how do I access the raw data of a string? I tried looking into  
>>> the
>>> buffer-protocol, but to be honest - that's beyond me, I don't see  
>>> where
>>> that is actually giving me access to the real data.
>> Hi Diez,
>> Would ctypes.create_string_buffer() work for you?
>
> I'm not using ctypes because I want a distributable egg with static  
> linkage. ctypes can't help there afaik.

Sorry, I read cython as CPython.




From xahlee at gmail.com  Wed Aug  5 17:44:49 2009
From: xahlee at gmail.com (Xah Lee)
Date: Wed, 5 Aug 2009 14:44:49 -0700 (PDT)
Subject: Google sitemap generator in python gone?
Message-ID: <5982ba4d-668c-460f-a666-5d7cbe697883@x25g2000prf.googlegroups.com>

google used to have a sitemap generator written in python, at:
 https://www.google.com/webmasters/tools/docs/en/sitemap-generator.html

but the url is gone. It seems the current version is moved here:
http://code.google.com/p/googlesitemapgenerator/
and is written in JavaScript.

is the old python version still available? or is there some official
doc about this change?

thanks.

  Xah
? http://xahlee.org/

?


From sturlamolden at yahoo.no  Wed Aug  5 17:51:12 2009
From: sturlamolden at yahoo.no (sturlamolden)
Date: Wed, 5 Aug 2009 14:51:12 -0700 (PDT)
Subject: access string data from within cython
References: <7dtt46F2e5osvU1@mid.uni-berlin.de>
	<88384285-0147-470d-943f-14cfaa79219f@t13g2000yqt.googlegroups.com>
	<7dubhgF2e96rfU3@mid.uni-berlin.de>
Message-ID: <71adfa33-faee-48d7-adb0-1403d8af4fd5@c14g2000yqm.googlegroups.com>

On 5 Aug, 23:22, "Diez B. Roggisch"  wrote:

> And that gives me the *full* bytestring, not only until the first zero?
> I can't try that right now (not at work anymore), but if it's that easy,
> that would be great.

It should, and if it does not it is a bug in Cython. The len()
function should work similarly in Python and Cython: It should just
call the object's __len__ method. Cython has no idea that your Python
object bytestring is a byte string, nor does Cython care.

>>> bs = '\x00'*10 # bytes string with 10 zeros
>>> len(bs)
10
>>> bs.__len__()
10



From joncle at googlemail.com  Wed Aug  5 17:55:02 2009
From: joncle at googlemail.com (Jon Clements)
Date: Wed, 5 Aug 2009 14:55:02 -0700 (PDT)
Subject: Google sitemap generator in python gone?
References: <5982ba4d-668c-460f-a666-5d7cbe697883@x25g2000prf.googlegroups.com>
Message-ID: <631e148d-9e26-4779-b76a-bd405f4525c8@c34g2000yqi.googlegroups.com>

On 5 Aug, 22:44, Xah Lee  wrote:
> google used to have a sitemap generator written in python, at:
> ?https://www.google.com/webmasters/tools/docs/en/sitemap-generator.html
>
> but the url is gone. It seems the current version is moved here:http://code.google.com/p/googlesitemapgenerator/
> and is written in JavaScript.
>
> is the old python version still available? or is there some official
> doc about this change?
>
> thanks.
>
> ? Xah
> ?http://xahlee.org/
>
> ?

How about asking Google, and not this list?

It's always good to see a funny troll on this list though...

Now please piddle off...


From martin.hellwig at dcuktec.org  Wed Aug  5 17:59:18 2009
From: martin.hellwig at dcuktec.org (Martin P. Hellwig)
Date: Wed, 05 Aug 2009 22:59:18 +0100
Subject: Google sitemap generator in python gone?
In-Reply-To: <631e148d-9e26-4779-b76a-bd405f4525c8@c34g2000yqi.googlegroups.com>
References: <5982ba4d-668c-460f-a666-5d7cbe697883@x25g2000prf.googlegroups.com>
	<631e148d-9e26-4779-b76a-bd405f4525c8@c34g2000yqi.googlegroups.com>
Message-ID: 

Jon Clements wrote:

> Now please piddle off...

I am guessing west-midlands? :-)

-- 
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'


From python at mrabarnett.plus.com  Wed Aug  5 18:03:11 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Wed, 05 Aug 2009 23:03:11 +0100
Subject: How to combine regexps?
In-Reply-To: 
References:  
Message-ID: <4A7A019F.3070205@mrabarnett.plus.com>

kj wrote:
> In  kj  writes:
> 
> 
> 
>> One of the nice things one can do with Perl's regexp's is illustrated
>> in the following example:
> 
>> my $gly = qr/gg[ucag]/i
>> my $ala = qr/gc[ucag]/i;
>> my $val = qr/gu[ucag]/i;
>> my $leu = qr/uu[ag]|cu[ucag]/i;
>> my $ile = qr/au[uca]/i;
> 
>> my $aliphatic = qr/$gly|$ala|$val|$leu|$ile/;
> 
> 
>> In other words, one can build regular expressions by re-combining
>> other regular expressions.
> 
>> Is there a way to do this with Python's regexps?
> 
> 
> OK, answering my own question here, it looks like the only way to
> do this is to leave the "component" expressions as regular strings,
> and combine those, before compiling them into regexps.
> 
> Easy enough.
> 
A compiled regular expression has 'pattern' and 'flags' attributes, so
you can get the original parameters which were used to create it if a
function is given just the compiled regular expression. Might be useful.


From mensanator at aol.com  Wed Aug  5 18:31:17 2009
From: mensanator at aol.com (Mensanator)
Date: Wed, 5 Aug 2009 15:31:17 -0700 (PDT)
Subject: Turtle Graphics are incompatible with gmpy
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> 
	 
	<4A79C7E2.3000406@aon.at>
	
Message-ID: 

I fixed this to produce the actual image I'm looking
for instead of that stupid black square. All I did was
use up() & dowm() in place of penup(), pendown() and
replace dot(2) with forward(1).

I'll be posting a followup report later.


import gmpy

##   (even) hi----|
##                |
##                lo (odd)
## or
##
##   (even) lo
##           |
##           |
##           ----hi (odd)
##
##
##
##

import turtle

tooter = turtle.Turtle()

#tooter.hideturtle()
tooter.speed('fast')
#turtle.update()
tooter.tracer(False)
#tooter.penup()
tooter.up()
tooter.color('black')

s = ['1','0']
while len(s[0])<10000:
    s = [''.join(s), s[0]]


origin = [0,0]
if s[0] == '0':
  tooter.goto(origin)
  #tooter.dot(1)
  tooter.down()
  tooter.forward(1)
  tooter.up()
if s[1] == '0':
  tooter.goto([1,0])
  #tooter.dot(1)
  tooter.down()
  tooter.forward(1)
  tooter.up()

print len(s[0])

for i,j in enumerate(s[0]):
  the_coord=[]
  cur_root = gmpy.sqrt(i)
  lo__root = gmpy.sqrt(i)**2
  hi__root = (gmpy.sqrt(i)+1)**2

  if hi__root%2==0:
    side = 'northeast'
  else:
    side = 'southwest'

  elbow = (hi__root - lo__root)/2 + lo__root + 1

  if i>= elbow:
    side_len = i - elbow
    elbow_plus = True
  else:
    side_len = elbow - i
    elbow_plus = False

  if side == 'northeast':
    elbow_offset = [(gmpy.sqrt(elbow)-1)/2 +1,-((gmpy.sqrt(elbow)-1)/2
+1)]
  else:
    elbow_offset = [-((gmpy.sqrt(elbow)-1)/2 +1),((gmpy.sqrt(elbow)-1)/
2 +1)]

  elbow_coord = [origin[0]+elbow_offset[0],origin[1]+elbow_offset[1]]

  if i != hi__root and i != lo__root:
    if i == elbow:
      the_coord = elbow_coord
    else:
      if elbow_plus:
        if side == 'northeast':
          the_coord = [elbow_coord[0]-side_len,elbow_coord[1]]
        else:
          the_coord = [elbow_coord[0]+side_len,elbow_coord[1]]
      else:
        if side == 'northeast':
          the_coord = [elbow_coord[0],elbow_coord[1]+side_len]
        else:
          the_coord = [elbow_coord[0],elbow_coord[1]-side_len]
  else:
    if i % 2 == 0:  # even square
      n = gmpy.sqrt(i)/2 - 1
      the_coord = [-n, -n-1]
    else:
      n = (gmpy.sqrt(i)-1)/2 - 1
      the_coord = [1+n, 1+n]
  if j == '0':
    tooter.goto(the_coord)
    #tooter.dot(2)
    tooter.down()
    tooter.forward(1)
    tooter.up()
print 'done'

#turtle.update()
turtle.done()
print 'done'


From ryan at rfk.id.au  Wed Aug  5 18:33:14 2009
From: ryan at rfk.id.au (Ryan Kelly)
Date: Thu, 06 Aug 2009 08:33:14 +1000
Subject: ANN:  extprot 0.1.1
Message-ID: <1249511594.4180.9.camel@durian>


Hi All,


Sorry if you get this twice, it seems to have gotten lost on its way
through python-announce.

I'm pleased to announce the first release of the "extprot" python
module.  Extprot implements a compact, efficient, extensible and
language-neutral object serialisation protocol.

License:      MIT
Downloads:    http://pypi.python.org/pypi/extprot/
Source code:  http://github.com/rfk/extprot/tree/master


You can think of extprot as something akin to Google's protocol buffers,
with a few extra bytes of serialisation overhead and a Python binding
that doesn't have nearly as many rough edges.  For example:

      * It's a stand-alone python module, packaged and distributed in
        the standard fashion.
      * It's friendly to dynamic package management tools like pip.
      * It works exclusively with standard Python objects. Declared a
        list field? It's a native list object.
      * You don't need to compile your protocol definitions.


More on the extprot format itself is here:

   http://eigenclass.org/R2/writings/extprot-extensible-protocols-intro

More on my motivations for this package here, if you're interested:

    http://www.rfk.id.au/blog/entry/new-python-module-extprot


Enjoy!


    Ryan

-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
ryan at rfk.id.au        |  http://www.rfk.id.au/ramblings/gpg/ for details

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 204 bytes
Desc: This is a digitally signed message part
URL: 

From steve at REMOVE-THIS-cybersource.com.au  Wed Aug  5 19:04:55 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 05 Aug 2009 23:04:55 GMT
Subject: trouble with complex numbers
References: <24821423.post@talk.nabble.com> 
	<24835436.post@talk.nabble.com>
	
Message-ID: <028a00b4$0$5185$c3e8da3@news.astraweb.com>

On Wed, 05 Aug 2009 15:27:51 -0500, Robert Kern wrote:

> On 2009-08-05 15:16, Dr. Phillip M. Feldman wrote:
>> I am using Python 2.5, and most of the cmath functions are not yet
>> available in this version.  Thanks!
>>
>> Phillip
>>
>> P.S. In your code, that should be x+= 0J
>>
>> P.P.S. I wish that the documentation indicated anything that is new.
> 
> It does.
> 
> http://docs.python.org/library/cmath#cmath.phase
> 
> "New in version 2.6."


Furthermore, every release comes with a What's New document:

http://docs.python.org/whatsnew/index.html




-- 
Steven


From lanyjie at yahoo.com  Wed Aug  5 19:05:41 2009
From: lanyjie at yahoo.com (Yingjie Lan)
Date: Wed, 5 Aug 2009 16:05:41 -0700 (PDT)
Subject: using expy to extend python
Message-ID: <871540.68601.qm@web54204.mail.re2.yahoo.com>


Hi,

The expy project provides an express way to extend Python. After some careful considerations, I came up with some reasons for expy (this is not an exhaustive list):

(I). WYSIWYG. The expy project enables you to write your module in Python the way your extension would be (WYSIWYG), and meanwhile write your implementation in pure C. You specify your modules, functions, methods, classes, and even their documentations the usual way of writing your Python correspondences. Then your provide your implementation to the functions/methods by returning a multi-line string. By such an arrangement, everything falls in its right place, and your extension code becomes easy to read and maintain. Also, the generated code is very human-friendly.

(II). You only provide minimal information to indicate your intension of how your module/class would function in Python. So your extension is largely independent from the Python extension API. As your interaction with the Python extension API is reduced to minimal (you only care about the functionality and logic), it is then possible that your module written in expy can be independent of changes in the extension API.

(III). The building and setup of your project can be automatically done with the distutil tool. In the tutorial, there are ample examples on how easily this is achieved.

(IV). Very light weight. The expy tool is surprisingly light weight dispite of its powerful ability, as it is written in pure Python. There is no parser or compiler for code generation, but rather the powerful reflexion mechanism of Python is exploited in a clever way to generate human-friendly codes. Currently, generating code in C is supported, however, the implementation is well modularized and code generation in other languages such as Java and C++ should be easy.

While there are already a couple of other projects trying to simply this task with different strategies, such as Cython, Pyrex and modulator, this project is unique and charming in its own way. All you need is the WYSIWYG Python file for your module extension, then expy takes care of everything else. What follows in this documentation is on how to extend Python in C using expy-cxpy: the module expy helps define your module, while module cxpy helps generate C codes for your defined module.

For more information about expy, please visit its homepage at: http://expy.sf.net/

Cheers,

Yingjie



      


From Samnsparky at gmail.com  Wed Aug  5 19:12:09 2009
From: Samnsparky at gmail.com (Sparky)
Date: Wed, 5 Aug 2009 16:12:09 -0700 (PDT)
Subject: Two Dimensional Array + ctypes
Message-ID: <79d2b3e3-b049-4d70-a56b-6e7f3ea2fa86@e27g2000yqm.googlegroups.com>

Hello! I am trying to call this method:

long _stdcall AIBurst(long *idnum,
			 long demo,
			 long stateIOin,
			 long updateIO,
			 long ledOn,
			 long numChannels,
			 long *channels,
			 long *gains,
			 float *scanRate,
			 long disableCal,
			 long triggerIO,
			 long triggerState,
			 long numScans,
			 long timeout,
			 float (*voltages)[4],
			 long *stateIOout,
			 long *overVoltage,
			 long transferMode);

I am having some problems with that  float (*voltages)[4]. Here is
what I tried:

def aiBurst(self, channels, scanRate, numScans, idNum=None, demo=0,
stateIOin=[0, 0, 0, 0], updateIO=0, ledOn=0, gains=[0, 0, 0, 0],
disableCal=0, triggerIO=0, triggerState=0, timeout=1, transferMode=0):

        if idNum is None:
            idNum = self.id

        idNum = ctypes.c_long(idNum)

        numChannels = len(channels)

        stateIOArray = listToCArray(stateIOin, ctypes.c_long)
        channelsArray = listToCArray(channels, ctypes.c_long)
        gainsArray = listToCArray(gains, ctypes.c_long)
        scanRate = ctypes.c_float(scanRate)
        pointerArray = (ctypes.c_void_p * 4)
        voltages = pointerArray(ctypes.cast(ctypes.pointer
((ctypes.c_long * 4096)()), ctypes.c_void_p), ctypes.cast
(ctypes.pointer((ctypes.c_long * 4096)()), ctypes.c_void_p),
ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)()),
ctypes.c_void_p), ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)
()), ctypes.c_void_p))
        stateIOout = (ctypes.c_long * 4096)()
        overVoltage = ctypes.c_long(999)

        staticLib.AIBurst(ctypes.byref(idNum), demo, stateIOArray,
updateIO, ledOn, numChannels, ctypes.byref(channelsArray), ctypes.byref
(gainsArray), ctypes.byref(scanRate), disableCal, triggerIO,
triggerState, numScans, timeout, ctypes.byref(voltages), ctypes.byref
(stateIOout), ctypes.byref(overVoltage), transferMode)

The program runs but the values that come back in the array are not
right. However, I am not sure if I am passing the array or if I am
just not reading them well afterwards. What is the best way to put
this in and what is the best way to cast it and read it back?

Thanks,
Sam


From nad at acm.org  Wed Aug  5 19:12:10 2009
From: nad at acm.org (Ned Deily)
Date: Wed, 05 Aug 2009 16:12:10 -0700
Subject: Install setup tools for 2.6
References: <373cf0740908051131gacaf77apba48fa40e929f491@mail.gmail.com>
Message-ID: 

In article 
<373cf0740908051131gacaf77apba48fa40e929f491 at mail.gmail.com>,
 Jeremy Cowles  wrote:
> Ok, I feel like this is a really stupid question, but how do you install
> setup tools for Python 2.6 under windows?
> The only format is .egg which requires setup tools to install, doesn't it?

http://pypi.python.org/pypi/setuptools#id1

-- 
 Ned Deily,
 nad at acm.org



From mensanator at aol.com  Wed Aug  5 19:16:10 2009
From: mensanator at aol.com (Mensanator)
Date: Wed, 5 Aug 2009 16:16:10 -0700 (PDT)
Subject: Turtle Graphics are incompatible with gmpy
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> 
	 
	<4A79C7E2.3000406@aon.at>
	
	
Message-ID: <49395cf2-c2fb-4fd9-b2f2-7f462abe8250@f37g2000yqn.googlegroups.com>

On Aug 5, 5:31?pm, Mensanator  wrote:
> I fixed this to produce the actual image I'm looking
> for instead of that stupid black square. All I did was
> use up() & dowm() in place of penup(), pendown() and
> replace dot(2) with forward(1).
>
> I'll be posting a followup report later.
>

http://www.mensanator.com/mensanator/PythonTurtle/turtle.htm


From ethan at stoneleaf.us  Wed Aug  5 19:29:17 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Wed, 05 Aug 2009 16:29:17 -0700
Subject: Programming by Contract
Message-ID: <4A7A15CD.9090306@stoneleaf.us>

Greetings!

I have seen posts about the assert statement and PbC (or maybe it was 
DbC), and I just took a very brief look at pycontract 
(http://www.wayforward.net/pycontract/) and now I have at least one 
question:  Is this basically another way of thinking about unit testing, 
or is the idea of PbC more along the lines of *always* checking the 
input/output of functions to ensure they are correct?  (*Contstant 
vigilance!* as Prof Moody would say ;)

I know asserts can be turned off, so they obviously won't work for the 
latter case, and having seen the sample of pycontract it seems it only 
does its thing during debugging.

So is Design (Programming) by Contract a fancy way of saying "Document 
your inputs/outputs!" or is there more to it?

~Ethan~


From wolfgang at rohdewald.de  Wed Aug  5 19:48:36 2009
From: wolfgang at rohdewald.de (Wolfgang Rohdewald)
Date: Thu, 6 Aug 2009 01:48:36 +0200
Subject: using expy to extend python
In-Reply-To: <871540.68601.qm@web54204.mail.re2.yahoo.com>
References: <871540.68601.qm@web54204.mail.re2.yahoo.com>
Message-ID: <200908060148.36696.wolfgang@rohdewald.de>

On Thursday 06 August 2009, Yingjie Lan wrote:
> For more information about expy, please visit its homepage at:
> http://expy.sf.net/

looks very interesting, bookmarked.

In your example class mate, def rename looks wrong:
if malloc fails, the previous name should probably not
be replaced by an empty string?

-- 
Wolfgang


From macmanes at gmail.com  Wed Aug  5 19:54:46 2009
From: macmanes at gmail.com (PeroMHC)
Date: Wed, 5 Aug 2009 16:54:46 -0700 (PDT)
Subject: remove last 76 letters from string
Message-ID: 

Hi All, So here is the problem... I have a FASTA file (used for DNA
analyses) that looks like this:

...
>gnl|SRA|SRR019045.10.1 SL-XAY_956090708:2:1:0:1028.1 length=152
NCTTTTTTTATTTTTTGTATAAATGAAGTTTCACTATATCGGACGAGCGGTTCAGCAGTCATTCCGAGAC
CGATATAGTGAAACTTCATTTCTACAAAAANTACCAAACGTCGCTCGGCAGAGCGTCGTGTTGGGCAAGA
GAGTAGCACTCG
>gnl|SRA|SRR019045.11.1 SL-XAY_956090708:2:1:0:1151.1 length=152
NGGTNTGGNNNNCNCCNTNCTNCNNCNTCANCCTCCNGTCNCANNCCNCNTNNNNNCNNNNNCNNTNCTT
CTNCNNTCTCCATTCCTTCTTNATAGCCTGCTCCANCGCACGTTGAACCTTCTGCACCACGAACGCACTC
ACACCACTCATC
>gnl|SRA|SRR019045.12.1 SL-XAY_956090708:2:1:0:1197.1 length=152
NGTCGGGTCTTCGCTATCACTGGACTGCTCCCATCAGCTATAGGTCCTCCCCGCCACACCCCATGCCCAC
CGCCTATCCACGTCTGTCACAACCTCATACATCAGACAGTCACACTTACCAACATATCCAAGCACCTCAA
GCAACACATCAT
...

This snippet represents 3 individual DNA sequences. Each sequences is
identified by the line starting with >
The complete file has about 10 million individual sequences.

A simple enough problem, I want to read in this data, and cut out the
last 76 letters (nucleotides) from each individual sequence and send
them to a new txt file with a similar format.

Any help on how to do this would be appreciated.
Thanks!


From zuo at chopin.edu.pl  Wed Aug  5 20:23:06 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Thu, 06 Aug 2009 02:23:06 +0200
Subject: remove last 76 letters from string
In-Reply-To: 
References: 
Message-ID: 

Dnia 06-08-2009 o 01:54:46 PeroMHC  wrote:

> This snippet represents 3 individual DNA sequences. Each sequences is
> identified by the line starting with >
> The complete file has about 10 million individual sequences.
>
> A simple enough problem, I want to read in this data, and cut out the
> last 76 letters (nucleotides) from each individual sequence and send
> them to a new txt file with a similar format.

If I understand correctly you want sth like this:


with open(path_to_the_input_file) as fasta:
     with open(path_to_the_input_file) as nucleotides:
	for seq in fasta:
             print >>nucleotides, '> foo bar length=76'
             print >>nucleotides, seq[-76]


Cheers,
*j

-- 
Jan Kaliszewski (zuo) 


From zuo at chopin.edu.pl  Wed Aug  5 20:24:22 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Thu, 06 Aug 2009 02:24:22 +0200
Subject: remove last 76 letters from string [sorry, errata]
In-Reply-To: 
References: 
Message-ID: 

Dnia 06-08-2009 o 01:54:46 PeroMHC  wrote:

> This snippet represents 3 individual DNA sequences. Each sequences is
> identified by the line starting with >
> The complete file has about 10 million individual sequences.
>
> A simple enough problem, I want to read in this data, and cut out the
> last 76 letters (nucleotides) from each individual sequence and send
> them to a new txt file with a similar format.

If I understand correctly you want sth like this:


with open(path_to_the_input_file) as fasta:
       with open(path_to_the_output_file) as nucleotides:
	for seq in fasta:
               print >>nucleotides, '> foo bar length=76'
               print >>nucleotides, seq[-76]


Cheers,
*j

-- 
Jan Kaliszewski (zuo) 


From python at mrabarnett.plus.com  Wed Aug  5 20:26:22 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 01:26:22 +0100
Subject: String to valid Python identifier
In-Reply-To: 
References: 
Message-ID: <4A7A232E.1060402@mrabarnett.plus.com>

?????? ??????????? wrote:
> Is there any easy function in the stdlib to convert any random string in 
> a valid Python identifier .. possibly by replacing non-valid characters 
> with _ ?
> 
> Python 2.x only, so no need to do Unicode.
> 
Lookup the 'maketrans' function in the 'string' module and the
'translate' method of the 'str' class.


From python at mrabarnett.plus.com  Wed Aug  5 20:32:22 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 01:32:22 +0100
Subject: remove last 76 letters from string
In-Reply-To: 
References: 
Message-ID: <4A7A2496.4080808@mrabarnett.plus.com>

PeroMHC wrote:
> Hi All, So here is the problem... I have a FASTA file (used for DNA
> analyses) that looks like this:
> 
> ...
>> gnl|SRA|SRR019045.10.1 SL-XAY_956090708:2:1:0:1028.1 length=152
> NCTTTTTTTATTTTTTGTATAAATGAAGTTTCACTATATCGGACGAGCGGTTCAGCAGTCATTCCGAGAC
> CGATATAGTGAAACTTCATTTCTACAAAAANTACCAAACGTCGCTCGGCAGAGCGTCGTGTTGGGCAAGA
> GAGTAGCACTCG
>> gnl|SRA|SRR019045.11.1 SL-XAY_956090708:2:1:0:1151.1 length=152
> NGGTNTGGNNNNCNCCNTNCTNCNNCNTCANCCTCCNGTCNCANNCCNCNTNNNNNCNNNNNCNNTNCTT
> CTNCNNTCTCCATTCCTTCTTNATAGCCTGCTCCANCGCACGTTGAACCTTCTGCACCACGAACGCACTC
> ACACCACTCATC
>> gnl|SRA|SRR019045.12.1 SL-XAY_956090708:2:1:0:1197.1 length=152
> NGTCGGGTCTTCGCTATCACTGGACTGCTCCCATCAGCTATAGGTCCTCCCCGCCACACCCCATGCCCAC
> CGCCTATCCACGTCTGTCACAACCTCATACATCAGACAGTCACACTTACCAACATATCCAAGCACCTCAA
> GCAACACATCAT
> ...
> 
> This snippet represents 3 individual DNA sequences. Each sequences is
> identified by the line starting with >
> The complete file has about 10 million individual sequences.
> 
> A simple enough problem, I want to read in this data, and cut out the
> last 76 letters (nucleotides) from each individual sequence and send
> them to a new txt file with a similar format.
> 
> Any help on how to do this would be appreciated.
> Thanks!

If the input file is large then you can reduce the amount of memory
needed by reading the input file a line at a time by iterating over the
file object:

     input_file = open(input_path)
     for line in input_file:
         ...
     input_file.close()

Each line will end with '\n', so use the 'rstrip' method to remove it,
and then slice the last 76 characters:

     last_part = line.rstrip()[-76 : ]


From darkneter at gmail.com  Wed Aug  5 20:39:52 2009
From: darkneter at gmail.com (NighterNet)
Date: Wed, 5 Aug 2009 17:39:52 -0700 (PDT)
Subject: sqlite3 gui
Message-ID: <3d2c4f7a-9d9b-4aff-9de1-141ecf4327de@x6g2000prc.googlegroups.com>

This took a while to get a gui working. I am new at this coding.

This work with sqlite3 Python Version: 3.1.0. The older version
doesn't work.

#!/usr/local/bin/python
'''
    This is for basic database access to view the information.
Python version: 3.1.0

Features:
-view database.
-run script
-update row
-delete row
-insert row

To do list:
-delete table
-create table
-export database
-import database
-primary id need to able to insert to the table
-delete table row
-refresh data

Note:
-It doesn't remove the GUI
-It bit buggy.
-Python version: 3.0.1 -Doesn't support the gui

execute script without '"' ->  INSERT INTO member (user, password)
VALUES( "admin", "admin")
'''

from tkinter import *
from tkinter import ttk
from tkinter import tix
import sqlite3 as sqlite
import re

DATABASE = 'nameofdatabasefile.db'
title = "Sqlite3 Database";

db = sqlite.connect(DATABASE);
cur = db.cursor();

print("#==============================#")
print("# Python Version: 3.1.0        #")
print("# sqlite3                      #")
print("#==============================#")

class Application(Frame):
    #label_serverstatus = Label()
    table = []
    tablename = ''
    tablerowid = ''
    tablecolid = '0'
    tablerowname = ''
    tablevarinput = []
    tablevartext = []
    tableentrywidgetrow = []
    tablelabelwidgetrow = []

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master.grid_columnconfigure(0, weight=1)
        self.master.grid_rowconfigure(0, weight=1)
        self.master.title(title)
        self.listtable()#Make a list table
        self.createWidgets()
        self.master.geometry("800x600")
        self.pack()
    def listtable(self):
        self.table = []
        cur.execute("select * from sqlite_master WHERE type='table'");
        for t in cur:
            #print (t[1])
            self.table.append(t[1])

    #Create Widgets
    def createWidgets(self):
        #Schema
        self.Schemaframe = ttk.Labelframe(self, text='Schema',
width=600, height=100)
        self.Schemaframe.grid(column=1, row=1, sticky=W)
        self.text_database = Label(self.Schemaframe)
        self.text_database["text"] = "Schema Database:" + DATABASE
        self.text_database.grid(column=1, row=1, sticky=W)

        #Table
        self.tableframe = ttk.Labelframe(self, text='Schema Table',
width=600, height=100)
        self.tableframe.grid(column=1, row=2, sticky=W)
        self.text_table = Label(self.tableframe)
        self.text_table["text"] = "table:"
        self.text_table.grid(column=1, row=1, sticky=W)

        self.combobox = ttk.Combobox(self.tableframe)
        self.combobox.grid(column=2, row=1, sticky=W)
        self.combobox["values"] = self.table
        self.combobox.bind('<>', self.table_click)
        self.combobox.current(1)

        self.button_deletetable = Button(self.tableframe)
        self.button_deletetable["text"] = "Delete Table"
        self.button_deletetable.grid(column=3, row=1, sticky=W)

        self.button_createtable = Button(self.tableframe)
        self.button_createtable["text"] = "Create Table"
        self.button_createtable.grid(column=4, row=1, sticky=W)

        #Table
        self.scriptframe = ttk.Labelframe(self, text='Schema Script',
width=600, height=100)
        self.scriptframe.grid(column=1, row=3, sticky=W)

        self.button_script = Button(self.scriptframe)
        self.button_script["text"] = "Exeute script"
        self.button_script["command"] = self.executescript
        self.button_script.grid(column=1, row=1, sticky=W)

        self.button_commit = Button(self.scriptframe)
        self.button_commit["text"] = "Commit"
        self.button_commit["command"] = self.commit_save
        self.button_commit.grid(column=2, row=1, sticky=W)

        #TEXT BOX
        self.textbox = Text(self.scriptframe, width=40, height=10)
        self.textbox.grid(column=1, row=2, sticky=W,columnspan=6)

        #TABLE FRAME LIST
        self.tablerowframe = ttk.Labelframe(self, text='Table Rows',
width=600, height=100)
        self.tablerowframe.grid(column=2, row=1, sticky=W,rowspan=3)

        #TABLE ROW LIST
        self.listbox = Listbox(self.tablerowframe, exportselection=0,
background="white")
        self.listbox.bind("<>",self.listselect_click)
        self.listbox.grid(column=1, row=1, sticky=W)

        #vbar
        self.vbar = Scrollbar(self.tablerowframe, name="vbar")
        self.vbar.grid(column=1, row=1, sticky=E)
        self.vbar.configure(orient=VERTICAL,
command=self.listbox.yview)
        self.listbox.configure(yscrollcommand=self.vbar.set)

        self.button_createrow = Button(self.tablerowframe)
        self.button_createrow["text"] = "Create Table Row"
        self.button_createrow["command"] = self.commit_save
        self.button_createrow.grid(column=1, row=2, sticky=W)

        #TABLE FRAME ROW EDIT
        self.tablerowframe = ttk.Labelframe(self, text='Table Rows
EDIT', width=256, height=480)
        self.tablerowframe.grid(column=1, row=4, sticky=W)

    #SELECT TABLE FROM COMBOBOX
    def table_click(self,event):
        #print("click")
        self.tablename = str(self.combobox.selection_get())
        print(self.tablename)
        self.tableselected(self.tablename);
        return "break"

    #SHOW TABLE ROWS IN THE LIST BOX
    def tableselected(self,name):
        #print("TABLE SELECT ->" + str(name))
        cur.execute("select * from " + name);
        self.listbox.delete(0, "end")
        for t in cur:
            #print (t)
            #print (t[1])#table
            #spreadsheet.append(t[1])
            self.listbox.insert("end", str(t[0]))
        #self.listbox["listvariable"] = spreadsheet

    #CLICK TABLE ROW SELECTED ID OR ROW NAME
    def listselect_click(self,event):
        rowid = self.listbox.curselection()
        rowid = self.listbox.index(rowid)
        #print(self.listbox.get(rowid))
        self.tablerowid = rowid
        self.tablerowname = self.listbox.get(rowid)
        self.selecttablerow()
        return "break"

    #TABLE ROW INFORMATION
    def selecttablerow(self):
        #print ("TABLE ROW ->")
        self.tablevartext = []
        self.tablevarinput = []

        cur.execute("select * from sqlite_master WHERE type='table'");
        for t in cur:
            if self.tablename == t[1]:
                #print (t)
                tablestr = t[4].replace("CREATE TABLE "
+self.tablename + " ",'')
                tablestr = tablestr.replace("(","")
                tablestr = tablestr.replace(")","")
                comumndata = tablestr.split(',')

                for col in comumndata:
                    col = col.strip()
                    m = re.match(r"(^(\w+))",col)
                    #print (m.group(0))#column name of the table
current selected.
                    self.tablevartext.append(m.group(0))
                break

        query = str('SELECT * FROM ' + self.tablename + " WHERE id=\'"
+ self.tablerowname + "\'")
        #print(query)
        cur.execute(query);
        #table row out put
        for t in cur:
            #print (t)
            for vardata in t:
                #print(vardata)
                self.tablevarinput.append(vardata)
        self.deletetablerowinput
        self.createtablerowinput()

    def createtablerowinput(self):
        self.deletetablerowinput()
        rowcount = 0
        #self.button_destroy = Button(self.tablerowframe)
        #self.button_destroy["text"] = "delete rows"
        #self.button_destroy["command"] = self.deletetablerowinput
        #self.button_destroy.grid(column=1, row=1, sticky=W)

        self.button_deleterowtable = Button(self.tablerowframe)
        self.button_deleterowtable["text"] = "Delete Table Row"
        self.button_deleterowtable["command"] = self.deletetablerow
        self.button_deleterowtable.grid(column=1, row=1, sticky=W)

        self.button_updatetablerow = Button(self.tablerowframe)
        self.button_updatetablerow["text"] = "Update Table Row"
        self.button_updatetablerow["command"] = self.updatetablerow
        self.button_updatetablerow.grid(column=2, row=1, sticky=W)

        self.button_inserttablerow = Button(self.tablerowframe)
        self.button_inserttablerow["text"] = "Insert Table Row"
        self.button_inserttablerow["command"] = self.inserttablerow
        self.button_inserttablerow.grid(column=3, row=1, sticky=W)

        for columnname in self.tablevartext:
            #print(columnname)
            self.entry_tablevarrow = Entry(self.tablerowframe,
width=30, textvariable=columnname)
            self.entry_tablevarrow.delete(0,"end")
            self.entry_tablevarrow.insert(0,str(self.tablevarinput
[rowcount]))
            self.entry_tablevarrow.grid(column=2, row=rowcount+2,
sticky=W)
            self.tableentrywidgetrow.append(self.entry_tablevarrow)

            self.label_var = Label(self.tablerowframe, width=16)
            self.label_var['text'] = columnname
            self.label_var.grid(column=1, row=rowcount+2, sticky=W)
            self.tablelabelwidgetrow.append(self.label_var)
            #print(rowcount)
            rowcount += 1
    def updatetablerow(self):
        count = 0;
        #mysql_query("UPDATE  $db_table SET imageid='{$hashname}'
WHERE idhash='{$IDIMAGE}'")
        query = "UPDATE " + self.tablename
        set = " SET "
        where = "WHERE"
        for x in self.tableentrywidgetrow:
            if count == 0:
                where = where + " " + x["textvariable"] + "=\'" + x.get
() + "\' "
            else:
                if count == len(self.tableentrywidgetrow)-1:
                    set = set + "" + x["textvariable"] + "=\'" + x.get
() + "\' "
                else:
                    set = set + "" + x["textvariable"] + "=\'" + x.get
() + "\', "

            print ( x["textvariable"] + "->" +  x.get())
            count += 1
        print (query + set + where)
        querystring = query + set + where
        self.applydata(querystring)
        #print (len(self.tableentrywidgetrow))
    def deletetablerow(self):
        count = 0;
        query = "DELETE FROM " + self.tablename + " WHERE "
        delete = ""
        for x in self.tableentrywidgetrow:
            if count == len(self.tableentrywidgetrow)-1:
                delete = delete + "" + x["textvariable"] + "=\'" +
x.get() + "\' "
            else:
                delete = delete + "" + x["textvariable"] + "=\'" +
x.get() + "\' AND "
            count += 1
        print (query + delete)
        querystring = query + delete
        self.applydata(querystring)
        #print (len(self.tableentrywidgetrow))
    def inserttablerow(self):
        #cur.execute('INSERT INTO member (user, password) VALUES
( "admin", "admin")')
        count = 0;
        query = "INSERT INTO " + self.tablename + "("
        values = ""
        insert = ""
        #be sure it not the primary key else it will give error
        for x in self.tableentrywidgetrow:
            if count == len(self.tableentrywidgetrow)-1:
                values = values + x["textvariable"] + ''
                insert = insert + '\"' + x.get() + '\"'
            else:
                if count == 0:
                    print ("PRIMARY KEY")
                else:
                    values = values + x["textvariable"] + ','
                    insert = insert + '\"' + x.get() + '\",'

            count += 1

        querystring = query + values + ") VALUES(" + insert + ")"
        print (querystring)
        self.applydata(querystring)
        #print (len(self.tableentrywidgetrow))

    def deletetablerowinput(self):
        for x in self.tableentrywidgetrow:
            x.destroy()
        self.tableentrywidgetrow = []
        for y in self.tablelabelwidgetrow:
            x.destroy()
        self.tablelabelwidgetrow = []

    #SCRIPTS ++++++
    def executescript(self):
        print("Execute Script...")
        scripttext = self.textbox.get('1.0', 'end')
        self.applydata(scripttext)
        print(scripttext)
    #COMMIT +++++++
    def commit_save(self):
        print("Sqlite3 Commit")
        db.commit()
    def applydata(self,querystr):
        print("Sqlite3 Commit")
        db = sqlite.connect(DATABASE);
        cur = db.cursor()
        cur.execute(querystr)
        db.commit()

root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()

Not sure what you guys think about this. Still working on it. I can't
hard code this well. Still learning it. >.<


From lanyjie at yahoo.com  Wed Aug  5 20:40:18 2009
From: lanyjie at yahoo.com (Yingjie Lan)
Date: Wed, 5 Aug 2009 17:40:18 -0700 (PDT)
Subject: using expy to extend python
In-Reply-To: <200908060148.36696.wolfgang@rohdewald.de>
Message-ID: <870509.8482.qm@web54208.mail.re2.yahoo.com>


> From: Wolfgang Rohdewald 
> Subject: Re: using expy to extend python
> To: python-list at python.org
> Date: Thursday, August 6, 2009, 3:48 AM
> On Thursday 06 August 2009, Yingjie
> Lan wrote:
> > For more information about expy, please visit its
> homepage at:
> > http://expy.sf.net/
> 
> looks very interesting, bookmarked.
> 

Glad to hear that! Thanks.

> In your example class mate, def rename looks wrong:
> if malloc fails, the previous name should probably not
> be replaced by an empty string?
> 

Thanks for pointing that out. Probably should throw an exception if malloc fails. 

Yingjie


      


From gregor.lingl at aon.at  Wed Aug  5 20:49:44 2009
From: gregor.lingl at aon.at (Gregor Lingl)
Date: Thu, 06 Aug 2009 02:49:44 +0200
Subject: Turtle Graphics are incompatible with gmpy
In-Reply-To: <49395cf2-c2fb-4fd9-b2f2-7f462abe8250@f37g2000yqn.googlegroups.com>
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at>
	
	<4A79C7E2.3000406@aon.at>
	
	
	<49395cf2-c2fb-4fd9-b2f2-7f462abe8250@f37g2000yqn.googlegroups.com>
Message-ID: <4a7a28b3$0$2303$91cee783@newsreader01.highway.telekom.at>

Mensanator schrieb:
> On Aug 5, 5:31 pm, Mensanator  wrote:
>> I fixed this to produce the actual image I'm looking
>> for instead of that stupid black square. All I did was
>> use up() & dowm() in place of penup(), pendown() and
>> replace dot(2) with forward(1).
>>
>> I'll be posting a followup report later.
>>
> 
> http://www.mensanator.com/mensanator/PythonTurtle/turtle.htm

Hi Mansanator,

Thanks for that thorough investigations.
I hope I'll soon find time to study it in detail.

I've just one idea, but I don't know if you might
be intersted in it or if it's rewarding at all:

What would be the results when using the old turtle
module with Python 3.1 (it will certainly not run
out of the box, but perhaps 2to3 might do it?)

That would clarify the question if there is some
impact of new division or some changes in Tkinter.

Best regards,
Gregor


From gagsl-py2 at yahoo.com.ar  Wed Aug  5 20:54:07 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Wed, 05 Aug 2009 21:54:07 -0300
Subject: Datetime with float seconds
References: 
Message-ID: 

En Wed, 05 Aug 2009 09:50:04 -0300, kpal 
escribi?:

> The standard datetime has 1 microsecond granularity.

Note that this is the finest granularity a datetime object can store, NOT
the precision of datetime.now() by example.

> My application
> needs finer time resolution, preferably float seconds.

"float seconds" doesn't mean much. time.time returns float seconds, but
its precision is around 15ms on Windows.

> Is there an
> alternative to the out-of-the-box datetime? Timezone support is not
> essential.

On Windows, use time.clock(), which internally uses
QueryPerformanceCounter. The resolution depends on your hardware, but it's
typically better than 1 microsecond. If you want to know the actual value:

py> from ctypes import *
py> kernel32=windll.kernel32
py> QueryPerformanceCounter=kernel32.QueryPerformanceCounter
py> QueryPerformanceFrequency=kernel32.QueryPerformanceFrequency
py> plonglong = POINTER(c_longlong)
py> QueryPerformanceFrequency.argtypes = [plonglong]
py> freq = c_longlong()
py> QueryPerformanceFrequency(byref(freq))
1
py> freq
c_longlong(3579545L)

That is, on my system the resolution is 1/3579545s, or better than 300ns

-- 
Gabriel Genellina



From gagsl-py2 at yahoo.com.ar  Wed Aug  5 20:54:16 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Wed, 05 Aug 2009 21:54:16 -0300
Subject: Install setup tools for 2.6
References: <373cf0740908051131gacaf77apba48fa40e929f491@mail.gmail.com>
Message-ID: 

En Wed, 05 Aug 2009 15:31:38 -0300, Jeremy Cowles
 escribi?:

> Ok, I feel like this is a really stupid question, but how do you install
> setup tools for Python 2.6 under windows?
> The only format is .egg which requires setup tools to install, doesn't  
> it?

I have no idea, and I try to stay as far away from setuptools/ez_setup as
I can. I think they solve some kind of problems for some kind of people
(else the tool would be defunct by now), but haven't worked for me.
Perhaps you don't need setuptools either?

-- 
Gabriel Genellina



From mensanator at aol.com  Wed Aug  5 21:31:00 2009
From: mensanator at aol.com (Mensanator)
Date: Wed, 5 Aug 2009 18:31:00 -0700 (PDT)
Subject: Turtle Graphics are incompatible with gmpy
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> 
	 
	<4A79C7E2.3000406@aon.at>
	
	 
	<49395cf2-c2fb-4fd9-b2f2-7f462abe8250@f37g2000yqn.googlegroups.com> 
	<4a7a28b3$0$2303$91cee783@newsreader01.highway.telekom.at>
Message-ID: 

On Aug 5, 7:49?pm, Gregor Lingl  wrote:
> Mensanator schrieb:
>
> > On Aug 5, 5:31 pm, Mensanator  wrote:
> >> I fixed this to produce the actual image I'm looking
> >> for instead of that stupid black square. All I did was
> >> use up() & dowm() in place of penup(), pendown() and
> >> replace dot(2) with forward(1).
>
> >> I'll be posting a followup report later.
>
> >http://www.mensanator.com/mensanator/PythonTurtle/turtle.htm
>
> Hi Mansanator,
>
> Thanks for that thorough investigations.
> I hope I'll soon find time to study it in detail.
>
> I've just one idea, but I don't know if you might
> be intersted in it or if it's rewarding at all:

Sure, not tonight, of course, but I can give it try.

>
> What would be the results when using the old turtle
> module with Python 3.1 (it will certainly not run
> out of the box, but perhaps 2to3 might do it?)

I would just need to copy turtle.py to 3.1 Lib (renamed,
of course)?

>
> That would clarify the question if there is some
> impact of new division or some changes in Tkinter.

I had a quick glance through the code. Not too many divisions
and most of them seemd to already be forcing float division
by constructs such as mutiplying by 1.0 (which I assume isn't
strictly neccessary as long as / and // are used correctly.

It seemed a lot of floats were used in the 2.5 code as I saw
such stuff as int(difference), so I really don't know why
.mpz would be a problem since they are integers also and a
Python int ought to be the same thing when coerced to a float
(at least in the range used by Turtle graphics.

>
> Best regards,
> Gregor



From sjmachin at lexicon.net  Wed Aug  5 21:31:56 2009
From: sjmachin at lexicon.net (John Machin)
Date: Thu, 6 Aug 2009 01:31:56 +0000 (UTC)
Subject: unicode() vs. s.decode()
References: 
	<1249487636.7120.798.camel@arrakis>
Message-ID: 

Jason Tackaberry  urandom.ca> writes:
> On Wed, 2009-08-05 at 16:43 +0200, Michael Str?der wrote:
> > These both expressions are equivalent but which is faster or should be used
> > for any reason?
> > u = unicode(s,'utf-8')
> > u = s.decode('utf-8') # looks nicer
> 
> It is sometimes non-obvious which constructs are faster than others in
> Python.  I also regularly have these questions, but it's pretty easy to
> run quick (albeit naive) benchmarks to see.
> 
> The first thing to try is to have a look at the bytecode for each:
[snip] 
> The presence of LOAD_ATTR in the first form hints that this is probably
> going to be slower.   Next, actually try it:
> 
>         >>> import timeit
>         >>> timeit.timeit('"foobarbaz".decode("utf-8")')
>         1.698289155960083
>         >>> timeit.timeit('unicode("foobarbaz", "utf-8")')
>         0.53305888175964355
> 
> So indeed, uncode(s, 'utf-8') is faster by a fair margin.

Faster by an enormous margin; attributing this to the cost of attribute lookup
seems implausible.

Suggested further avenues of investigation:

(1) Try the timing again with "cp1252" and "utf8" and "utf_8"

(2) grep "utf-8" /Objects/unicodeobject.c

HTH,
John



From digitalhillbilly at hotmail.com  Wed Aug  5 21:40:57 2009
From: digitalhillbilly at hotmail.com (DH)
Date: Wed, 5 Aug 2009 18:40:57 -0700 (PDT)
Subject: access read / write violation with ctypes
Message-ID: 

Hi all,

I'm quite new to cytpes and am having some troubles I was hoping I
could get a little help with. Before I get into the details this is
what I'm trying to accomplish - I would like to read a dng with python
pass it through either libraw.dll or dcraw.dll (notes on dcraw.dll
version at the end) for initial processing then to MagickWand for some
light enhancement and final jpeg output. After I get these working I
will see how I can add LittleCMS into the fray. I'm not doing
something correctly but don't know what. I've read a lot of documents
over the past couple days and though I've learned quite a lot I just
can't get past this access violation error.

I very grateful for anything that can be offered.

dh

...

I am currently working out MagickWand and dcraw separately but am
having similar troubles with both resulting in either 'Windows Error:
exception: access violation reading 0x00000000' or alternatively
'Windows Error: ... writing'

1 - MagickWand (read violation):

I'm using popen to capture dcraw stdout and want to pass it to
magickwand. If I instead write the dcraw output to a file then read it
with magickwand I get the same error. But if I comment out the dcraw
protion and read the dcraw output file from the previous attempt,
MagickWand opens the file fine and I can manipulate it to my hearts
content. The basics:

proc = subprocess.Popen("dcraw -c -4 -T image.dng", shell=True,
close_fds=False, stdout=subprocess.PIPE).communicate()[0]

magickWandLib = 'C:\\Program Files (x86)\\ImageMagick-6.5.3-Q16\
\CORE_RL_wand_.dll'
Magick = cdll.LoadLibrary(magickWandLib)

Magick.MagickWandGenesis()
wand = Magick.NewMagickWand()

Magick.MagickReadImageFile(proc)
-> access violation reading

2 - DCRaw (write violation):

I've been bouncing between libraw.dll and dcraw.dll. The dcraw version
I'm using is found at
http://translate.google.com/translate?hl=en&sl=es&tl=en&u=http://www.ojodigital.com/foro/perfectraw-perfectblend/206898-perfectraw-0-5-a.html
. Libraw is limited in the sence that it is mainly suited to loading
and unpacking raw images. Actual processing is done only in emulation
mode which I have not yet been able to access throught the library.
PerfectRaw uses a tweaked and librarised version of dcraw with thier
GUI + some enhanced functions. I'm only interesed in the dll though

2.1 - libraw.dll

I won't go into great detail as I can get it to work but only open,
unpack and write out a tiff or ppm. No process settings

2.2 - dcraw.dll

I can load the library but cannot initialise an instance. Each attempt
in a variety or methods always returns an 'access violation writing
0x00000000'. The parameters I use to initialise are taken from a test
program provided by the authors.

test app:
	int w,h;
	printf("Resultado de leer el RAW: %i\n",DCRAW_Init("c:\\test\
\IMG_4118.CR2",&w,&h)

python:
	dcraw_lib = 'C:\\programs\\PerfectRaw\\dcraw.dll'
	dcraw = ctypes.cdll.LoadLibrary(dcraw_lib)

	img = 'C:\\programs\\PerfectRaw\\image.dng'
	dcraw.DCRAW_Init(img,4000,3000) # canon G9 converted to dng
	-> access violation writing



From gforgx at lavabit.com  Wed Aug  5 21:51:52 2009
From: gforgx at lavabit.com (Sergey Simonenko)
Date: Wed, 05 Aug 2009 19:51:52 -0600
Subject: Subclassing Python's dict
Message-ID: 

Hi,

I subclass builtin 'dict' in my application and experience some problems  
with it.

The whole issue is that I should redefine 'setdefault' and 'update'  
methods after redefining '__setitem__' or/and '__delitem__',
otherwise 'update' and 'setdefault' ignore redefined '__setitem__' and use  
builtin dict's one so dict looks kinda like a black box.

Another guy have reported me that he experiences similar problems with  
subclassing builtin 'list'.

Kind regards, Sergey.

-- 
???????? ? ???????? ??????? ???????? Opera: http://www.opera.com/mail/



From cocobear.cn at gmail.com  Wed Aug  5 22:17:53 2009
From: cocobear.cn at gmail.com (cocobear)
Date: Wed, 5 Aug 2009 19:17:53 -0700 (PDT)
Subject: merge two png pic
References: 
	 
	
	<006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com>
	<4a77e249$0$2449$426a74cc@news.free.fr>
	<72d7aad1-1fb7-4b32-a87f-636505b0faa2@v15g2000prn.googlegroups.com>
	<4a793852$0$19598$426a74cc@news.free.fr>
Message-ID: <69579cfc-9151-43df-a5ef-a6b05f1bd718@13g2000prl.googlegroups.com>

On Aug 5, 3:44?pm, News123  wrote:
> You didn't really tell us why you need one big file, which contains more
> pixel, than you can probably store in RAM
>

In fact I do not need such a big image.
I just want to know the solution.


> Is it for printing?
> Not knwoing your goal makes it difficult to suggest solutions.
>
> Can't you use other image formats like raw RGB or
> What other image formats are supported?
> tiff? Raw? PPM (http://en.wikipedia.org/wiki/Portable_pixmap)?
>

I want to view image use Windows Pic View.

I don't familiar with PPM? photoshop don't support PPM, does PIL
support this format?


> concatenating raw/ppm files with the same width would be really trivial.
>
> so you could use python to create horizontal raw/ppm stripes.
>
> then you could concatenate them without having to have the whole image
> in RAM.
>
> Perhaps there's even converters from ppm to png, that don't need the
> whole image in RAM.
>
>
>
> cocobear wrote:
> > On Aug 4, 3:24 pm, News123  wrote:
> >> Hi,
>
> >> cocobear wrote:
> >>>>>>> Map = Image.new("RGB", (x,y))
> >>>>>>> Map.paste(im, box)
> >>>>>>> Map.paste(im1,box)
> >>>>>>> Map = Map.convert("L", optimize=True, palette=Image.ADAPTIVE)
> >>>>>>> But if thetwopngpicis too big , or if I have tomergemorepic
> >>>>>>> together, I will get MemoryError:
> >>>>>>>>>>>>> Image.new("RGB",(44544,38656))
> >>>> What do you want to do with such a big image? You will run into the same
> >>>> limitation when you are trying to display it.
> >>> I want to download a map from google map with high precision
> >> For me it sounds strange to handle such big files.
>
> >> Is the map you download from Google really that big?
> >> Mostly Google maps uses normally tiles of sizes 256x256 pixel, wich you
> >> have to compose to get the ?big image.
>
> > The map I downloaded from Google is small(256x256). These small maps
> > will compose a big image.
>
> >> If your problem is to combine tiles with different palettes, then you
> >> should pobably look at a way to ?'unify' the palette of all tiles befor
> >> combining them.
>
> > I think it is impossible to 'unify' all this tiles.
>
> >> Being no expert of PIL I don't know whether this is easily possible though?
>
> >> bye
>
> >> N



From wuwei23 at gmail.com  Wed Aug  5 23:19:37 2009
From: wuwei23 at gmail.com (alex23)
Date: Wed, 5 Aug 2009 20:19:37 -0700 (PDT)
Subject: Subclassing Python's dict
References: 
	<2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com> 
	
Message-ID: 

Xavier Ho wrote:
> You should subclass collections.UserDict, and not the default dict class.
> Refer to the collections module.

Xavier, why do you think that is the correct approach? The docs say
"The need for this class has been largely supplanted by the ability to
subclass directly from dict (a feature that became available starting
with Python version 2.2)."

If you mean that Sergey should subclass _in this instance_ could you
please explain why? (Sorry if you already have, I never saw your
original post...)




From rt8396 at gmail.com  Wed Aug  5 23:35:43 2009
From: rt8396 at gmail.com (r)
Date: Wed, 5 Aug 2009 20:35:43 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
Message-ID: <93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegroups.com>

On Aug 4, 12:55?am, David Lyon  wrote:
> It isn't totally about the writers...
> Peoples egos are also at stake - it seems.
> If "Fred X wrote Doc Y".. they don't want their name taken off.. So
> they generally speaking don't want the docs changed.
> If you talk too much about docs.. you can be told you're OT..
> even in a thread about docs...

This is the most honest post within this thread. Yes i believe --
although it does not make me happy-- that many within this community
are hostile, vulgar, and viscous towards any notion of change if it
comes from outside the "insiders" group (and even sometimes from the
inside). Which is very sad.

Yes sometimes people are just trolling, but this tread has nothing to
do with trolling. kj has a legitimate complaint. Do i believe the docs
are a complete waste of bytes, No! Many people have invested tons of
hard work into them (and i thank them for their hard work). But i do
believe --like all things in this word-- perfection is always just out
of hands reach, we must constantly seek perfection because we can
never attain it. Like any group effort, eventually it will adopt the
idioms of self indulgence. Python dev needs the input of those who are
not experts in the language --especially in the realm of docs.

It is so easy to forget the struggles we face when learning something
new. The accessibility and appeal of Python to new users is in the
best interest of this community. If you don't believe that, you are
pissing on all the years of hard work that has been put in here. You
might as well just tell Guido to "close up shop"

I have posted this once before but i will post it again. Please read
Christopher's words carefully because they apply to this community in
a big way...Don't fall into the trap of narcissism.

Christopher Lasch referring to the pitfalls of Narcissistic societies:

"""In such a society of constant competition, there can be no allies,
and little transparency. The threats to
acquisitions of social symbols are so numerous, varied and frequently
incomprehensible, that defensiveness, as well as competitiveness,
becomes a way of life. Any real sense of community is undermined -- or
even destroyed -- to be replaced by virtual equivalents that strive,
unsuccessfully, to synthesize a sense of community."""

While I agree that some narcissism is vital to an individuals ego in
competitive atmospheres, I do not believe the Python community
warrants this need.


From rays at blue-cove.com  Thu Aug  6 00:21:13 2009
From: rays at blue-cove.com (RayS)
Date: Wed, 05 Aug 2009 21:21:13 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com>
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
Message-ID: <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>

An HTML attachment was scrubbed...
URL: 

From davea at ieee.org  Thu Aug  6 00:51:19 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 00:51:19 -0400
Subject: Error on Attaching to the process while debugging
In-Reply-To: <21dbc649-2f82-4e4c-9777-c8a58c25a9e0@r2g2000yqm.googlegroups.com>
References: <21dbc649-2f82-4e4c-9777-c8a58c25a9e0@r2g2000yqm.googlegroups.com>
Message-ID: <4A7A6147.5030901@ieee.org>


MalC0de wrote:
> Hello there, I'm writting a debugger,
> the problem is there no good interpretation ...
>
> here's the codes:
>
> my_debugger.py :
>
> #!/usr/bin/env python
> from ctypes import *
> from my_debugger_defines import *
> kernel32 = windll.kernel32
> class debugger():
>     def __init__(self):
> 	  self.h_process = None
> 	  self.pid = None
> 	  self.debugger_active = False
>           pass
>     def load(self,path_to_exe):
>         creation_flags = DEBUG_PROCESS
>         startupinfo = STARTUPINFO()
>         process_information = PROCESSINFORMATION()
>         startupinfo.dwFlags = 0x1
>         startupinfo.wShowWindow = 0x0
>         startupinfo.cb = sizeof(startupinfo)
>         if kernel32.CreateProcessA(path_to_exe,
>                                     None,
>                                     None,
>                                     None,
>                                     None,
>                                     creation_flags,
>                                     None,
>                                     None,
>                                     byref(startupinfo),
>                                     byref(process_information)):
>                   print "[*]we have sucessfully launched the process"
>                   print "[*]PID %d" % process_information.dwProcessId
>                   self.h_process = self.open_process
> (process_information.dwProcessId)
>         else:
>             print"[*]Error 0x%08x." % kernel32.GetLastError()
>
> def Open_process(self,pid):
>     h_process = kernel32.OpenProcess(PROCESS_ALL_ACCESS,pid,False)
>     return h_process
> def attach(self,pid):
>         self.h_process = self.open_process(pid)
>         # We attempt to attach to the process
>         # if this fails we exit the call
>         if kernel32.DebugActiveProcess(pid):
>             self.debugger_active = True
>             self.pid             = int(pid)
>
>         else:
>             print "[*] Unable to attach to the process."
>
> def run(self):
>     while self.debugger_active == True:
>         self.get_debug_event()
> def get_debug_event(self):
>     debug_event = DEBUG_EVENT()
>     continue_status = DBG_CONTINUE
>     if kernel32.WaitForDebugEvent(byref(debug_event),INFINITE):
>         raw_input("Press a key to continue ...")
>     self.debugger_active = False
>     kernel32.ContinueDebugEvent
> (debug_event.dwProdcessid,debug_event.dwThreadId,continue_status)
>     def detach(self):
>         if kernel32.DeugActiveProcessStop(self.pid):
>             print "[*]Finished debugging. exiting ..."
>             return True
>         else:
>             print "there was an error"
>             return false
>
> it's already have a method named : Attach ...
> 
>   
Indentation is critical.  You have defined functions ( Open_process() 
attach(), run(), etc. ) that have formal parameters named self, but are 
indented outside of the class definition.  Indentation trumps, so these 
are not attributes of the class.  They're functions, not methods.

It looks like you have other indentation problems, but I'll let you run 
with this much.

Incidentally, following naming conventions could also help here.  
debugger is a class, but it's not capitalized.  Open_process() is 
intended to be a method, but it is capitalized.  And your comments refer 
to attach() as Attach...  Another convention you're breaking is using    
"from ctypes import * "   That's a dangerous way to do imports, as it 
mixes those names with the ones in this module.  I prefer a simple 
import, and use the module name as a prefix when you reference those 
symbols.  If there are a few symbols you do want to have directly 
included, then import them one at a time, without the * notation.  (just 
my opinion)

DaveA



From gagsl-py2 at yahoo.com.ar  Thu Aug  6 01:19:24 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 02:19:24 -0300
Subject: Two Dimensional Array + ctypes
References: <79d2b3e3-b049-4d70-a56b-6e7f3ea2fa86@e27g2000yqm.googlegroups.com>
Message-ID: 

En Wed, 05 Aug 2009 20:12:09 -0300, Sparky  escribi?:

> Hello! I am trying to call this method:
>
> long _stdcall AIBurst(long *idnum, [...]
> 			 long timeout,
> 			 float (*voltages)[4],
> 			 long *stateIOout,
> 			 long *overVoltage,
> 			 long transferMode);
>
> I am having some problems with that  float (*voltages)[4].

>         pointerArray = (ctypes.c_void_p * 4)
>         voltages = pointerArray(ctypes.cast(ctypes.pointer
> ((ctypes.c_long * 4096)()), ctypes.c_void_p), ctypes.cast
> (ctypes.pointer((ctypes.c_long * 4096)()), ctypes.c_void_p),
> ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)()),
> ctypes.c_void_p), ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)

Why c_long and not c_float?
Anyway, this way looks much more clear to me (and doesn't require a cast):

arr4096_type = ctypes.c_float * 4096
voltages_type = arr4096_type * 4
voltages = voltages_type()

> The program runs but the values that come back in the array are not
> right.

Thay might be due to the long/float confusion.

-- 
Gabriel Genellina



From davea at ieee.org  Thu Aug  6 01:25:48 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 01:25:48 -0400
Subject: Web page data and urllib2.urlopen
In-Reply-To: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
Message-ID: <4A7A695C.4010403@ieee.org>

Massi wrote:
> Hi everyone, I'm using the urllib2 library to get the html source code
> of web pages. In general it works great, but I'm having to do with a
> financial web site which does not provide the souce code I expect. As
> a matter of fact if you try:
>
> import urllib2
> res = urllib2.urlopen("http://www.marketwatch.com/story/mondays-
> biggest-gaining-and-declining-stocks-2009-07-27")
> page = res.read()
> print page
>
> you will see that the printed code is very different from the one
> given, for example, by mozilla. Since I have really little knowledge
> in html I can't even understand if this is a python or html problem.
> Can anyone give me some help?
> Thanks in advance.
>
>   
I don't think this is a Python issue, but a "raw read" versus an 
interactive interpretation of a page.  The browser does lots more than a 
single roundtrip defined by urlopen/read.

I also would love to see some explanation of what happens here, or a 
pointer to a reference that would help me understand it.

I took the output of the read(), and formatted it, roughly, as html.  I 
expected to find a refresh, which is the simplest way that one page can 
cause a very different one to be loaded.
      

If Mozilla had seen a page with this line in an appropriate place, it'd 
immediately begin loading the other page, at "someotherurl"  But there's 
no such line.

Next, I looked for javascript.  The Mozilla page contains lots of 
javascript, but there's none in the raw page.  So I can't explain 
Mozilla's differences that way.

I did notice the link to /m/Content/mobile2.css, but I don' t know any 
way a CSS file could cause the content to change, just the display.

All I can guess is that it has something to do with "browser type" or 
cookies.  And that would make lots of sense if this was a cgi page.  But 
the URL doesn't look like that, as it doesn't end in pl, py, asp, or any 
of another dozen special suffixes.

Any hints, anybody???

DaveA



From MatzeGuentert at gmx.de  Thu Aug  6 01:26:31 2009
From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=)
Date: Thu, 06 Aug 2009 07:26:31 +0200
Subject: M2Crypto: How to generate subjectKeyIdentifier /
	authorityKeyIdentifier
In-Reply-To: 
References: 
	
Message-ID: <1249536391.3348.35.camel@celsius>

> M2Crypto has a couple of bugs open related that, with potential
> workarounds that I haven't yet deemed polished enough to checkin, but
> which might help you out:
> 
> https://bugzilla.osafoundation.org/show_bug.cgi?id=7530
> https://bugzilla.osafoundation.org/show_bug.cgi?id=12151

Thanks, that helped me a lot. Generating the 'subjectKeyIdentifier' now
works for me using the following procedure:

----------------------------------------------------------
import hashlib 

def get_public_key_fingerprint(self):
	h = hashlib.new('sha1')
    	h.update(self.keypair.as_der())
    	client_serial = h.hexdigest().upper()
    	client_serial_hex = ''
    	
    	for byte in xrange(20):
    	 client_serial_hex += client_serial[byte*2] + client_serial[byte*2
+1]
    		if byte < 19:
    			client_serial_hex += ':'
    
        return client_serial_hex 

[...]
cert_extension_4 = X509.new_extension("subjectKeyIdentifier",
keys_ca.get_public_key_fingerprint()) 
----------------------------------------------------------

However I don't understand the way the hash gets build. Comparing the
output from a given keypair and certificate build via OpenVPNs easy-rsa
scripts shows different subjectKeyIdentifiers. As stated out by rfc5280
there is no right or wrong way in creating the unique hash, so this
should be fine. 

But setting the 'authorityKeyIdentifier' extension gives me some
headache here. The following code snippet produces a segmentation fault
on my python interpreter (version 2.6)  

----------------------------------------------------------
cert_extension = X509.new_extension("authorityKeyIdentifier",
keys_ca.get_public_key_fingerprint())

cert_extension_stack.push(cert_extension)
----------------------------------------------------------

Same on this:
----------------------------------------------------------
cert_extension = 

X509.new_extension("authorityKeyIdentifier",
"keyid:1C:88:E1:8E:F1:5F:9D:1C:2B:6C:41:D4:3D:BB:79:0D:33:4A:E3:9A,
DirName:/C=US/ST=CA/L=SanFrancisco/O=Fort-Funston/CN=Fort-Funston
CA/emailAddress=me at myhost.mydomain, serial:B1:82:B1:E4:23:78:F1:12")

cert_extension_stack.push(cert_extension)
----------------------------------------------------------

So the question is: Is there another workaround to set this extension?
How can I provide more information to get this fixed? Working with the
latest SVN version is no option for me at the moment. 

Thanks in advance,
Matthias 




From gagsl-py2 at yahoo.com.ar  Thu Aug  6 01:30:58 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 02:30:58 -0300
Subject: os.system in a service
References: 
Message-ID: 

En Wed, 05 Aug 2009 13:07:39 -0300, Lawrence Wong  
 escribi?:

> I wrote a program which runs a .bat file using os.system like:  
> 'os.system(pathToBatFile)' and everything was good.  Then I decided to  
> turn my program into a service as opposed to being run with the command  
> prompt showing.  When my program became a service, I noticed that the  
> os.system command to run my .bat file was no longer working.  By 'not  
> working' I mean no exception is thrown, but it was as if the line with  
> os.system(pathToBatFile) did not exist.  I was wondering why this is and  
> if there is a way to fix this or what an alternative to using os.system  
> to run my .bat file was?

Capture stdout and stderr and you'll probably see the error message:

some_command >logfile.txt 2>&1

-- 
Gabriel Genellina



From pfeldman at verizon.net  Thu Aug  6 01:42:26 2009
From: pfeldman at verizon.net (Dr. Phillip M. Feldman)
Date: Wed, 5 Aug 2009 22:42:26 -0700 (PDT)
Subject: How to comment on a Python PEP?
Message-ID: <24840417.post@talk.nabble.com>


Is there a mechanism for submitting comments on a Python PEP?
-- 
View this message in context: http://www.nabble.com/How-to-comment-on-a-Python-PEP--tp24840417p24840417.html
Sent from the Python - python-list mailing list archive at Nabble.com.



From mlm2winnet at gmail.com  Thu Aug  6 01:49:42 2009
From: mlm2winnet at gmail.com (Chris Harris)
Date: Wed, 5 Aug 2009 22:49:42 -0700 (PDT)
Subject: Hi everyone
Message-ID: <150d41dd-018a-48a0-8dda-43e7832d6434@r38g2000yqn.googlegroups.com>

I'm happy to be a part of this group, i'd liek to say hi and invite
everyone to join my group =D Have a great night i look forward to
being an active member of this group

http://groups.google.com/group/mlm-2-win


From gagsl-py2 at yahoo.com.ar  Thu Aug  6 01:50:01 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 02:50:01 -0300
Subject: Parsing Binary Structures; Is there a better way / What is your
	way?
References: 
Message-ID: 

En Wed, 05 Aug 2009 11:46:13 -0300, Martin P. Hellwig  
 escribi?:

> On several occasions I have needed (and build) a parser that reads a  
> binary piece of data with custom structure. For example (bogus one):
>
> BE
> +---------+---------+-------------+-------------+------+--------+
> | Version | Command | Instruction | Data Length | Data | Filler |
> +---------+---------+-------------+-------------+------+--------+
> Version: 6 bits
> Command: 4 bits
> Instruction: 5 bits
> Data Length: 5 bits
> Data: 0-31 bits
> Filler: filling 0 bits to make the packet dividable by 8

> - Using a string for binary representation takes at least 8 times more  
> memory for the packet than strictly necessary.

The size difference isn't so big; an integer takes 12 bytes and a string  
takes 24+len bytes. "Data" above would take 56 bytes max when stored as a  
string '0110001...' vs. 12 bytes when using a plain integer (sizes  
computed on Windows 32bits). Plus, doing bitwise operations in Python  
isn't a fast operation as it is in C, by example -- so your current  
implementation might be a quite good one (in pure Python, I mean).

-- 
Gabriel Genellina



From davea at ieee.org  Thu Aug  6 02:30:47 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 02:30:47 -0400
Subject: access read / write violation with ctypes
In-Reply-To: 
References: 
Message-ID: <4A7A7897.1030207@ieee.org>

DH wrote:
> 
>
> I'm using popen to capture dcraw stdout and want to pass it to
> magickwand. If I instead write the dcraw output to a file then read it
> with magickwand I get the same error. But if I comment out the dcraw
> protion and read the dcraw output file from the previous attempt,
> MagickWand opens the file fine and I can manipulate it to my hearts
> content. The basics:
>
> 
>   
Just a quick guess, based only on this paragraph.  But I'd guess the 
dcraw output file is buffered, and is not fully written when you're 
trying to read it back.

You could do some checking by comparing sizes, when you get it from the 
pipe, and when you see it finally written in the directory.

DaveA


From hendrik at microcorp.co.za  Thu Aug  6 02:43:58 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Thu, 6 Aug 2009 08:43:58 +0200
Subject: Datetime with float seconds
In-Reply-To: 
References: 
Message-ID: <200908060843.58925.hendrik@microcorp.co.za>

On Wednesday 05 August 2009 14:50:04 kpal wrote:
> Hello Everybody,
>
> The standard datetime has 1 microsecond granularity. My application
> needs finer time resolution, preferably float seconds. Is there an
> alternative to the out-of-the-box datetime? Timezone support is not
> essential.

I am curious as to what would require less than microsecond
timing - about the only thing I can think of would be something
involving measuring the speed of light, where nanoseconds
or better would be nice.

- Hendrik



From davea at ieee.org  Thu Aug  6 02:45:01 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 02:45:01 -0400
Subject: Parsing Binary Structures;	Is there a better way / What is
	your way?
In-Reply-To: <7xr5vqw0v9.fsf@ruckus.brouhaha.com>
References: 	<7x3a86gmfe.fsf@ruckus.brouhaha.com>	
	<7xr5vqw0v9.fsf@ruckus.brouhaha.com>
Message-ID: <4A7A7BED.4030105@ieee.org>

Paul Rubin wrote:
> "Martin P. Hellwig"  writes:
>   
>> Is there an advantage using shifts and masks over my kitchen type solution?
>>     
>
> Weren't you complaining about the 8-to-1 expansion from turning each bit
> to an ascii char?
>
>   
One warning to Martin:

If you want your code portable across systems, watch out for 
big-endian/little-endian  issues, as well as alignment ones.  Shift & 
mask code tends to be highly specific to a particular endian-ness, 
especially if trying to get multiple bits that cross a byte or word 
boundary.

Over the years, I know I've seen at least three endian versions for the 
same 32bit word.  Something like abcd, dcba, and cdab.

One advantage of converting first to bitstrings, is that there's just 
the two places to fix, for portability, the conversion from byte array 
to bitstring, and the conversion back.

DaveA



From deets at nospam.web.de  Thu Aug  6 02:59:13 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Thu, 06 Aug 2009 08:59:13 +0200
Subject: os.system in a service
In-Reply-To: 
References: 
	
Message-ID: <7dvda1F2c4s7kU1@mid.uni-berlin.de>

Gabriel Genellina schrieb:
> En Wed, 05 Aug 2009 13:07:39 -0300, Lawrence Wong 
>  escribi?:
> 
>> I wrote a program which runs a .bat file using os.system like: 
>> 'os.system(pathToBatFile)' and everything was good.  Then I decided to 
>> turn my program into a service as opposed to being run with the 
>> command prompt showing.  When my program became a service, I noticed 
>> that the os.system command to run my .bat file was no longer working.  
>> By 'not working' I mean no exception is thrown, but it was as if the 
>> line with os.system(pathToBatFile) did not exist.  I was wondering why 
>> this is and if there is a way to fix this or what an alternative to 
>> using os.system to run my .bat file was?
> 
> Capture stdout and stderr and you'll probably see the error message:
> 
> some_command >logfile.txt 2>&1

Which isn't possible as a service.

The OP might consider using suprocess istead of os.system, and establish 
pipes to read the output of the command into a file he can analyze.

Diez


From hendrik at microcorp.co.za  Thu Aug  6 03:39:33 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Thu, 6 Aug 2009 09:39:33 +0200
Subject: Parsing Binary Structures;
	Is there a better way / What is your way?
In-Reply-To: 
References: 
Message-ID: <200908060939.33365.hendrik@microcorp.co.za>

On Wednesday 05 August 2009 16:46:13 Martin P. Hellwig wrote:
> Hi List,
>
> On several occasions I have needed (and build) a parser that reads a
> binary piece of data with custom structure. For example (bogus one):
>
> BE
> +---------+---------+-------------+-------------+------+--------+
>
> | Version | Command | Instruction | Data Length | Data | Filler |
>
> +---------+---------+-------------+-------------+------+--------+
> Version: 6 bits
> Command: 4 bits
> Instruction: 5 bits
> Data Length: 5 bits
> Data: 0-31 bits
> Filler: filling 0 bits to make the packet dividable by 8
>
> what I usually do is read the packet in binary mode, convert the output
> to a concatenated 'binary string'(i.e. '0101011000110') and then use
> slice indeces to get the right data portions.
> Depending on what I need to do with these portions I convert them to
> whatever is handy (usually an integer).

This bit banging stuff is a PITA, no matter what you do.
Python does not have bit fields like C.
And C bit fields are implementation dependent.
Write an extension?

Some time ago I asked a similar question, and
Castironpi came up with what was essentially an
indexed integer, with named bits.

It stores the bits natively, but I suspect that the
price paid is access time.

I enclose a module that you can adapt.
It talks about bytes but they are integers really.
It is different from what you are doing, as it
was aimed at reading and writing bits in 
a hardware context.

If you get your head around the concept,
then it may give you some ideas.  It should
be possible to extend the concept to
pass name,length tuples at construction time
instead of just a name with an implied length 
of one bit, and it may make sense to change
the underlying type from an integer to an 
array of one byte integers.

It is nice to be able to say:
val = bitname() 
to read, and 
bitname(1)
or
bitname(0)
to write.

I can also write:
outputbits[3] = 1
or
val = inputbits[5]

If you can successfully generalise it
to field names It should be very useful.

I cannot think of a way though, to not
have the "in" and "out" split, but you can
program your way around that - you do not
have to update "in place".

- Hendrik

-------------- next part --------------
A non-text attachment was scrubbed...
Name: bits.py
Type: application/x-python
Size: 4379 bytes
Desc: not available
URL: 

From kpalamartchouk at gmail.com  Thu Aug  6 03:46:58 2009
From: kpalamartchouk at gmail.com (kpal)
Date: Thu, 6 Aug 2009 00:46:58 -0700 (PDT)
Subject: Datetime with float seconds
References: 
	
Message-ID: <0819ae46-767f-4256-81d9-f265b7552cd8@h31g2000yqd.googlegroups.com>

On Aug 6, 7:43?am, Hendrik van Rooyen  wrote:

> I am curious as to what would require less than microsecond
> timing - about the only thing I can think of would be something
> involving measuring the speed of light, where nanoseconds
> or better would be nice.

You are right :-) I am trying to write a scientific software that does
some satellite geodesy computations (involving the speed of light),
and I would prefer to keep all the times float, while retaining the
time and time interval arithmetics and format transformation
capabilities of datetime. The system time granularity, that is of
cause limited, is not a problem at all, as the data are to be
initialized by constructing instances from external data.

Thanks


From hendrik at microcorp.co.za  Thu Aug  6 03:58:30 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Thu, 6 Aug 2009 09:58:30 +0200
Subject: Parsing Binary Structures;
	Is there a better way / What is your way?
In-Reply-To: <7x3a86gmfe.fsf@ruckus.brouhaha.com>
References: 
	<7x3a86gmfe.fsf@ruckus.brouhaha.com>
Message-ID: <200908060958.30882.hendrik@microcorp.co.za>

On Wednesday 05 August 2009 20:12:05 Paul Rubin wrote:
> "Martin P. Hellwig"  writes:
> > what I usually do is read the packet in binary mode, convert the
> > output to a concatenated 'binary string'(i.e. '0101011000110') and
>
> Something wrong with reading the data words as an integer and using
> old fashioned shifts and masks to get at the bit fields?

There is nothing wrong with that, and in the final analysis, it is what
is used - however, I can sympathize with the OP, as it is much nicer
to just call a named thing than to juggle a bunch of hard coded
shifts and masks.

I think the real point here is sort of meta programming - what
is needed is a way to describe and name the elements of the
structure so that useful python objects are created.

The code I posted for bits does that, and I use it all the
time - it is almost as good as being back in 8031 assembler
with direct named bit access.

- Hendrik


From contact at xavierho.com  Thu Aug  6 04:05:52 2009
From: contact at xavierho.com (Xavier Ho)
Date: Thu, 6 Aug 2009 18:05:52 +1000
Subject: merge two png pic
In-Reply-To: <69579cfc-9151-43df-a5ef-a6b05f1bd718@13g2000prl.googlegroups.com>
References: 
	
	
	<006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com>
	<4a77e249$0$2449$426a74cc@news.free.fr>
	<72d7aad1-1fb7-4b32-a87f-636505b0faa2@v15g2000prn.googlegroups.com>
	<4a793852$0$19598$426a74cc@news.free.fr>
	<69579cfc-9151-43df-a5ef-a6b05f1bd718@13g2000prl.googlegroups.com>
Message-ID: <2d56febf0908060105p1604f02u57128d23172b3d67@mail.gmail.com>

On Thu, Aug 6, 2009 at 12:17 PM, cocobear  wrote:

>
> I want to view image use Windows Pic View.
>
> If you run out of memory trying to combining those images into a 30k by 40k
pixels image, the Windows Pic View isn't going to be able to display it
either.

Regards,

Ching-Yun "Xavier" Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: contact at xavierho.com
Website: http://xavierho.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From hendrik at microcorp.co.za  Thu Aug  6 04:06:04 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Thu, 6 Aug 2009 10:06:04 +0200
Subject: Parsing Binary Structures;
	Is there a better way / What is your way?
In-Reply-To: 
References: 
	<7xr5vqw0v9.fsf@ruckus.brouhaha.com>
	
Message-ID: <200908061006.04437.hendrik@microcorp.co.za>

On Wednesday 05 August 2009 21:41:26 Martin P. Hellwig wrote:

> Yes you are (of course) right, my 'dream' solution would be something
> that accepts slice indeces on bit level. Your reasoning did reveal some
> flaws in my approach though ;-)

This is the first time I have been compared to the sandman...

:-)

- Hendrik



From martin at v.loewis.de  Thu Aug  6 04:24:08 2009
From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=)
Date: Thu, 06 Aug 2009 10:24:08 +0200
Subject: String to valid Python identifier
In-Reply-To: 
References: 
Message-ID: <4a7a9328$0$2355$9b622d9e@news.freenet.de>

> Is there any easy function in the stdlib to convert any random string in 
> a valid Python identifier .. possibly by replacing non-valid characters 
> with _ ?

I think this is fairly underspecified as a problem statement. A solution
that would meet your specification would be

def mkident(s):
    return "foo"

It returns a valid Python identifier for any random string.

If you now complain that this gives too many collisions, I propose

def mkident(s):
    return "foo%d" % (hash(s) & 0x7fffffff)

Regards,
Martin


From contact at xavierho.com  Thu Aug  6 04:26:22 2009
From: contact at xavierho.com (Xavier Ho)
Date: Thu, 6 Aug 2009 18:26:22 +1000
Subject: Subclassing Python's dict
In-Reply-To: 
References: 
	<2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com>
	
	
Message-ID: <2d56febf0908060126i323d499fla4b7a22c934c5e7@mail.gmail.com>

On Thu, Aug 6, 2009 at 1:19 PM, alex23  wrote:

> Xavier Ho wrote:
> > You should subclass collections.UserDict, and not the default dict class.
> > Refer to the collections module.
>
> Xavier, why do you think that is the correct approach?


I'll be honest first and say that I do not completely understand how dict is
implemented in the underlying C structure. But as Bruno had already
mentioned, dict has a slightly different behaviour then we'd expect. For
example, the __getitem__() function isn't actually used by the interpreter
(which, you know, *can* be a problem.)

http://www.python.org/download/releases/2.2.3/descrintro/#subclassing
(I don't know if 2.6.2 changed anything since 2.2.3, but there are some
references you can look at, and sample code.)

To answer your question, it's really not "the correct approach", but I think
(meaning: untested) UserDict doesn't have the same implementation, which
might free up some restrictions Sergey encountered.

The docs say
> "The need for this class has been largely supplanted by the ability to
> subclass directly from dict (a feature that became available starting
> with Python version 2.2)."


I didn't realise they took UserDict out in later versions (2.6, for
example), and put it back in Python 3.0. Does anyone know why?

So, I do not actually know.

> If you mean that Sergey should subclass _in this instance_ could you
> please explain why? (Sorry if you already have, I never saw your
> original post...)
>

It was really more or less an educated guess. He didn't tell us what he is
trying to achieve, so _in this instance_ I can't give more advice than
saying "well, if this doesn't work, here are you other options that I know
of/just found. Try these and let us know if you got it to work." *winks*

-

Sometimes I do answer a little too quickly, I apologise for that.

- Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From iainking at gmail.com  Thu Aug  6 04:28:29 2009
From: iainking at gmail.com (Iain King)
Date: Thu, 6 Aug 2009 01:28:29 -0700 (PDT)
Subject: remove last 76 letters from string
References: 
	
Message-ID: 

>      print >>nucleotides, seq[-76]

> ? ? ?last_part = line.rstrip()[-76 : ]

You all mean:   seq[:-76]   , right? (assuming you've already stripped
any junk off the end of the string)

Iain


From gagsl-py2 at yahoo.com.ar  Thu Aug  6 04:35:57 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 05:35:57 -0300
Subject: os.system in a service
References: 
	
	<7dvda1F2c4s7kU1@mid.uni-berlin.de>
Message-ID: 

En Thu, 06 Aug 2009 03:59:13 -0300, Diez B. Roggisch   
escribi?:
> Gabriel Genellina schrieb:
>> En Wed, 05 Aug 2009 13:07:39 -0300, Lawrence Wong  
>>  escribi?:

>>> I wrote a program which runs a .bat file using os.system like:  
>>> 'os.system(pathToBatFile)' and everything was good.  Then I decided to  
>>> turn my program into a service as opposed to being run with the  
>>> command prompt showing.  When my program became a service, I noticed  
>>> that the os.system command to run my .bat file was no longer working.  
>>> [...]

>>  Capture stdout and stderr and you'll probably see the error message:
>>  some_command >logfile.txt 2>&1
>
> Which isn't possible as a service.

Why you say so? One should avoid using mapped drive letters and network  
shares -- that probably aren't defined for the account under which the  
service runs. And always use absolute paths. And ensure the account has  
write permissions for the output file... But other than that, os.system  
should work fine. Do I miss something?

> The OP might consider using suprocess istead of os.system, and establish  
> pipes to read the output of the command into a file he can analyze.

That's a good idea, although overkill for simple cases I'd say.

-- 
Gabriel Genellina



From martin at v.loewis.de  Thu Aug  6 04:42:33 2009
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Thu, 06 Aug 2009 10:42:33 +0200
Subject: How to comment on a Python PEP?
In-Reply-To: 
References: 
Message-ID: <4a7a9779$0$2384$9b622d9e@news.freenet.de>

> Is there a mechanism for submitting comments on a Python PEP?

You post to python-dev or comp.lang.python, and you CC the author.

Regards,
Martin


From dr.scottgriffiths at gmail.com  Thu Aug  6 04:44:19 2009
From: dr.scottgriffiths at gmail.com (sgriffiths)
Date: Thu, 6 Aug 2009 01:44:19 -0700 (PDT)
Subject: Parsing Binary Structures; Is there a better way / What is your 
	way?
References: 
Message-ID: 

On Aug 5, 3:46?pm, "Martin P. Hellwig" 
wrote:
> Hi List,
>
> On several occasions I have needed (and build) a parser that reads a
> binary piece of data with custom structure. For example (bogus one):
>
> BE
> +---------+---------+-------------+-------------+------+--------+
> | Version | Command | Instruction | Data Length | Data | Filler |
> +---------+---------+-------------+-------------+------+--------+
> Version: 6 bits
> Command: 4 bits
> Instruction: 5 bits
> Data Length: 5 bits
> Data: 0-31 bits
> Filler: filling 0 bits to make the packet dividable by 8
>
> what I usually do is read the packet in binary mode, convert the output
> to a concatenated 'binary string'(i.e. '0101011000110') and then use
> slice indeces to get the right data portions.
> Depending on what I need to do with these portions I convert them to
> whatever is handy (usually an integer).
>
> This works out fine for me. Most of the time I also put the ASCII art
> diagram of this 'protocol' as a comment in the code, making it more
> readable/understandable.
>
> Though there are a couple of things that bothers me with my approach:
> - This seems such a general problem that I think that there must be
> already a general pythonic solution.
> - Using a string for binary representation takes at least 8 times more
> memory for the packet than strictly necessary.
> - Seems to need a lot of prep work before doing the actual parsing.
>
> Any suggestion is greatly appreciated.
>
> --
> MPHhttp://blog.dcuktec.com
> 'If consumed, best digested with added seasoning to own preference.'

Take a look at the bitstring module (in pypi or google code). It's
designed to help make this sort of thing easy and it's more fully
featured than BitVector or BitSet. Internally the data is stored as a
byte array, so memory isn't wasted. It will also do all the dirty work
of bit masking and shifting so that you can concentrate on the real
problems. For example:

>>> s = BitString('0x1232432312')  # just to give us some data to play with
>>> ver, comm, instr, bitlen = s.read('uint6, bin4, bin5, uint5')
>>> data = s.readbits(bitlen)

Different interpretations of the binary data are given using Python
properties (e.g. s.hex, s.oct, s.uint, etc.) and it supports bit-wise
slicing, modification, finding, replacing and more. It is also still
in active development (full disclosure: I'm the author :-)).



From contact at xavierho.com  Thu Aug  6 04:44:45 2009
From: contact at xavierho.com (Xavier Ho)
Date: Thu, 6 Aug 2009 18:44:45 +1000
Subject: remove last 76 letters from string
In-Reply-To: 
References: 
	
	
Message-ID: <2d56febf0908060144g4201d152mbf981c9273d5915f@mail.gmail.com>

On Thu, Aug 6, 2009 at 6:28 PM, Iain King  wrote:

> >      print >>nucleotides, seq[-76]
>
> >      last_part = line.rstrip()[-76 : ]
>
> You all mean:   seq[:-76]   , right? (assuming you've already stripped
> any junk off the end of the string)
>

I think so, probably both of them typo'd. (What are the probabilities of
that?)

It looks to me like you have two lines per DNA sequence. What you could do
instead, is to alternate the line reading with a with statement, as
suggested by Jan. Although I don't know why he's nesting two of them.
(explanation would be neat.)

Here's my version of approach, given the sample data the OP posted:

with open('NodeList.txt', 'r') as file:
    for line in file.readlines():
        line = line.rstrip()
        if line[0] == '>':
            # Do for New DNA Sequence
            # ...
        else:
            line = line[:-76]
            # ...

Should do what you need.

Best regards,

Ching-Yun "Xavier" Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: contact at xavierho.com
Website: http://xavierho.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From sanu1267 at gmail.com  Thu Aug  6 05:25:58 2009
From: sanu1267 at gmail.com (sanju ps)
Date: Thu, 6 Aug 2009 14:55:58 +0530
Subject: handling kill signal
Message-ID: <2b76be80908060225n674cbea5x6511d768c2828be6@mail.gmail.com>

I want to handle a kill signal..In my program i wrote like this

def handler(signum, frame):
    print "Signal",signum
    delete_temp_file()
    exit(1)
signal.signal(signal.SIGTERM, handler)

And when i tried pkill processid .program is exited but not deleting the
temp file
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From thangappan143 at gmail.com  Thu Aug  6 06:30:15 2009
From: thangappan143 at gmail.com (Thangappan.M)
Date: Thu, 6 Aug 2009 16:00:15 +0530
Subject: Problem in installing PyGreSQL
In-Reply-To: 
References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com>
	<7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net>
	<20090804084856.b825967a.darcy@druid.net>
	
	<20090804095547.a5274e22.darcy@druid.net> 
Message-ID: <7aa29e790908060330x67d900a9rfb4677eaf0eddeb@mail.gmail.com>

I have downloaded the  psycopg2 tar file from the following link.
http://initd.org/tracker/psycopg

I have done the following things.
         * Extracting the files from the tar file
         * tried to execute python ./setup.py build

It gives the following error.

#python ./setup.py build

running build
running build_py
running build_ext
Traceback (most recent call last):
  File "./setup.py", line 410, in ?
    ext_modules=ext)
  File "distutils/core.py", line 149, in setup
  File "distutils/dist.py", line 946, in run_commands
  File "distutils/dist.py", line 966, in run_command
  File "distutils/command/build.py", line 112, in run
  File "/usr/lib/python2.4/cmd.py", line 333, in run_command
    del help[cmd]
  File "distutils/dist.py", line 965, in run_command
  File "/usr/lib/python2.4/cmd.py", line 117, in ensure_finalized
    pass
  File "./setup.py", line 219, in finalize_options
    except (Warning, w):
NameError: global name 'w' is not defined

What would be the solution?
Otherwise can you tell how to install DB-API in debian machine.

On Wed, Aug 5, 2009 at 10:43 AM, Dennis Lee Bieber wrote:

> On Tue, 4 Aug 2009 09:55:47 -0400, "D'Arcy J.M. Cain" 
> declaimed the following in gmane.comp.python.general:
>
> >
> > By the way, you don't have to be super user to install PyGreSQL.  You
> > just need SU if you want to install it system wide.  PyGreSQL doesn't
> > require any special privileges to run.
> >
>         Potentially silly question:
>
>        While the DB-API module may be installable in a user mode... Do we
> know if the original querant even has PostgreSQL running and accessible?
>
> The statement
>
> OP> I want to access the database related stuffs in python.So I found
> the
> OP> PyGreSQL module in net.
>
> doesn't leave me with any confidence that they realize this is just an
> access module for one specific server -- and that they still need a
> server to which they can connect.
>
>        If they don't have a PostgreSQL server, it may be better just to
> direct them to SQLite3...
> --
>        Wulfraed        Dennis Lee Bieber               KD6MOG
>        wlfraed at ix.netcom.com           wulfraed at bestiaria.com
>                HTTP://wlfraed.home.netcom.com/
>        (Bestiaria Support Staff:               web-asst at bestiaria.com)
>                HTTP://www.bestiaria.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Regards,
Thangappan.M
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From python at mrabarnett.plus.com  Thu Aug  6 06:34:24 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 11:34:24 +0100
Subject: remove last 76 letters from string
In-Reply-To: 
References: 	
	
Message-ID: <4A7AB1B0.7090606@mrabarnett.plus.com>

Iain King wrote:
>>      print >>nucleotides, seq[-76]
> 
>>      last_part = line.rstrip()[-76 : ]
> 
> You all mean:   seq[:-76]   , right? (assuming you've already stripped
> any junk off the end of the string)
> 
The OP said "cut out the last 76 letters (nucleotides) from each
individual sequence and send them to a new txt file with a similar 
format.", ie extract the last 76 letters (in the same format) to a file.


From deets at nospam.web.de  Thu Aug  6 06:38:39 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Thu, 06 Aug 2009 12:38:39 +0200
Subject: Cython + setuptools not working with .pyx,only with .c-files
Message-ID: <7dvq5fF2e21b7U1@mid.uni-berlin.de>

Hi,


I'm trying to build a Cython-extension as Egg.

However, this doesn't work - I can either use distutils to build the
extension, creating a myextension.c-file on the way.

If that's there, I can use setuptools to build the egg.

But when I remove the .c-file, the .pyx-file isn't used to re-generate it.

This is my setup.py:

----
import os
import glob
from setuptools import setup, Extension
#from distutils.core import setup
#from distutils.extension import Extension

from Cython.Distutils import build_ext


objs = [...] # a static lib I want to wrap

setup(
    name='MyExtension',
    version="0.1",
    description='',
    author='Diez B. Roggisch',
    author_email='...',
    cmdclass = {'build_ext': build_ext},
    ext_modules = [Extension("myextension", ["myextension.pyx"],
                             libraries=["crypto"],
                             extra_objects = objs)],

-----


I can of course check in the myextension.c-file , and then when actually
working on the extension create it new by uncommenting the above lines.

But I guess that's not really the way things should work...

Diez


From pavlovevidence at gmail.com  Thu Aug  6 06:38:53 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Thu, 6 Aug 2009 03:38:53 -0700 (PDT)
Subject: Subclassing Python's dict
References:  
	<4a7999b1$0$306$426a74cc@news.free.fr>
Message-ID: <2c161a54-fade-4753-aa3f-3fee67632056@l5g2000pra.googlegroups.com>

On Aug 5, 7:39?am, Bruno Desthuilliers  wrote:
> Sergey Simonenko a ?crit :
>
> > Hi,
>
> > I subclass builtin 'dict' in my application and experience some problems
> > with it.
>
> > The whole issue is that I should redefine 'setdefault' and 'update'
> > methods after redefining '__setitem__' or/and '__delitem__',
> > otherwise 'update' and 'setdefault' ignore redefined '__setitem__' and
> > use builtin dict's one so dict looks kinda like a black box.
>
> > Another guy have reported me that he experiences similar problems with
> > subclassing builtin 'list'.
>
> I indeed notice this behaviour here (Python 2.6.2). I'm afraid it has to
> do with some optimization tricks (dict being the very fundamental data
> structure in Python, it has to be higly optimized).

You can ultimately blame it on optimization in this case, but in
general there isn't any way (in Python) to require that __setitem__ be
the common point for all modifications.

In fact this is an example of a general condition of OOP.  A "high-
level" method may or may not call a "low-level" method to do its dirty
work, and there is no way to know this simply from the class's
interface.  You need to have knowledge of the implementation to know
whether you need to override "high-level" or "low-level" methods.  In
general you can't safely subclass based on the interface alone; you
have to know what you're subclassing.

(As an aside: this intuitively is the reason why I never cared much
for some of the arguments against inheritance.  Many arguments against
inheritance go like this: "Inheritance is bad because X can happen if
you're not careful".  Doesn't mean anything to me because you have be
careful anyway.)

Because of the care required when subclassing, I tend to use
inheritance only when the intended base class is A. also under my
control, or B. specifically designed to be subclassed.  Examples of B
in the standard Python library are Queue and Thread.  list and dict
are allowed to be subclassed but aren't specifically designed for it,
so I tend not to subclass those.  (It is occasionally indispensible,
though.)


Carl Banks


From cournape at gmail.com  Thu Aug  6 06:57:11 2009
From: cournape at gmail.com (David Cournapeau)
Date: Thu, 6 Aug 2009 19:57:11 +0900
Subject: Using Python to automate builds
In-Reply-To: 
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com>
	
	
Message-ID: <5b8d13220908060357rb2fa7bp519809ce73455c28@mail.gmail.com>

On Thu, Aug 6, 2009 at 12:39 AM, Kosta wrote:

>
> Setenv.bat sets up the path and other environment variables build.exe
> needs to compile and link (and even binplace) its utilities. ?So
> building itself is not the issue. ?The problem is that if I call
> setenv.bat from Python and then build.exe, but the modifications to
> the path (and other environment settings) are not seen by Python, so
> the attempt to build without a specified path fails.

It sounds like you do not propagate the environment when calling
setenv.bat from python. There is an option to do so in
subprocess.Popen init method, or you can define your own environment
if you do not want to propagate the whole environment (but this is
often difficult to avoid for build environment in my experience,
expecially if you don't have access to the sources of the whole system
to check which variables are necessary).

David


From lawrencew00 at hotmail.com  Thu Aug  6 06:58:03 2009
From: lawrencew00 at hotmail.com (Lawrence Wong)
Date: Thu, 6 Aug 2009 10:58:03 +0000
Subject: os.system in a service
In-Reply-To: 
References: 
	
	<7dvda1F2c4s7kU1@mid.uni-berlin.de> 
	
Message-ID: 


I actually found the solution.  I was trying to copy a file from another computer to the current one.  My 'access was denied'.  So I had to go to my service at Admin Tools --> Services and 'Log on as' the Administrator.  Was ok after that.  Thanks for your responses everyone.  

> To: python-list at python.org
> From: gagsl-py2 at yahoo.com.ar
> Subject: Re: os.system in a service
> Date: Thu, 6 Aug 2009 05:35:57 -0300
> 
> En Thu, 06 Aug 2009 03:59:13 -0300, Diez B. Roggisch   
> escribi?:
> > Gabriel Genellina schrieb:
> >> En Wed, 05 Aug 2009 13:07:39 -0300, Lawrence Wong  
> >>  escribi?:
> 
> >>> I wrote a program which runs a .bat file using os.system like:  
> >>> 'os.system(pathToBatFile)' and everything was good.  Then I decided to  
> >>> turn my program into a service as opposed to being run with the  
> >>> command prompt showing.  When my program became a service, I noticed  
> >>> that the os.system command to run my .bat file was no longer working.  
> >>> [...]
> 
> >>  Capture stdout and stderr and you'll probably see the error message:
> >>  some_command >logfile.txt 2>&1
> >
> > Which isn't possible as a service.
> 
> Why you say so? One should avoid using mapped drive letters and network  
> shares -- that probably aren't defined for the account under which the  
> service runs. And always use absolute paths. And ensure the account has  
> write permissions for the output file... But other than that, os.system  
> should work fine. Do I miss something?
> 
> > The OP might consider using suprocess istead of os.system, and establish  
> > pipes to read the output of the command into a file he can analyze.
> 
> That's a good idea, although overkill for simple cases I'd say.
> 
> -- 
> Gabriel Genellina
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

_________________________________________________________________
More storage. Better anti-spam and antivirus protection. Hotmail makes it simple.
http://go.microsoft.com/?linkid=9671357
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From cournape at gmail.com  Thu Aug  6 07:00:09 2009
From: cournape at gmail.com (David Cournapeau)
Date: Thu, 6 Aug 2009 20:00:09 +0900
Subject: Cython + setuptools not working with .pyx,only with .c-files
In-Reply-To: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
References: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
Message-ID: <5b8d13220908060400m4d096726i6d929fb0e32a0327@mail.gmail.com>

On Thu, Aug 6, 2009 at 7:38 PM, Diez B. Roggisch wrote:
> Hi,
>
>
> I'm trying to build a Cython-extension as Egg.
>
> However, this doesn't work - I can either use distutils to build the
> extension, creating a myextension.c-file on the way.
>
> If that's there, I can use setuptools to build the egg.
>
> But when I remove the .c-file, the .pyx-file isn't used to re-generate it.
>
> This is my setup.py:
>
> ----
> import os
> import glob
> from setuptools import setup, Extension
> #from distutils.core import setup
> #from distutils.extension import Extension
>
> from Cython.Distutils import build_ext

What happens if you import setuptools *after* Cython.distutils ? My
guess - I could be wrong - is that both Cython.distutils and
setuptools monkey-patch distutils, and that setuptools does not "see"
Cython.Distutils. It could also be an incompatibility between
Cython.Distutils and setuptools (the design of distutils forces you to
take into account the details of things modified by every distutils
extension).

cheers,

David


From doron.tal.list at gmail.com  Thu Aug  6 08:00:45 2009
From: doron.tal.list at gmail.com (Doron Tal)
Date: Thu, 6 Aug 2009 15:00:45 +0300
Subject: inspect.stack() performance
Message-ID: <2a8674c60908060500k1c77b556la70d06d5feaaef0e@mail.gmail.com>

I use inspect.stack() to extract some info, such as file name, function name
and line number, for the sake of logging (home brew logger).
I tested to see how much time it takes to execute the command:

Python 2.4.3 (#1, Jan 21 2009, 01:11:33)
[GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> t = timeit.Timer('inspect.stack()', 'import inspect')
>>> t.repeat(3,1000)
[0.28500604629516602, 0.28315305709838867, 0.29169297218322754]
>>>

About 280uSec per call.

If I log 1000 times per seconds than I get to spend 28% of the process time
on inspect.stack()
Is there a better/quicker way of retrieving the same info?

Thanks,
--doron
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From Michalek.Jan at uhul.cz  Thu Aug  6 08:37:55 2009
From: Michalek.Jan at uhul.cz (=?iso-8859-2?Q?MICH=C1LEK_Jan_Mgr=2E?=)
Date: Thu, 6 Aug 2009 14:37:55 +0200
Subject: one method of COM object needs a variant type variable
Message-ID: <913F77222E913C49A057FDD7BBDEAAA30192B846@br-dc.uhul.wan>

How i can use this type in win32.com? One method of com object (geomedia storage service) needs this variable for storage geometry of geometry object (this variable will be writen into blob in DB). Is possible make this variable in py??
Thanks Jelen/Stack
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From marcusw at cox.net  Thu Aug  6 09:24:33 2009
From: marcusw at cox.net (Marcus Wanner)
Date: Thu, 06 Aug 2009 09:24:33 -0400
Subject: Overlap in python
In-Reply-To: <4c9f81a5-51b9-4487-9df9-d458b327d286@s15g2000yqs.googlegroups.com>
References: 	<4A78B19D.4020306@mrabarnett.plus.com>	
	<4c9f81a5-51b9-4487-9df9-d458b327d286@s15g2000yqs.googlegroups.com>
Message-ID: 

On 8/5/2009 10:56 AM, nn wrote:
> On Aug 5, 7:13 am, Marcus Wanner  wrote:
>> On 8/4/2009 6:09 PM, MRAB wrote:
>>
>>>  >>> parts = [(5, 9, "a"), (7, 10, "b"), (3, 6, "c"), (15, 20, "d"),
>>> (18, 23, "e")]
>>>  >>> parts.sort()
>>>  >>> parts
>>> [(3, 6, 'c'), (5, 9, 'a'), (7, 10, 'b'), (15, 20, 'd'), (18, 23, 'e')]
>>>  >>> # Merge overlapping intervals.
>>>  >>> pos = 1
>>>  >>> while pos < len(parts):
>>>         # Merge the pair in parts[pos - 1 : pos + 1] if they overlap.
>>>         p, q = parts[pos - 1 : pos + 1]
>>>         if p[1] >= q[0]:
>>>                 parts[pos - 1 : pos + 1] = [(p[0], max(p[1], q[1]), p[2]
>>> + "." + q[2])]
>>>         else:
>>>                 # They don't overlap, so try the next pair.
>>>                 pos += 1
>>>  >>> parts
>>> [(3, 10, 'c.a.b'), (15, 23, 'd.e')]
>> That's the best solution I've seen so far. It even has input/output
>> formatted as close as is reasonably possible to the format specified.
>>
>> As we would say in googlecode, +1.
>>
>> Marcus
> 
> How does it compare to this one?
> 
> http://groups.google.com/group/comp.lang.python/browse_frm/thread/1a1d2ed9d05d11d0/56684b795fc527cc#56684b795fc527cc
That is a different problem, and the solution is more complex.
I am not going to try to judge which is better.

Marcus

-- 
print ''.join([chr(((ord(z)+(ord("I'M/THE"[3])+sum(
     [ord(x)for x in 'CRYPTOR'])))%(4*ord('8')+ord(
     ' ')))) for z in ''.join(([(('\xca\x10\x03\t'+
     '\x01\xff\xe6\xbe\x0c\r\x06\x12\x17\xee\xbe'+
     '\x10\x03\x06\x12\r\x0c\xdf\xbe\x12\x11\x13'+
     '\xe8')[13*2-y]) for y in range(int(6.5*4)+1)]
     ))])



From tjreedy at udel.edu  Thu Aug  6 09:55:04 2009
From: tjreedy at udel.edu (Terry Reedy)
Date: Thu, 06 Aug 2009 22:55:04 +0900
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
Message-ID: 

RayS wrote:
> At 08:35 PM 8/5/2009 -0700, r wrote:
>> """... Any real sense of community is undermined -- or
>> even destroyed -- to be replaced by virtual equivalents that strive,
>> unsuccessfully, to synthesize a sense of community."""
> 
> I've brought up the idea of the quasi-community doc that PHP uses to 
> good effect.

And what have you done about setting up such a project?

> http://www.php.net/manual/en/language.types.array.php is a prime example 
> where 2/3 of the "doc" is user-contributed comments and code.

I consider consider this to an unreadable mishmash. If you and others 
want something like that, do it.  And quite bitching about the work of 
those of us who have done something compact and readable. We are all 
volunteers here.

tjr



From iainking at gmail.com  Thu Aug  6 09:58:13 2009
From: iainking at gmail.com (Iain King)
Date: Thu, 6 Aug 2009 06:58:13 -0700 (PDT)
Subject: remove last 76 letters from string
References: 
	
	
	
Message-ID: <938fdab5-65c5-47a0-8386-95edc470da9e@a26g2000yqn.googlegroups.com>

On Aug 6, 11:34?am, MRAB  wrote:
> Iain King wrote:
> >> ? ? ?print >>nucleotides, seq[-76]
>
> >> ? ? ?last_part = line.rstrip()[-76 : ]
>
> > You all mean: ? seq[:-76] ? , right? (assuming you've already stripped
> > any junk off the end of the string)
>
> The OP said "cut out the last 76 letters (nucleotides) from each
> individual sequence and send them to a new txt file with a similar
> format.", ie extract the last 76 letters (in the same format) to a file.

So he did.  Excuse me while I go eat my other foot.


From tack at urandom.ca  Thu Aug  6 10:15:41 2009
From: tack at urandom.ca (Jason Tackaberry)
Date: Thu, 06 Aug 2009 10:15:41 -0400
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 
	<1249487636.7120.798.camel@arrakis>
	
Message-ID: <1249568141.10840.37.camel@arrakis>

On Thu, 2009-08-06 at 01:31 +0000, John Machin wrote:
> Faster by an enormous margin; attributing this to the cost of attribute lookup
> seems implausible.

Ok, fair point.  I don't think the time difference fully registered when
I composed that message.

Testing a global access (LOAD_GLOBAL) versus an attribute access on a
global object (LOAD_GLOBAL + LOAD_ATTR) shows that the latter is about
40% slower than the former.  So that certainly doesn't account for the
difference.


> Suggested further avenues of investigation:
> 
> (1) Try the timing again with "cp1252" and "utf8" and "utf_8"
> 
> (2) grep "utf-8" /Objects/unicodeobject.c

Very pedagogical of you. :)  Indeed, it looks like bigger player in the
performance difference is the fact that the code path for unicode(s,
enc) short-circuits the codec registry for common encodings (which
includes 'utf-8' specifically), whereas s.decode('utf-8') necessarily
consults the codec registry.

Cheers,
Jason.



From thorsten at thorstenkampe.de  Thu Aug  6 10:32:34 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Thu, 6 Aug 2009 16:32:34 +0200
Subject: unicode() vs. s.decode()
References: 
Message-ID: 

* Michael Str?der (Wed, 05 Aug 2009 16:43:09 +0200)
> These both expressions are equivalent but which is faster or should be
> used for any reason?
> 
> u = unicode(s,'utf-8')
> 
> u = s.decode('utf-8') # looks nicer

"decode" was added in Python 2.2 for the sake of symmetry to encode(). 
It's essentially the same as unicode() and I wouldn't be surprised if it 
is exactly the same. I don't think any measurable speed increase will be 
noticeable between those two.

Thorsten


From sbassi at clubdelarazon.org  Thu Aug  6 10:35:36 2009
From: sbassi at clubdelarazon.org (Sebastian Bassi)
Date: Thu, 6 Aug 2009 11:35:36 -0300
Subject: ANN: Python for Bioinformatics book
Message-ID: <9e2f512b0908060735w7d270238y773275d45c46a954@mail.gmail.com>

"Python for Bioinformatics"
ISBN 1584889292
Amazon: http://www.tinyurl.com/biopython
Publisher: http://www.crcpress.com/product/isbn/9781584889298

This book introduces programming concepts to life science researchers,
bioinformaticians, support staff, students, and everyone who is
interested in applying programming to solve biologically-related
problems. Python is the chosen programming language for this task
because it is both powerful and easy-to-use.

It begins with the basic aspects of the language (like data types and
control structures) up to essential skills on today's bioinformatics
tasks like building web applications, using relational database
management systems, XML and version control. There is a chapter
devoted to Biopython (www.biopython.org) since it can be used for most
of the tasks related to bioinformatics data processing.

There is a section with applications with source code, featuring
sequence manipulation, filtering vector contamination, calculating DNA
melting temperature, parsing a genbank file, inferring splicing sites,
and more.

There are questions at the end of every chapter and odd numbered
questiona are answered in an appendix making this text suitable for
classroom use.

This book can be used also as a reference material as it includes
Richard Gruet's Python Quick Reference, and the Python Style Guide.

DVD: The included DVD features a virtual machine with a special
edition of DNALinux, with all the programs and complementary files
required to run the scripts commented in the book. All scripts can be
tweaked to fit a particular configuration. By using a pre-configured
virtual machine the reader has access to the same development
environment than the author, so he can focus on learning Python. All
code is also available at the http://py3.us/## where ## is the code
number, for example: http://py3.us/57

I've been working on this book for more than two years testing the
examples under different setups and working to make the code
compatible for most versions of Python, Biopython and operating
systems. Where there is code that only works with a particular
dependency, this is clearly noted.

Finally, I want to highlight that non-bioinformaticians out there can
use this book as an introduction to bioinformatics by starting with
the included "Diving into the Gene Pool with BioPython" (by Zachary
Voase and published originally in Python Magazine).


-- 
Sebasti?n Bassi. Diplomado en Ciencia y Tecnolog?a.

Non standard disclaimer: READ CAREFULLY. By reading this email,
you agree, on behalf of your employer, to release me from all
obligations and waivers arising from any and all NON-NEGOTIATED
agreements, licenses, terms-of-service, shrinkwrap, clickwrap,
browsewrap, confidentiality, non-disclosure, non-compete and
acceptable use policies ("BOGUS AGREEMENTS") that I have
entered into with your employer, its partners, licensors, agents and
assigns, in perpetuity, without prejudice to my ongoing rights and
privileges. You further represent that you have the authority to release
me from any BOGUS AGREEMENTS on behalf of your employer.


From kee at kagi.com  Thu Aug  6 10:39:10 2009
From: kee at kagi.com (Kee Nethery)
Date: Thu, 6 Aug 2009 07:39:10 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
Message-ID: <701EC8AD-A151-46F9-A393-31B3960CE2FC@kagi.com>


On Aug 6, 2009, at 6:55 AM, Terry Reedy wrote:

> RayS wrote:
>> At 08:35 PM 8/5/2009 -0700, r wrote:
>>> """... Any real sense of community is undermined -- or
>>> even destroyed -- to be replaced by virtual equivalents that strive,
>>> unsuccessfully, to synthesize a sense of community."""
>> I've brought up the idea of the quasi-community doc that PHP uses  
>> to good effect.
>
> And what have you done about setting up such a project?
>
>> http://www.php.net/manual/en/language.types.array.php is a prime  
>> example where 2/3 of the "doc" is user-contributed comments and code.
>
> I consider consider this to an unreadable mishmash. If you and  
> others want something like that, do it.  And quite bitching about  
> the work of those of us who have done something compact and  
> readable. We are all volunteers here.

As I struggle through trying to figure out how to make python do  
simple stuff for me, I frequently generate samples. If some volunteer  
here would point me towards the documentation that would tell me how I  
can alter the existing Python docs to include sample code, I'd be more  
than happy to do so.

I would like to "do it". Please point me to the docs that tell me how  
to "do it" so that we people with newbie questions and a need for  
examples can get out of your way and "do it" ourselves.

Thanks,
Kee Nethery





From jakecjacobson at gmail.com  Thu Aug  6 10:50:07 2009
From: jakecjacobson at gmail.com (jakecjacobson)
Date: Thu, 6 Aug 2009 07:50:07 -0700 (PDT)
Subject: Help making this script better
Message-ID: <2f8e34ec-01aa-4ec4-9636-a8ec1f87c68c@o6g2000yqj.googlegroups.com>

Hi,

After much Google searching and trial & error, I was able to write a
Python script that posts XML files to a REST API using HTTPS and
passing PEM cert & key file.  It seems to be working but would like
some pointers on how to handle errors.  I am using Python 2.4, I don't
have the capability to upgrade even though I would like to.  I am very
new to Python so help will be greatly appreciated and I hope others
can use this script.

#!/usr/bin/python
#################################################################
# catalog_feeder.py
#################################################################
# This sciript will process a directory of XML files and push them to
the Enterprise Catalog.
#  You configure this script by using a configuration file that
describes the required variables.
#  The path to this file is either passed into the script as a command
line argument or hard coded
#  in the script.  The script will terminate with an error if it can't
process the XML file.
#################################################################

# IMPORT STATEMENTS
import httplib
import mimetypes
import os
import sys
import shutil
import time
from urllib import *
from time import strftime
from xml.dom import minidom

def main(c):
	start_time = time.time()
	# Set configuration parameters
	try:
		# Process the XML conf file ....
		xmldoc = minidom.parse(c)
		catalog_host = readConfFile(xmldoc, 'catalog_host')
		catalog_port = int(readConfFile(xmldoc, 'catalog_port'))
		catalog_path = readConfFile(xmldoc, 'catalog_path')
		collection_name = readConfFile(xmldoc, 'collection_name')
		cert_file = readConfFile(xmldoc, 'cert_file')
		key_file = readConfFile(xmldoc, 'key_file')
		log_file = readConfFile(xmldoc, 'log_file')
		input_dir = readConfFile(xmldoc, 'input_dir')
		archive_dir = readConfFile(xmldoc, 'archive_dir')
		hold_dir = readConfFile(xmldoc, 'hold_dir')
	except Exception, inst:
		# I had an error so report it and exit script
		print "Unexpected error opening %s: %s" % (c, inst)
		sys.exit(1)
	# Log Starting
	logOut = verifyLogging(log_file)
	if logOut:
		log(logOut, "Processing Started ...")
	# Get list of XML files to process
	if os.path.exists(input_dir):
		files = getFiles2Post(input_dir)
	else:
		if logOut:
			log(logOut, "WARNING!!! Couldn't find input directory: " +
input_dir)
			cleanup(logOut)
		else:
			print "Dir doen't exist: " + input_dir
			sys.exit(1)
	try:
		# Process each file to the catalog
		connection = httplib.HTTPSConnection(catalog_host, catalog_port,
key_file, cert_file)
		for file in files:
			log(logOut, "Processing " + file + " ...")
			try:
				response = post2Catalog(connection, catalog_path, os.path.join
(input_dir, file), collection_name)
				if response.status == 200:
					msg = "Succesfully posted " +  file + " to cataloge ..."
					print msg
					log(logOut, msg)
					# Move file to done directory
					shutil.move(os.path.join(input_dir, file), os.path.join
(archive_dir, file))
				else:
					msg = "Error posting " +  file + " to cataloge [" + response.read
() + "] ..."
					print msg
					log(logOut, response.read())
					# Move file to error dir
					shutil.move(os.path.join(input_dir, file), os.path.join(hold_dir,
file))
			except IOError, (errno):
				print "%s" % (errno)

	except httplib.HTTPException, (e):
		print "Unexpected error %s " % (e)

	run_time = time.time() - start_time
	print 'Run time: %f seconds' % run_time

	# Clean up
	connection.close()
	cleanup(logOut)

# Get an arry of files from the input_dir
def getFiles2Post(d):
	return (os.listdir(d))

# Read out the conf file and set the needed global variable
def readConfFile(xmldoc, tag):
	return (xmldoc.getElementsByTagName(tag)[0].firstChild.data)

# Write out the message to log file
def log(f, m):
	f.write(strftime("%Y-%m-%d %H:%M:%S") + " : " + m + '\n')

# Clean up and exit
def cleanup(logOut):
	if logOut:
		log(logOut, "Processing Ended ...\n")
		logOut.close()
	sys.exit(0)

# Verify if we can write to the log file and return a file handle if
we can
def verifyLogging(l):
	fh=''  # No logging default behavior
	if os.path.exists(os.path.dirname(l)):
		fh = open(l, 'a')
	return(fh)

# Print out the usage of this script
def printusage():
	print""
	print
"**************************************************************************************************"
	print " Must provide the path to the configuration file when calling
this script ..."
	print " Example: " + sys.argv[0] + " /path_2_configuration_file/
conf.xml"
	print
"**************************************************************************************************"
	print ""
	sys.exit(1)

#############################
# Posting XML file to the Catelog Service
#############################
def post2Catalog(connection, path, file, collection):
	head = {"Content-Type" : "application/x-www-form-urlencoded",
"Accept" : "text/plain"}
	parameters = urlencode({"collection" : collection, "entryxml" : open
(file,'r').read()})
	connection.request('POST', path, parameters, head)
	response = connection.getresponse()
	# To reuse the connection, I have to read the response.  I really
don't care about it so I do nothing with it.
	body = response.read()
	return response

# Main
if __name__ == "__main__":
	_pathname = os.path.dirname(sys.argv[0])
	total=len(sys.argv)
	if len(sys.argv) > 1:
		main(sys.argv[1])
	else:
		printusage()


From bearophileHUGS at lycos.com  Thu Aug  6 10:52:44 2009
From: bearophileHUGS at lycos.com (Bearophile)
Date: Thu, 6 Aug 2009 07:52:44 -0700 (PDT)
Subject: ANN: Python for Bioinformatics book
References: 
Message-ID: 

Sebastian Bassi:

> All code is also available at thehttp://py3.us/##where ## is the code number, for example:http://py3.us/57<

The book looks interesting, but that doesn't look like a good way to
show/offer the code. I suggest to also put it into a zip that can be
downloaded.

Bye,
bearophile


From josepharmbruster at gmail.com  Thu Aug  6 11:05:20 2009
From: josepharmbruster at gmail.com (joseph armbruster)
Date: Thu, 6 Aug 2009 08:05:20 -0700 (PDT)
Subject: FCC Amateur Radio database -> SQLite
Message-ID: <1b304bef-150f-405d-a66a-6ec2979a1f2c@a1g2000yqn.googlegroups.com>

Here is a quick way to get the amateur radio database from the FCC put
into sqlite.  If anyone has insight into a pure-python import, please
comment.

http://libjoe.blogspot.com/2009/08/loading-up-fcc-license-database.html

Joseph Armbruster
http://www.joevial.com


From kuchunwah01 at yahoo.com  Thu Aug  6 11:19:20 2009
From: kuchunwah01 at yahoo.com (John)
Date: Thu, 6 Aug 2009 08:19:20 -0700 (PDT)
Subject: convert non-delimited to delimited
Message-ID: <768586.94351.qm@web65602.mail.ac4.yahoo.com>

I am not really a CS person, but I have a task to import a non-delimited text to an access database.? After some research, I *think* the best way to do this is by first converting the non-delimited text to delimited text, and then import it to the database.? Is this the best way to approach this?? Or is there easier way?

Example:
---------------------------------------------------------------------------
Test , BTS
0800000532
05/MAY/1945 00:00
Female
858327
AB Pos
�

CMV Neg Req'd
IgA Deficient




Wr(a+)
S-


>> OCT/23/07 08:18:00 TRETHEWEYD >>>>>>>>>>>>>>>>> Please fax to:
>> OCT/22/07 09:37:00 [COMBINE] [Combine from person_id 924598 to person_id 858327]
[Following comments for to person_id 924598]
>> OCT/18/07 15:53:00 TRETHEWEYD 2007/10/18 15:52

-----------------------------------------------------------------------------------
Basically there are 2 portions to this.? The first portion consist of 7 lines (Full Name, Medical record number, birth date, gender, internal ID, blood group, phenotype).? The second portion list the different list of requirements, denote by  and .? In the sample shown above, the patient do not have information on phenotype, thus there is the � symbol.? 
?
I am really stump on where to go from here.? Any help would be appreciated it.? I have also include a text file which gives several more examples.
?
Thanks so much!


      __________________________________________________________________
Looking for the perfect gift? Give the gift of Flickr! 

http://www.flickr.com/gift/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: samplepatient.txt
Type: application/octet-stream
Size: 48996 bytes
Desc: not available
URL: 

From sbassi at clubdelarazon.org  Thu Aug  6 11:34:35 2009
From: sbassi at clubdelarazon.org (Sebastian Bassi)
Date: Thu, 6 Aug 2009 12:34:35 -0300
Subject: ANN: Python for Bioinformatics book
In-Reply-To: 
References: 
	
Message-ID: <9e2f512b0908060834g5ad2ce34vbc2df78d16a24f69@mail.gmail.com>

On Thu, Aug 6, 2009 at 11:52 AM, Bearophile wrote:
> The book looks interesting, but that doesn't look like a good way to
> show/offer the code. I suggest to also put it into a zip that can be
> downloaded.

Code is also in a directory in the DVD and also inside the virtual
machine. Anyway I think it wouldn't hurt to make a zip and put it
online, so i will do it. Thanks.
Best,
SB.


From rcdailey at gmail.com  Thu Aug  6 11:35:57 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 6 Aug 2009 08:35:57 -0700 (PDT)
Subject: Help with regex
Message-ID: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>

Hey guys,

I'm creating a python script that is going to try to search a text
file for any text that matches my regular expression. The thing it is
looking for is:

FILEVERSION #,#,#,#

The # symbol represents any number that can be any length 1 or
greater. Example:

FILEVERSION 1,45,10082,3

The regex should only match the exact above. So far here's what I have
come up with:

re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )

This works, but I was hoping for something a bit cleaner. I'm having
to create a special case portion of the regex for the last of the 4
numbers simply because it doesn't end with a comma like the first 3.
Is there a better, more compact, way to write this regex?


From mydevforums at gmail.com  Thu Aug  6 11:49:30 2009
From: mydevforums at gmail.com (IronyOfLife)
Date: Thu, 6 Aug 2009 08:49:30 -0700 (PDT)
Subject: Python configuration question when python scripts are executed 
	using Appweb as web server.
References: 
	
	
	
Message-ID: 

Hi Gabriel

On Aug 5, 4:18?pm, "Gabriel Genellina"  wrote:
> En Tue, 04 Aug 2009 10:15:24 -0300, IronyOfLife 
> escribi?:
>
> > On Aug 3, 8:42?pm, "Gabriel Genellina"  wrote:
> >> En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife  ?
> >> escribi?:
>
> >> > I have installed python 2.6.2 in windows xp professional machine. I
> >> > have set the following environment variables -- PYTHONPATH. It points
> >> > to following windows folders: python root folder, the lib folder and
> >> > lib-tk folder.
>
> >> Why? Did you read it somewhere? Usually there is no need to set the ?
> >> PYTHONPATH variable at all; remove it.
>
> > Setting PYTHONPATH environment variables is mentioned in Python docs.
>
> Could you provide a link please? Setting PYTHONPATH should not be

Here are couple of links that discusses setting PYTHONPATH environment
variable.
http://docs.python.org/using/windows.html
http://www.daimi.au.dk/~chili/PBI/pythonpath.html

> necesary, and in fact it's a very bad idea. Environment variables are
> global, but Python modules may depend on the Python version, architecture,
> install location... By example, you may install a 64 bits Python 3.1
> version *and* a 32 bits Python 2.5 version and they both can coexist
> peacefully - but an extension module compiled for the former cannot be
> used in the later version. You must build a separate library for each
> version, and install them in two separate directories. But since the
> PYTHONPATH variable is shared by all installations, which directory should
> contain?
> It's best not to use PYTHONPATH at all and rely on other alternatives
> (like .pth files, that are searched relative to the current Python
> executable, so different versions use different configuration files)

I understand your concerns regarding setting of PYTHONPATH while
multiple versions of Python are installed on the same machine. My fix
however does not use PYTHONPATH. The GNUTLS wrapper module for PYTHON
loads the GNUTLS dll's and it was not able to find them. Using FileMon
(win tool) I found out the paths that are scanned and I copied the
dlls to one of such paths. I still do not like this fix. This is a
temporary solution.

Can you explain maybe with some sample how to set .pth files? Maybe
this will resolve my issue.
>
> > I solved the issue temporarily by copying the gnutls related dlls to
> > the path searched by python.exe
>
> Glad to see you could finally fix it!
>
> --
> Gabriel Genellina

Thanks very much for your reply.


From wuwei23 at gmail.com  Thu Aug  6 11:52:51 2009
From: wuwei23 at gmail.com (alex23)
Date: Thu, 6 Aug 2009 08:52:51 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
Message-ID: <96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>

Kee Nethery wrote:
> As I struggle through trying to figure out how to make python do ?
> simple stuff for me, I frequently generate samples. If some volunteer ?
> here would point me towards the documentation that would tell me how I ?
> can alter the existing Python docs to include sample code, I'd be more ?
> than happy to do so.

No offence, but the last thing the official documentation needs is
example code written by people learning how to code. Suggest changes,
request clarifications, submit samples for review, sure, but direct
modification by users? I've seen the PHP docs; thanks but no thanks.

> I would like to "do it". Please point me to the docs that tell me how ?
> to "do it" so that we people with newbie questions and a need for ?
> examples can get out of your way and "do it" ourselves.

You start by reading this: http://docs.python.org/documenting/index.html
And this: http://www.python.org/dev/contributing/
And this: http://wiki.python.org/moin/WikiGuidelines

The first link, which directly answers your question, is clearly
listed on the doc contents page as "Documenting Python". I'm uncertain
how the docs could be made any _more_ helpful if people aren't
prepared to put effort into reading them. We're a long way away from
direct upload to the brain, unfortunately.

If you're learning the language, you should also consider using more
appropriate resources:
http://mail.python.org/mailman/listinfo/tutor
http://www.doughellmann.com/PyMOTW/
http://diveintopython.org/

The documentation cannot be all things to all people, and it most
certainly can't be a guide to general programming, which is what often
seems to be the issue with novice users. Python's a great language to
learn how to program in, sure, but I would hate to see that become the
focus of the docs.


From python at mrabarnett.plus.com  Thu Aug  6 12:02:44 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 17:02:44 +0100
Subject: Help with regex
In-Reply-To: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
Message-ID: <4A7AFEA4.4050800@mrabarnett.plus.com>

Robert Dailey wrote:
> Hey guys,
> 
> I'm creating a python script that is going to try to search a text
> file for any text that matches my regular expression. The thing it is
> looking for is:
> 
> FILEVERSION #,#,#,#
> 
> The # symbol represents any number that can be any length 1 or
> greater. Example:
> 
> FILEVERSION 1,45,10082,3
> 
> The regex should only match the exact above. So far here's what I have
> come up with:
> 
> re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
> 
> This works, but I was hoping for something a bit cleaner. I'm having
> to create a special case portion of the regex for the last of the 4
> numbers simply because it doesn't end with a comma like the first 3.
> Is there a better, more compact, way to write this regex?

The character class \d is equivalent to [0-9], and ',' isn't a special
character so it doesn't need to be escaped:

     re.compile(r'FILEVERSION (?:\d+,){3}\d+')


From wuwei23 at gmail.com  Thu Aug  6 12:07:51 2009
From: wuwei23 at gmail.com (alex23)
Date: Thu, 6 Aug 2009 09:07:51 -0700 (PDT)
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
Message-ID: <2b20f8fe-86e7-452e-ae94-e9179627fc74@y4g2000prf.googlegroups.com>

On Aug 7, 1:35?am, Robert Dailey  wrote:
> I'm creating a python script that is going to try to search a text
> file for any text that matches my regular expression. The thing it is
> looking for is:
>
> FILEVERSION 1,45,10082,3

Would it be easier to do it without regex? The following is untested
but I would probably do it more like this:

TOKEN = 'FILEVERSION '
for line in file:
  if line.startswith(TOKEN):
    version = line[len(TOKEN):]
    maj, min, rev, other = version.split(',')
    break # if there's only one occurance, otherwise do stuff here


From sion at viridian.paintbox  Thu Aug  6 12:11:24 2009
From: sion at viridian.paintbox (Sion Arrowsmith)
Date: Thu, 06 Aug 2009 16:11:24 GMT
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
Message-ID: 

Terry Reedy   wrote:
>RayS wrote:
>> http://www.php.net/manual/en/language.types.array.php is a prime example 
>> [ ... ]
>I consider consider this to an unreadable mishmash.
[compared to]
> something compact and readable.

Are you talking about the language or the documentation? 9-)

(Actually, that might be a serious point: does the approach to
documentation reflect language design?)

-- 
\S

   under construction



From atragor at gmail.com  Thu Aug  6 12:12:53 2009
From: atragor at gmail.com (Roman)
Date: Thu, 6 Aug 2009 20:12:53 +0400
Subject: Help with regex
In-Reply-To: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
Message-ID: <20090806161253.GA6789@localhost>

On 06/08/09 08:35, Robert Dailey wrote:
> Hey guys,
> 
> I'm creating a python script that is going to try to search a text
> file for any text that matches my regular expression. The thing it is
> looking for is:
> 
> FILEVERSION #,#,#,#
> 
> The # symbol represents any number that can be any length 1 or
> greater. Example:
> 
> FILEVERSION 1,45,10082,3
> 
> The regex should only match the exact above. So far here's what I have
> come up with:
> 
> re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
> 
> This works, but I was hoping for something a bit cleaner. I'm having
> to create a special case portion of the regex for the last of the 4
> numbers simply because it doesn't end with a comma like the first 3.
> Is there a better, more compact, way to write this regex?
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Since there cannot be more than one "end of string" you can try this
expression:
re.compile( r'FILEVERSION (?:[0-9]+(,|$)){4}' )


From rcdailey at gmail.com  Thu Aug  6 12:14:08 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 6 Aug 2009 09:14:08 -0700 (PDT)
Subject: Character encoding & the copyright symbol
Message-ID: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>

Hello,

I'm loading a file via open() in Python 3.1 and I'm getting the
following error when I try to print the contents of the file that I
obtained through a call to read():

UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
position 1650: character maps to 

The file is defined as ASCII and the copyright symbol shows up just
fine in Notepad++. However, Python will not print this symbol. How can
I get this to work? And no, I won't replace it with "(c)". Thanks!


From robert.kern at gmail.com  Thu Aug  6 12:14:51 2009
From: robert.kern at gmail.com (Robert Kern)
Date: Thu, 06 Aug 2009 11:14:51 -0500
Subject: How to comment on a Python PEP?
In-Reply-To: <4a7a9779$0$2384$9b622d9e@news.freenet.de>
References: 
	<4a7a9779$0$2384$9b622d9e@news.freenet.de>
Message-ID: 

On 2009-08-06 03:42, "Martin v. L?wis" wrote:
>> Is there a mechanism for submitting comments on a Python PEP?
>
> You post to python-dev or comp.lang.python, and you CC the author.

And be sure to put the PEP number in the Subject: line.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From rcdailey at gmail.com  Thu Aug  6 12:17:10 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 6 Aug 2009 09:17:10 -0700 (PDT)
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
	
Message-ID: <64c96ebc-ce6f-4657-968e-4cbe77a8303d@t13g2000yqt.googlegroups.com>

On Aug 6, 11:02?am, MRAB  wrote:
> Robert Dailey wrote:
> > Hey guys,
>
> > I'm creating a python script that is going to try to search a text
> > file for any text that matches my regular expression. The thing it is
> > looking for is:
>
> > FILEVERSION #,#,#,#
>
> > The # symbol represents any number that can be any length 1 or
> > greater. Example:
>
> > FILEVERSION 1,45,10082,3
>
> > The regex should only match the exact above. So far here's what I have
> > come up with:
>
> > re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
>
> > This works, but I was hoping for something a bit cleaner. I'm having
> > to create a special case portion of the regex for the last of the 4
> > numbers simply because it doesn't end with a comma like the first 3.
> > Is there a better, more compact, way to write this regex?
>
> The character class \d is equivalent to [0-9], and ',' isn't a special
> character so it doesn't need to be escaped:
>
> ? ? ?re.compile(r'FILEVERSION (?:\d+,){3}\d+')

But ',' is a special symbol It's used in this way:
{0,3}

This will match the previous regex 0-3 times. Are you sure commas need
not be escaped?

In any case, your suggestions help to clean it up a bit!


From rylesny at gmail.com  Thu Aug  6 12:20:28 2009
From: rylesny at gmail.com (ryles)
Date: Thu, 6 Aug 2009 09:20:28 -0700 (PDT)
Subject: Web page data and urllib2.urlopen
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
Message-ID: <923ea664-5da0-480b-a114-e83c831a44c8@f10g2000vbf.googlegroups.com>

On Aug 5, 4:30?pm, Massi  wrote:
> Hi everyone, I'm using the urllib2 library to get the html source code
> of web pages. In general it works great, but I'm having to do with a
> financial web site which does not provide the souce code I expect. As
> a matter of fact if you try:
>
> import urllib2
> res = urllib2.urlopen("http://www.marketwatch.com/story/mondays-
> biggest-gaining-and-declining-stocks-2009-07-27")
> page = res.read()
> print page
>
> you will see that the printed code is very different from the one
> given, for example, by mozilla. Since I have really little knowledge
> in html I can't even understand if this is a python or html problem.
> Can anyone give me some help?
> Thanks in advance.

Check if setting your user agent to Mozilla results in a different
page:

http://diveintopython.org/http_web_services/user_agent.html


From http  Thu Aug  6 12:20:33 2009
From: http (Paul Rubin)
Date: 06 Aug 2009 09:20:33 -0700
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
Message-ID: <7xab2c52y6.fsf@ruckus.brouhaha.com>

alex23  writes:
> No offence, but the last thing the official documentation needs is
> example code written by people learning how to code. Suggest changes,
> request clarifications, submit samples for review, sure, but direct
> modification by users? I've seen the PHP docs; thanks but no thanks.

The PHP docs as I remember are sort of regular (non-publically
editable) doc pages, each of which has a public discussion thread
where people can post questions and answers about the topic of that
doc page.  I thought it worked really well.  The main thing is that
the good stuff from the comment section gets folded into the actual
doc now and then.

There is something similar with the PostgreSQL docs.  There is also
Real World Haskell (http://book.realworld.haskell.org) which has a lot
of interspersed user comments.  It would be cool if Python's doc site
did something like it too.


From michael at stroeder.com  Thu Aug  6 12:26:09 2009
From: michael at stroeder.com (=?UTF-8?B?TWljaGFlbCBTdHLDtmRlcg==?=)
Date: Thu, 06 Aug 2009 18:26:09 +0200
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 
	
Message-ID: <2qcrk6-doj.ln1@nb2.stroeder.com>

Thorsten Kampe wrote:
> * Michael Str?der (Wed, 05 Aug 2009 16:43:09 +0200)
>> These both expressions are equivalent but which is faster or should be
>> used for any reason?
>>
>> u = unicode(s,'utf-8')
>>
>> u = s.decode('utf-8') # looks nicer
> 
> "decode" was added in Python 2.2 for the sake of symmetry to encode(). 

Yes, and I like the style. But...

> It's essentially the same as unicode() and I wouldn't be surprised if it 
> is exactly the same.

Did you try?

> I don't think any measurable speed increase will be noticeable between
> those two.

Well, seems not to be true. Try yourself. I did (my console has UTF-8 as charset):

Python 2.6 (r26:66714, Feb  3 2009, 20:52:03)
[GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer("'???????'.decode('utf-8')").timeit(1000000)
7.2721178531646729
>>> timeit.Timer("'???????'.decode('utf8')").timeit(1000000)
7.1302499771118164
>>> timeit.Timer("unicode('???????','utf8')").timeit(1000000)
8.3726329803466797
>>> timeit.Timer("unicode('???????','utf-8')").timeit(1000000)
1.8622009754180908
>>> timeit.Timer("unicode('???????','utf8')").timeit(1000000)
8.651669979095459
>>>

Comparing again the two best combinations:

>>> timeit.Timer("unicode('???????','utf-8')").timeit(10000000)
17.23644495010376
>>> timeit.Timer("'???????'.decode('utf8')").timeit(10000000)
72.087096929550171

That is significant! So the winner is:

unicode('???????','utf-8')

Ciao, Michael.


From philip at semanchuk.com  Thu Aug  6 12:31:27 2009
From: philip at semanchuk.com (Philip Semanchuk)
Date: Thu, 6 Aug 2009 12:31:27 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
Message-ID: 


On Aug 6, 2009, at 12:14 PM, Robert Dailey wrote:

> Hello,
>
> I'm loading a file via open() in Python 3.1 and I'm getting the
> following error when I try to print the contents of the file that I
> obtained through a call to read():
>
> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> position 1650: character maps to 
>
> The file is defined as ASCII and the copyright symbol shows up just
> fine in Notepad++. However, Python will not print this symbol. How can
> I get this to work? And no, I won't replace it with "(c)". Thanks!

If the file is defined as ASCII and it contains 0xa9, then the file  
was written incorrectly or you were told the wrong encoding. There is  
no such character in ASCII which runs from 0x00 - 0x7f.

The copyright symbol == 0xa9 if the encoding is ISO-8859-1 or  
windows-1252, and since you're on Windows the latter is a likely bet.

http://en.wikipedia.org/wiki/Ascii
http://en.wikipedia.org/wiki/Iso-8859-1
http://en.wikipedia.org/wiki/Windows-1252


Bottom line is that your file is not in ASCII. Try specifying  
windows-1252 as the encoding. Without seeing your code I can't tell  
you where you need to specify the encoding, but the Python docs should  
help you out.


HTH
Philip



From R.Brodie at rl.ac.uk  Thu Aug  6 12:31:58 2009
From: R.Brodie at rl.ac.uk (Richard Brodie)
Date: Thu, 6 Aug 2009 17:31:58 +0100
Subject: Character encoding & the copyright symbol
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
Message-ID: 


"Robert Dailey"  wrote in message 
news:29ab0981-b95d-4435-91bd-a7a520419ada at b15g2000yqd.googlegroups.com...

> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> position 1650: character maps to 
>
> The file is defined as ASCII.

That's the problem: ASCII is a seven bit code. What you have is
actually ISO-8859-1 (or possibly Windows-1252).

The different ISO-8859-n variants assign various characters to
to '\xa9'. Rather than being Western-European centric and assuming
ISO-8859-1 by default, Python throws an error when you stray
outside of strict ASCII. 




From python at mrabarnett.plus.com  Thu Aug  6 12:34:59 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 17:34:59 +0100
Subject: Help with regex
In-Reply-To: <64c96ebc-ce6f-4657-968e-4cbe77a8303d@t13g2000yqt.googlegroups.com>
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>	
	<64c96ebc-ce6f-4657-968e-4cbe77a8303d@t13g2000yqt.googlegroups.com>
Message-ID: <4A7B0633.2030106@mrabarnett.plus.com>

Robert Dailey wrote:
> On Aug 6, 11:02 am, MRAB  wrote:
>> Robert Dailey wrote:
>>> Hey guys,
>>> I'm creating a python script that is going to try to search a text
>>> file for any text that matches my regular expression. The thing it is
>>> looking for is:
>>> FILEVERSION #,#,#,#
>>> The # symbol represents any number that can be any length 1 or
>>> greater. Example:
>>> FILEVERSION 1,45,10082,3
>>> The regex should only match the exact above. So far here's what I have
>>> come up with:
>>> re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
>>> This works, but I was hoping for something a bit cleaner. I'm having
>>> to create a special case portion of the regex for the last of the 4
>>> numbers simply because it doesn't end with a comma like the first 3.
>>> Is there a better, more compact, way to write this regex?
>> The character class \d is equivalent to [0-9], and ',' isn't a special
>> character so it doesn't need to be escaped:
>>
>>      re.compile(r'FILEVERSION (?:\d+,){3}\d+')
> 
> But ',' is a special symbol It's used in this way:
> {0,3}
> 
> This will match the previous regex 0-3 times. Are you sure commas need
> not be escaped?
> 
> In any case, your suggestions help to clean it up a bit!

By 'special' I mean ones like '?', '*', '(', etc. ',' isn't special in
that sense.

In fact, the {...} quantifier is special only if it's syntactically
correct, otherwise it's just a literal, eg "a{," and a{} are just
literals.


From Samnsparky at gmail.com  Thu Aug  6 12:40:23 2009
From: Samnsparky at gmail.com (Sparky)
Date: Thu, 6 Aug 2009 09:40:23 -0700 (PDT)
Subject: Two Dimensional Array + ctypes
References: <79d2b3e3-b049-4d70-a56b-6e7f3ea2fa86@e27g2000yqm.googlegroups.com>
	
Message-ID: <6a218894-54d3-48d4-8a91-74e02ceefecb@g23g2000vbr.googlegroups.com>

On Aug 5, 11:19?pm, "Gabriel Genellina" 
wrote:
> En Wed, 05 Aug 2009 20:12:09 -0300, Sparky  escribi?:
>
>
>
>
>
> > Hello! I am trying to call this method:
>
> > long _stdcall AIBurst(long *idnum, [...]
> > ? ? ? ? ? ? ? ? ? ? long timeout,
> > ? ? ? ? ? ? ? ? ? ? float (*voltages)[4],
> > ? ? ? ? ? ? ? ? ? ? long *stateIOout,
> > ? ? ? ? ? ? ? ? ? ? long *overVoltage,
> > ? ? ? ? ? ? ? ? ? ? long transferMode);
>
> > I am having some problems with that ?float (*voltages)[4].
> > ? ? ? ? pointerArray = (ctypes.c_void_p * 4)
> > ? ? ? ? voltages = pointerArray(ctypes.cast(ctypes.pointer
> > ((ctypes.c_long * 4096)()), ctypes.c_void_p), ctypes.cast
> > (ctypes.pointer((ctypes.c_long * 4096)()), ctypes.c_void_p),
> > ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)()),
> > ctypes.c_void_p), ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)
>
> Why c_long and not c_float?
> Anyway, this way looks much more clear to me (and doesn't require a cast):
>
> arr4096_type = ctypes.c_float * 4096
> voltages_type = arr4096_type * 4
> voltages = voltages_type()
>
> > The program runs but the values that come back in the array are not
> > right.
>
> Thay might be due to the long/float confusion.
>
> --
> Gabriel Genellina

Brilliant! Your code is much cleaner and the problem must have been
float vs long.

Thanks,
Sam


From arockinit at gmail.com  Thu Aug  6 12:41:06 2009
From: arockinit at gmail.com (Adam N)
Date: Thu, 6 Aug 2009 09:41:06 -0700 (PDT)
Subject: Using easy_install, reduncant?
References:  
	
Message-ID: <671c5d83-650b-4a20-9504-b430b1ee8318@d4g2000vbm.googlegroups.com>

On Jul 27, 7:53?pm, David Lyon  wrote:
> On Mon, 27 Jul 2009 09:42:06 -0700 (PDT), ray 
> wrote:
>
> > I am working on a Trac installation. ?I am new to Python. ?To install
> > packages, it is suggested to use setuptools. ?I have not understood
> > the directions.
>
> > I execute ez_install.py.
>
> > Then I attempt to execute easy_install.py setuptools-0.6c9-py2.6.egg.
> > There response that setuptools is already the active version in easy-
> > install.pth. ?Then:
> > Installing easy_install.exe script to C:\Python26\Scripts error: ?C:
> > \Python26\Scripts\Easy_install.exe: Permission denied.
>
> > I have compared the file entries before and after this attempt and
> > there are no new files. ?Is there any problems here? ?What did I miss?
>
> Try using python package manager :http://sourceforge.net/projects/pythonpkgmgr/
>
> You might find it a lot simpler. It will download and install setuptools
> for you if you are still having problems.
>
> David

Is there any solution within the easy_install world?  I'm trying to
run a script (pinax) that calls it specifically so I'd have to do all
sorts of hacking to use pythonpkgmgr.


From rcdailey at gmail.com  Thu Aug  6 12:41:07 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 6 Aug 2009 09:41:07 -0700 (PDT)
Subject: Character encoding & the copyright symbol
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
	
Message-ID: 

On Aug 6, 11:31?am, "Richard Brodie"  wrote:
> "Robert Dailey"  wrote in message
>
> news:29ab0981-b95d-4435-91bd-a7a520419ada at b15g2000yqd.googlegroups.com...
>
> > UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> > position 1650: character maps to 
>
> > The file is defined as ASCII.
>
> That's the problem: ASCII is a seven bit code. What you have is
> actually ISO-8859-1 (or possibly Windows-1252).
>
> The different ISO-8859-n variants assign various characters to
> to '\xa9'. Rather than being Western-European centric and assuming
> ISO-8859-1 by default, Python throws an error when you stray
> outside of strict ASCII.

Thanks for the help guys. Sorry I left out code, I wasn't sure at the
time if it would be helpful. Below is my code:


#========================================================
def GetFileContentsAsString( file ):
   f = open( file, mode='r', encoding='cp1252' )
   contents = f.read()
   f.close()
   return contents

#========================================================
def ReplaceVersion( file, version, regExps ):
   #match = regExps[0].search( 'FILEVERSION 1,45332,2100,32,' )
   #print( match.group() )
   text = GetFileContentsAsString( file )
   print( text )


As you can see, I am trying to load the file with encoding 'cp1252'
which, according to the python 3.1 docs, translates to windows-1252. I
also tried 'latin_1', which translates to ISO-8859-1, but this did not
work either. Am I doing something else wrong?


From rcdailey at gmail.com  Thu Aug  6 12:43:42 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 6 Aug 2009 09:43:42 -0700 (PDT)
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
	
Message-ID: <35f72d0f-d659-423a-bea0-955092e02d15@d34g2000vbm.googlegroups.com>

On Aug 6, 11:12?am, Roman  wrote:
> On 06/08/09 08:35, Robert Dailey wrote:
>
>
>
>
>
> > Hey guys,
>
> > I'm creating a python script that is going to try to search a text
> > file for any text that matches my regular expression. The thing it is
> > looking for is:
>
> > FILEVERSION #,#,#,#
>
> > The # symbol represents any number that can be any length 1 or
> > greater. Example:
>
> > FILEVERSION 1,45,10082,3
>
> > The regex should only match the exact above. So far here's what I have
> > come up with:
>
> > re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
>
> > This works, but I was hoping for something a bit cleaner. I'm having
> > to create a special case portion of the regex for the last of the 4
> > numbers simply because it doesn't end with a comma like the first 3.
> > Is there a better, more compact, way to write this regex?
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Since there cannot be more than one "end of string" you can try this
> expression:
> re.compile( r'FILEVERSION (?:[0-9]+(,|$)){4}' )

I had thought of this but I can't use that either. I have to assume
that someone was silly and put text at the end somewhere, perhaps a
comment. Like so:

FILEVERSION 1,2,3,4     // This is the file version

It would be nice if there was a type of counter for regex. So you
could say 'match only 1 [^,]' or something like that...


From marduk at letterboxes.org  Thu Aug  6 12:45:43 2009
From: marduk at letterboxes.org (Albert Hopkins)
Date: Thu, 06 Aug 2009 12:45:43 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
Message-ID: <1249577143.6168.14.camel@centar>

On Thu, 2009-08-06 at 09:14 -0700, Robert Dailey wrote:
> Hello,
> 
> I'm loading a file via open() in Python 3.1 and I'm getting the
> following error when I try to print the contents of the file that I
> obtained through a call to read():
> 
> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> position 1650: character maps to 
> 
> The file is defined as ASCII and the copyright symbol shows up just
> fine in Notepad++. However, Python will not print this symbol. How can
> I get this to work? And no, I won't replace it with "(c)". Thanks!

It's not actually ASCII but Windows-1252 extended ASCII-like.  So with
that information you can do either of 2 things: You can open it in text
mode and specify the encoding:

>>> fp = open(filename, 'r', encoding='windows-1252')
>>> s = fp.read()
>>> print(s)

or you can open it in binary mode and decode it later:

>>> fp = open(filename, 'rb')
>>> b = fp.read()
>>> print(str(b, encoding='windows-1252'))

Or you may be able to set the default encoding to windows-1252 but I
don't know how to do that (in Windows).

p.s.

Next time it might be helpful to paste a code snippet else we have to
make assumptions about what you are actually doing.



From R.Brodie at rl.ac.uk  Thu Aug  6 13:02:01 2009
From: R.Brodie at rl.ac.uk (Richard Brodie)
Date: Thu, 6 Aug 2009 18:02:01 +0100
Subject: Character encoding & the copyright symbol
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
	
	
Message-ID: 


"Robert Dailey"  wrote in message 
news:f64f9830-c416-41b1-a510-c1e486271b4e at g19g2000vbi.googlegroups.com...

> As you can see, I am trying to load the file with encoding 'cp1252'
> which, according to the python 3.1 docs, translates to windows-1252. I
> also tried 'latin_1', which translates to ISO-8859-1, but this did not
> work either. Am I doing something else wrong?

Probably it's just the debugging print that has a problem, and if you
opened an output file with an encoding specified it would be fine.
When you get a UnicodeEncodingError, it's conversion _from_
Unicode that has failed. 




From philip at semanchuk.com  Thu Aug  6 13:02:14 2009
From: philip at semanchuk.com (Philip Semanchuk)
Date: Thu, 6 Aug 2009 13:02:14 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: 
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
	
	
Message-ID: <1886EEEC-CFDA-40BD-8BAC-64015C4D3672@semanchuk.com>


On Aug 6, 2009, at 12:41 PM, Robert Dailey wrote:

> On Aug 6, 11:31 am, "Richard Brodie"  wrote:
>> "Robert Dailey"  wrote in message
>>
>> news:29ab0981-b95d-4435-91bd-a7a520419ada at b15g2000yqd.googlegroups.com 
>> ...
>>
>>> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
>>> position 1650: character maps to 
>>
>>> The file is defined as ASCII.
>>
>> That's the problem: ASCII is a seven bit code. What you have is
>> actually ISO-8859-1 (or possibly Windows-1252).
>>
>> The different ISO-8859-n variants assign various characters to
>> to '\xa9'. Rather than being Western-European centric and assuming
>> ISO-8859-1 by default, Python throws an error when you stray
>> outside of strict ASCII.
>
> Thanks for the help guys. Sorry I left out code, I wasn't sure at the
> time if it would be helpful. Below is my code:
>
>
> #========================================================
> def GetFileContentsAsString( file ):
>   f = open( file, mode='r', encoding='cp1252' )
>   contents = f.read()
>   f.close()
>   return contents
>
> #========================================================
> def ReplaceVersion( file, version, regExps ):
>   #match = regExps[0].search( 'FILEVERSION 1,45332,2100,32,' )
>   #print( match.group() )
>   text = GetFileContentsAsString( file )
>   print( text )
>
>
> As you can see, I am trying to load the file with encoding 'cp1252'
> which, according to the python 3.1 docs, translates to windows-1252. I
> also tried 'latin_1', which translates to ISO-8859-1, but this did not
> work either. Am I doing something else wrong?


Are you getting the error when you read the file or when you  
print(text)?

As a side note, you should probably use something other than "file"  
for the parameter name in GetFileContentsAsString() since file() is a  
Python function.






From kosta.koeman at gmail.com  Thu Aug  6 13:27:56 2009
From: kosta.koeman at gmail.com (Kosta)
Date: Thu, 6 Aug 2009 10:27:56 -0700 (PDT)
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> 
	
	
	
Message-ID: <1a236d86-72de-4b43-bc7b-cf0c9bdab615@u38g2000pro.googlegroups.com>

On Aug 6, 3:57?am, David Cournapeau  wrote:
> On Thu, Aug 6, 2009 at 12:39 AM, Kosta wrote:
>
> > Setenv.bat sets up the path and other environment variables build.exe
> > needs to compile and link (and even binplace) its utilities. ?So
> > building itself is not the issue. ?The problem is that if I call
> > setenv.bat from Python and then build.exe, but the modifications to
> > the path (and other environment settings) are not seen by Python, so
> > the attempt to build without a specified path fails.
>
> It sounds like you do not propagate the environment when calling
> setenv.bat from python. There is an option to do so in
> subprocess.Popen init method, or you can define your own environment
> if you do not want to propagate the whole environment (but this is
> often difficult to avoid for build environment in my experience,
> expecially if you don't have access to the sources of the whole system
> to check which variables are necessary).
>
> David

David,

Thanks you.  I looked up the docs on Popen (http://docs.python.org/
library/subprocess.html) where I read:

On Windows: the Popen class uses CreateProcess() to execute the child
program, which operates on strings. If args is a sequence, it will be
converted to a string using the list2cmdline() method. Please note
that not all MS Windows applications interpret the command line the
same way: list2cmdline() is designed for applications using the same
rules as the MS C runtime.

My interpretation of the above (and your email) is that using Popen
allows one to pass the Python environment to a child processs (in my
case, setenv.bat).   I need the reverse, to propagate from the child
to the parent.

Thanks,
Kosta



From ladasky at my-deja.com  Thu Aug  6 13:36:40 2009
From: ladasky at my-deja.com (John Ladasky)
Date: Thu, 6 Aug 2009 10:36:40 -0700 (PDT)
Subject: Overlap in python
References: 
	<4a7892c2$0$2297$91cee783@newsreader02.highway.telekom.at> 
	
Message-ID: <900c8420-fc28-41d2-8720-518fc48763db@v15g2000prn.googlegroups.com>

On Aug 4, 3:21?pm, Jay Bird  wrote:
> Hi everyone,
>
> I wanted to thank you all for your help and *excellent* discussion. ?I
> was able to utilize and embed the script by Grigor Lingl in the 6th
> post of this discussion to get my program to work very quickly (I had
> to do about 20 comparisons per data bin, with over 40K bins in
> total). ?I am involved in genomic analysis research and this problem
> comes up a lot and I was surprised to not have been able to find a
> clear way to solve it. ?I will also look through all the tips in this
> thread, I have a feeling they may come in handy for future use!
>
> Thank you again,
> Jay

Hi Jay,

I know this is a bit off-topic, but how does this pertain to genomic
analysis?  Are you counting the lengths of microsatellite repeats or
something?


From steve at REMOVE-THIS-cybersource.com.au  Thu Aug  6 13:39:10 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 06 Aug 2009 17:39:10 GMT
Subject: Unexpected side-effects of assigning to sys.modules[__name__]
Message-ID: <028b05d5$0$5185$c3e8da3@news.astraweb.com>

Given this module:

#funny.py
import sys
print "Before:"
print "  __name__ =", __name__
print "  sys.modules[__name__] =", sys.modules[__name__]
sys.modules[__name__] = 123
print "After:"
print "  __name__ =", __name__
print "  sys =", sys


when I run it I get these results:


[steve at sylar python]$ python2.6 funny.py
Before:
  __name__ = __main__
  sys.modules[__name__] = 
After:
  __name__ = None
  sys = None



I'm completely perplexed by this behaviour. sys.modules() seems to be a 
regular dict, at least according to type(), and yet assigning to an item 
of it seems to have unexpected, and rather weird, side-effects.

What am I missing?



-- 
Steven


From nobody at nowhere.com  Thu Aug  6 13:50:23 2009
From: nobody at nowhere.com (Nobody)
Date: Thu, 06 Aug 2009 18:50:23 +0100
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
	
Message-ID: 

On Thu, 06 Aug 2009 17:02:44 +0100, MRAB wrote:

> The character class \d is equivalent to [0-9]

Not for Unicode, which is the default in 3.x.



From nobody at nowhere.com  Thu Aug  6 13:58:10 2009
From: nobody at nowhere.com (Nobody)
Date: Thu, 06 Aug 2009 18:58:10 +0100
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
Message-ID: 

On Thu, 06 Aug 2009 08:35:57 -0700, Robert Dailey wrote:

> I'm creating a python script that is going to try to search a text
> file for any text that matches my regular expression. The thing it is
> looking for is:
> 
> FILEVERSION #,#,#,#
> 
> The # symbol represents any number that can be any length 1 or
> greater. Example:
> 
> FILEVERSION 1,45,10082,3
> 
> The regex should only match the exact above. So far here's what I have
> come up with:
> 
> re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )

[0-9]+ allows any number of leading zeros, which is sometimes undesirable.
Using:

	(0|[1-9][0-9]*)

is more robust.



From jeanmichel at sequans.com  Thu Aug  6 14:01:42 2009
From: jeanmichel at sequans.com (Jean-Michel Pichavant)
Date: Thu, 06 Aug 2009 20:01:42 +0200
Subject: Unexpected side-effects of assigning to sys.modules[__name__]
In-Reply-To: <028b05d5$0$5185$c3e8da3@news.astraweb.com>
References: <028b05d5$0$5185$c3e8da3@news.astraweb.com>
Message-ID: <4A7B1A86.8040609@sequans.com>

Steven D'Aprano wrote:
> Given this module:
>
> #funny.py
> import sys
> print "Before:"
> print "  __name__ =", __name__
> print "  sys.modules[__name__] =", sys.modules[__name__]
> sys.modules[__name__] = 123
> print "After:"
> print "  __name__ =", __name__
> print "  sys =", sys
>
>
> when I run it I get these results:
>
>
> [steve at sylar python]$ python2.6 funny.py
> Before:
>   __name__ = __main__
>   sys.modules[__name__] = 
> After:
>   __name__ = None
>   sys = None
>
>
>
> I'm completely perplexed by this behaviour. sys.modules() seems to be a 
> regular dict, at least according to type(), and yet assigning to an item 
> of it seems to have unexpected, and rather weird, side-effects.
>
> What am I missing?
>
>
>
>   
Maybe when you assign 123 to sys.modules[__name__], you've removed the 
last reference on  and it is 
garbaged. You are then loosing all your initial namespace.


try this one:
#funny.py
import sys
print "Before:"
print "  __name__ =", __name__
print "  sys.modules[__name__] =", sys.modules[__name__]
foo = sys.modules[__name__] # backup ref for the garbage collector
sys.modules[__name__] = 123
print "After:"
print "  __name__ =", __name__
print "  sys =", sys

Jean-Michel




From thorsten at thorstenkampe.de  Thu Aug  6 14:05:52 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Thu, 6 Aug 2009 20:05:52 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
Message-ID: 

* Michael Str?der (Thu, 06 Aug 2009 18:26:09 +0200)
> Thorsten Kampe wrote:
> > * Michael Str?der (Wed, 05 Aug 2009 16:43:09 +0200)
> > I don't think any measurable speed increase will be noticeable
> > between those two.
> 
> Well, seems not to be true. Try yourself. I did (my console has UTF-8 as charset):
> 
> Python 2.6 (r26:66714, Feb  3 2009, 20:52:03)
> [GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import timeit
> >>> timeit.Timer("'???????'.decode('utf-8')").timeit(1000000)
> 7.2721178531646729
> >>> timeit.Timer("'???????'.decode('utf8')").timeit(1000000)
> 7.1302499771118164
> >>> timeit.Timer("unicode('???????','utf8')").timeit(1000000)
> 8.3726329803466797
> >>> timeit.Timer("unicode('???????','utf-8')").timeit(1000000)
> 1.8622009754180908
> >>> timeit.Timer("unicode('???????','utf8')").timeit(1000000)
> 8.651669979095459
> >>>
> 
> Comparing again the two best combinations:
> 
> >>> timeit.Timer("unicode('???????','utf-8')").timeit(10000000)
> 17.23644495010376
> >>> timeit.Timer("'???????'.decode('utf8')").timeit(10000000)
> 72.087096929550171
> 
> That is significant! So the winner is:
> 
> unicode('???????','utf-8')

Unless you are planning to write a loop that decodes "???????" one 
million times, these benchmarks are meaningless.

Thorsten


From nobody at nowhere.com  Thu Aug  6 14:08:26 2009
From: nobody at nowhere.com (Nobody)
Date: Thu, 06 Aug 2009 19:08:26 +0100
Subject: Character encoding & the copyright symbol
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
Message-ID: 

On Thu, 06 Aug 2009 09:14:08 -0700, Robert Dailey wrote:

> I'm loading a file via open() in Python 3.1 and I'm getting the
> following error when I try to print the contents of the file that I
> obtained through a call to read():
> 
> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> position 1650: character maps to 
> 
> The file is defined as ASCII and the copyright symbol shows up just
> fine in Notepad++. However, Python will not print this symbol. How can
> I get this to work? And no, I won't replace it with "(c)". Thanks!

1. As others have said, your file *isn't* ASCII, but that isn't the
problem.

2. The problem is that the encoding which your standard output
stream uses doesn't have the copyright symbol. You need to use something
like:

sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'iso-8859-1')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'iso-8859-1')

to fix the encoding of the stdout and stderr streams.



From python-url at phaseit.net  Thu Aug  6 14:21:58 2009
From: python-url at phaseit.net (Gabriel Genellina)
Date: Thu, 6 Aug 2009 18:21:58 +0000 (UTC)
Subject: Python-URL! - weekly Python news and links (Aug  6)
Message-ID: 

QOTW:  "The economy rises and falls, money comes and goes, but a great
conference has permanent good effects.  Well, a lot more permanent than
government fiscal policy, anyway." - Python Software Foundation Director
"bitter-in-victory-gracious-in-defeat-ly y'rs" timbot

    
    Is python free of "buffer overflow" errors?
        http://groups.google.com/group/comp.lang.python/t/a31faac6feced289/

    Lessons learned in implementation of a write-once dict:
        http://groups.google.com/group/comp.lang.python/t/bc8b91669257e246/

    Methods, attributes, iterators, lambdas, and how Ruby handles them:
        http://groups.google.com/group/comp.lang.python/t/6e4fc61946513405/

    Python 3 allows for custom types to be used as a class namespace 
    not just dicts):
        http://groups.google.com/group/comp.lang.python/t/50caadd10d2cca16/

    Could Python be used to write a device driver?
        http://groups.google.com/group/comp.lang.python/t/4efc28f9fe45b69e/

    The various meanings of the underscore character '_' in identifiers:
        http://groups.google.com/group/comp.lang.python/t/e32d577ad3d5a208/

    Generate a new object each time a name is imported:
        http://groups.google.com/group/comp.lang.python/t/b7112f74e2efa8bd/

    heapq.nlargest takes a "key" argument - why not the other functions in
    the same module?
        http://groups.google.com/group/comp.lang.python/t/a5095d3f4b54f79b/

    Immutable objects and how they could improve concurrency [old thread,
    still alive]:
        http://groups.google.com/group/comp.lang.python/t/cb0cf56c52321ccc/5c82cd09767ba85a?#5c82cd09767ba85a

    How to modify a variable in an outer (non global) scope:
        http://groups.google.com/group/comp.lang.python/t/e0e64250bd82825f/

    Best way to add "private" directories to sys.path:
        http://groups.google.com/group/comp.lang.python/t/cb43cf90d72f6833/

    Interval arithmetic:
        http://groups.google.com/group/comp.lang.python/t/71f050d8f5987244/

    Ensure that no more than three instances of the same program are
    running at the same time:
        http://groups.google.com/group/comp.lang.python/t/af7ae6429c2bda1e/

    Some people don't like the way Python documentation is managed/presented:
        http://groups.google.com/group/comp.lang.python/t/a52b22cd90b15ef8/
    
    
========================================================================
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

    Just beginning with Python?  This page is a great place to start:
	http://wiki.python.org/moin/BeginnersGuide/Programmers

    The Python Papers aims to publish "the efforts of Python enthusiasts":
	http://pythonpapers.org/
    The Python Magazine is a technical monthly devoted to Python:
	http://pythonmagazine.com

    Readers have recommended the "Planet" sites:
	http://planetpython.org
	http://planet.python.org

    comp.lang.python.announce announces new Python software.  Be
    sure to scan this newsgroup weekly.
        http://groups.google.com/group/comp.lang.python.announce/topics

    Python411 indexes "podcasts ... to help people learn Python ..."
    Updates appear more-than-weekly:
        http://www.awaretek.com/python/index.html

    The Python Package Index catalogues packages.
        http://www.python.org/pypi/

    Much of Python's real work takes place on Special-Interest Group
    mailing lists
        http://www.python.org/sigs/

    Python Success Stories--from air-traffic control to on-line
    match-making--can inspire you or decision-makers to whom you're
    subject with a vision of what the language makes practical.
        http://www.pythonology.com/success

    The Python Software Foundation (PSF) has replaced the Python
    Consortium as an independent nexus of activity.  It has official
    responsibility for Python's development and maintenance.
        http://www.python.org/psf/
    Among the ways you can support PSF is with a donation.
        http://www.python.org/psf/donations/

    The Summary of Python Tracker Issues is an automatically generated
    report summarizing new bugs, closed ones, and patch submissions. 
        http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date

    Although unmaintained since 2002, the Cetus collection of Python
    hyperlinks retains a few gems.
        http://www.cetus-links.org/oo_python.html

    Python FAQTS
        http://python.faqts.com/

    The Cookbook is a collaborative effort to capture useful and
    interesting recipes.
	http://code.activestate.com/recipes/langs/python/

    Many Python conferences around the world are in preparation.
    Watch this space for links to them.

    Among several Python-oriented RSS/RDF feeds available, see:
        http://www.python.org/channews.rdf
    For more, see:
        http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all
    The old Python "To-Do List" now lives principally in a
    SourceForge reincarnation.
        http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse
	http://www.python.org/dev/peps/pep-0042/

    del.icio.us presents an intriguing approach to reference commentary.
    It already aggregates quite a bit of Python intelligence.
        http://del.icio.us/tag/python

    Enjoy the *Python Magazine*.
	http://pymag.phparch.com/

    *Py: the Journal of the Python Language*
        http://www.pyzine.com

    Dr.Dobb's Portal is another source of Python news and articles:
        http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python
    and Python articles regularly appear at IBM DeveloperWorks:
        http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8

Previous - (U)se the (R)esource, (L)uke! - messages are listed here:
  http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date
  http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d&
  http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes

There is *not* an RSS for "Python-URL!"--at least not yet.  Arguments
for and against are occasionally entertained.


Suggestions/corrections for next week's posting are always welcome.
E-mail to  should get through.

To receive a new issue of this posting in e-mail each Monday morning
(approximately), ask  to subscribe.  Mention
"Python-URL!".  Write to the same address to unsubscribe.


-- The Python-URL! Team--

Phaseit, Inc. (http://phaseit.net) is pleased to participate in and
sponsor the "Python-URL!" project.  Watch this space for upcoming
news about posting archives.


From rt8396 at gmail.com  Thu Aug  6 14:33:06 2009
From: rt8396 at gmail.com (r)
Date: Thu, 6 Aug 2009 11:33:06 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
Message-ID: <2eaf5b79-dc0a-4762-9f06-5de7e22381a2@r38g2000yqn.googlegroups.com>

On Aug 6, 11:20?am, Paul Rubin  wrote:
...(snip)
> There is something similar with the PostgreSQL docs. ?There is also
> Real World Haskell (http://book.realworld.haskell.org) which has a lot
> of interspersed user comments. ?It would be cool if Python's doc site
> did something like it too.

hear! hear!


From kee at kagi.com  Thu Aug  6 14:36:31 2009
From: kee at kagi.com (Kee Nethery)
Date: Thu, 6 Aug 2009 11:36:31 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
Message-ID: 

As someone trying to learn the language I want to say that the tone on  
this list towards people who are trying to learn Python  feels like it  
has become anti-newbies.

Learning a new language is difficult enough without seeing other  
newbies getting shamed for not knowing everything there is to know  
about Python before asking their questions.

For example, the guy who was looking for Python sample code for the  
Google Map API, calling him a troll was harsh. Suggesting he broach  
the question to Google was a reasonable answer. By the same token, his  
asking this list about the missing Python examples seems reasonable  
also. Seems to me that people on a Python list might have some  
background knowledge or even samples of the Google Python code that  
was no longer on the Google web site.

There seems to be a general consensus among the newbies that other  
languages have a user contributions resource tied to the main official  
docs to allow newbies to teach each other what they have learned. The  
desire is for python.org to have the same kind of support resource so  
that us newbies can self support each other.

Kee Nethery


From dioxide.software at gmail.com  Thu Aug  6 14:49:26 2009
From: dioxide.software at gmail.com (KK)
Date: Thu, 6 Aug 2009 11:49:26 -0700 (PDT)
Subject: pylucene installation problem on Ubuntu 9.04
Message-ID: 

hi all,
I've trying to install pylucene on my linux box from last 2 days but
not able to do so. first i tried to install it using apt-get like
this,
kk-laptop$ sudo apt-get install pylucene
and it did install python2.5, python2.5-minimal and pylucene. I must
mention one thing that I already had python2.6 on my box as the
default python i.e /usr/bin/python is linked to python2.6. Anyway s,
now i started the python interpreter using "python" command from cli
and then to make sure pylucene has been installed i tried to import
the module and to my surprise it said "module pylucene not found".
I thought I should enter the python2.6 env and do the same , so i
tried starting the python2.6 interpreter using "python2.6" as the
command and tried importing the same module and again it failed giving
the same irritating message.
 As a final try i pulled the source code of pylucene and as per the
comments given there in the README file, copied the mentioned files to
site-packages directory of python2.6 and then tried importing the
module and then got the same error message saying no module name
pylucene is present. I'm sick of this error !
Can someone point me what is the issue? If it is due to multiple
version of python running on box, can someone tell me which one to
remove or someone tell me how to get the whole thing running? I'll
very much thankful to you guys.

Thanks,
KK.


From martin.hellwig at dcuktec.org  Thu Aug  6 14:50:30 2009
From: martin.hellwig at dcuktec.org (Martin P. Hellwig)
Date: Thu, 06 Aug 2009 19:50:30 +0100
Subject: Parsing Binary Structures; Is there a better way / What is your
	way?
In-Reply-To: 
References: 
Message-ID: 

Thanks all for your insights and suggestions.
It seems to me that there are a couple of ways to this bit manipulation 
and a couple of foreign modules to assist you with that.

Would it be worth the while to do a PEP on this?
Personally I think that it would be nice to have a standard module in 
Python for this but perhaps there is a good reason that there isn't 
already one.

-- 
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'


From piet at cs.uu.nl  Thu Aug  6 14:58:13 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Thu, 06 Aug 2009 20:58:13 +0200
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com>
	
	
	
	<1a236d86-72de-4b43-bc7b-cf0c9bdab615@u38g2000pro.googlegroups.com>
Message-ID: 

>>>>> Kosta  (K) wrote:

>K> My interpretation of the above (and your email) is that using Popen
>K> allows one to pass the Python environment to a child processs (in my
>K> case, setenv.bat).   I need the reverse, to propagate from the child
>K> to the parent.

I don't think there is any modern OS that allows that. Unless you use
your own protocol of course, like letting the child write the
environment to its stdout and reading and interpreting it in the parent.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From wescpy at gmail.com  Thu Aug  6 15:14:21 2009
From: wescpy at gmail.com (Wesley Chun)
Date: Thu, 6 Aug 2009 12:14:21 -0700 (PDT)
Subject: Python docs disappointing
References: 
Message-ID: <1fcc79a2-692a-4744-a3e4-122394e3dad9@a39g2000pre.googlegroups.com>

On Jul 31, 1:10?pm, kj  wrote:
> I'm pretty new to Python, and I like a lot overall, but I find the
> documentation for Python rather poor, overall.
>
> I'm sure that Python experts don't have this problem:


kj,

welcome to Python! i'm sorry that you find the documentation lacking.
the one thing about the docs is that they're just pointers to get you
started and aren't very comprehensive. there are plenty of good online
tutorials out there as well as books. in fact, one of my main
motivations for writing "Core Python Programming" was because when i
learned Python 13 years ago, the online docs were enough to get me
started but did not have enough info to help me become an intermediate
Python programmer. there were only *2*(!) Python books out there, and
they were special-topic oriented, not ones to learn the language from.
it took almost a year and a half to write, but from what i hear from
readers and what has been said in reviews, it's pretty comprehensive,
and is a good book to learn Python from. i only wish that *i* had it
when i was learning!

Most "Python experts" do not have the entire language memorized, so
everyone has to look at the docs from time-to-time, not just
beginners. i'll either hit up http://docs.python.org/library/MODULE.html
or flip open my Nutshell or PER references, and finally, i'll google
if i have to (rare). the Python docs are the language manuals and not
necessarily full reference texts, so you have to just take them for
what they are.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


From martin at v.loewis.de  Thu Aug  6 15:14:41 2009
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Thu, 06 Aug 2009 21:14:41 +0200
Subject: Character encoding & the copyright symbol
In-Reply-To: 
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>		
	
Message-ID: <4A7B2BA1.2020002@v.loewis.de>

> As a side note, you should probably use something other than "file" for
> the parameter name in GetFileContentsAsString() since file() is a Python
> function.

Python 3.1.1a0 (py3k:74094, Jul 19 2009, 13:39:42)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
py> file
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'file' is not defined

Regards,
Martin



From piet at cs.uu.nl  Thu Aug  6 15:17:16 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Thu, 06 Aug 2009 21:17:16 +0200
Subject: Web page data and urllib2.urlopen
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
	
Message-ID: 

>>>>> Dave Angel  (DA) wrote:

>DA> Massi wrote:
>>> Hi everyone, I'm using the urllib2 library to get the html source code
>>> of web pages. In general it works great, but I'm having to do with a
>>> financial web site which does not provide the souce code I expect. As
>>> a matter of fact if you try:
>>> 
>>> import urllib2
>>> res = urllib2.urlopen("http://www.marketwatch.com/story/mondays-
>>> biggest-gaining-and-declining-stocks-2009-07-27")
>>> page = res.read()
>>> print page
>>> 
>>> you will see that the printed code is very different from the one
>>> given, for example, by mozilla. Since I have really little knowledge
>>> in html I can't even understand if this is a python or html problem.
>>> Can anyone give me some help?
>>> Thanks in advance.
>>> 
>>> 
>DA> I don't think this is a Python issue, but a "raw read" versus an
>DA> interactive interpretation of a page.  The browser does lots more than a
>DA> single roundtrip defined by urlopen/read.

>DA> I also would love to see some explanation of what happens here, or a
>DA> pointer to a reference that would help me understand it.

>DA> I took the output of the read(), and formatted it, roughly, as html.  I
>DA> expected to find a refresh, which is the simplest way that one page can
>DA> cause a very different one to be loaded.
>DA>      

>DA> If Mozilla had seen a page with this line in an appropriate place, it'd
>DA> immediately begin loading the other page, at "someotherurl"  But there's no
>DA> such line.

>DA> Next, I looked for javascript.  The Mozilla page contains lots of
>DA> javascript, but there's none in the raw page.  So I can't explain Mozilla's
>DA> differences that way.

>DA> I did notice the link to /m/Content/mobile2.css, but I don' t know any way
>DA> a CSS file could cause the content to change, just the display.

>DA> All I can guess is that it has something to do with "browser type" or
>DA> cookies.  And that would make lots of sense if this was a cgi page.  But
>DA> the URL doesn't look like that, as it doesn't end in pl, py, asp, or any of
>DA> another dozen special suffixes.

>DA> Any hints, anybody???

If you look into the HTML that Firefox gets, there is a lot of
javascript in it.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From steve at REMOVE-THIS-cybersource.com.au  Thu Aug  6 15:17:30 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 06 Aug 2009 19:17:30 GMT
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
Message-ID: <028b1ce0$0$5185$c3e8da3@news.astraweb.com>

On Thu, 06 Aug 2009 20:05:52 +0200, Thorsten Kampe wrote:

> > That is significant! So the winner is:
> > 
> > unicode('???????','utf-8')
> 
> Unless you are planning to write a loop that decodes "???????" one
> million times, these benchmarks are meaningless.

What if you're writing a loop which takes one million different lines of 
text and decodes them once each?


>>> setup = 'L = ["abc"*(n%100) for n in xrange(1000000)]'
>>> t1 = timeit.Timer('for line in L: line.decode("utf-8")', setup)
>>> t2 = timeit.Timer('for line in L: unicode(line, "utf-8")', setup)
>>> t1.timeit(number=1)
5.6751680374145508
>>> t2.timeit(number=1)
2.6822888851165771


Seems like a pretty meaningful difference to me.



-- 
Steven


From philip at semanchuk.com  Thu Aug  6 15:20:48 2009
From: philip at semanchuk.com (Philip Semanchuk)
Date: Thu, 6 Aug 2009 15:20:48 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: <4A7B2BA1.2020002@v.loewis.de>
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>		
	
	<4A7B2BA1.2020002@v.loewis.de>
Message-ID: <45B3614D-01A3-4CC2-BB78-5B488BC74841@semanchuk.com>


On Aug 6, 2009, at 3:14 PM, Martin v. L?wis wrote:

>> As a side note, you should probably use something other than "file"  
>> for
>> the parameter name in GetFileContentsAsString() since file() is a  
>> Python
>> function.
>
> Python 3.1.1a0 (py3k:74094, Jul 19 2009, 13:39:42)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> py> file
> Traceback (most recent call last):
>  File "", line 1, in 
> NameError: name 'file' is not defined


Whooops, didn't know about that change from 2.x to 3.x. Thanks.



From joncle at googlemail.com  Thu Aug  6 15:38:48 2009
From: joncle at googlemail.com (Jon Clements)
Date: Thu, 6 Aug 2009 12:38:48 -0700 (PDT)
Subject: pylucene installation problem on Ubuntu 9.04
References: 
Message-ID: 

On 6 Aug, 19:49, KK  wrote:
> hi all,
> I've trying to install pylucene on my linux box from last 2 days but
> not able to do so. first i tried to install it using apt-get like
> this,
> kk-laptop$ sudo apt-get install pylucene
> and it did install python2.5, python2.5-minimal and pylucene. I must
> mention one thing that I already had python2.6 on my box as the
> default python i.e /usr/bin/python is linked to python2.6. Anyway s,
> now i started the python interpreter using "python" command from cli
> and then to make sure pylucene has been installed i tried to import
> the module and to my surprise it said "module pylucene not found".
> I thought I should enter the python2.6 env and do the same , so i
> tried starting the python2.6 interpreter using "python2.6" as the
> command and tried importing the same module and again it failed giving
> the same irritating message.
> ?As a final try i pulled the source code of pylucene and as per the
> comments given there in the README file, copied the mentioned files to
> site-packages directory of python2.6 and then tried importing the
> module and then got the same error message saying no module name
> pylucene is present. I'm sick of this error !
> Can someone point me what is the issue? If it is due to multiple
> version of python running on box, can someone tell me which one to
> remove or someone tell me how to get the whole thing running? I'll
> very much thankful to you guys.
>
> Thanks,
> KK.

If you installed using apt, have you a pylucene directory under /usr/
local/lib/python2.6/dist-packages/?

Also, if you run python, and import sys; print sys.path
whats it show?

Jon.


From benjamin.kaplan at case.edu  Thu Aug  6 15:48:27 2009
From: benjamin.kaplan at case.edu (Benjamin Kaplan)
Date: Thu, 6 Aug 2009 15:48:27 -0400
Subject: pylucene installation problem on Ubuntu 9.04
In-Reply-To: 
References: 
Message-ID: 

On Thu, Aug 6, 2009 at 2:49 PM, KK wrote:
>
> kk-laptop$ sudo apt-get install pylucene
> and it did install python2.5, python2.5-minimal and pylucene. I must
> mention one thing that I already had python2.6 on my box as the
> default python i.e /usr/bin/python is linked to python2.6. Anyway s,
> now i started the python interpreter using "python" command from cli
> and then to make sure pylucene has been installed i tried to import
> the module and to my surprise it said "module pylucene not found".
> I thought I should enter the python2.6 env and do the same , so i
> tried starting the python2.6 interpreter using "python2.6" as the
> command and tried importing the same module and again it failed giving
> the same irritating message.

Pylucene seems to have installed under Python 2.5. Python extensions
are only installed for one version of python and extensions that use C
may only work under one particular version. If you want to use that
package, run python2.5 from the command line and try importing it.


From benjamin.kaplan at case.edu  Thu Aug  6 15:54:26 2009
From: benjamin.kaplan at case.edu (Benjamin Kaplan)
Date: Thu, 6 Aug 2009 15:54:26 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: 
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
	
	
Message-ID: 

On Thu, Aug 6, 2009 at 12:41 PM, Robert Dailey wrote:
> On Aug 6, 11:31?am, "Richard Brodie"  wrote:
>> "Robert Dailey"  wrote in message
>>
>> news:29ab0981-b95d-4435-91bd-a7a520419ada at b15g2000yqd.googlegroups.com...
>>
>> > UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
>> > position 1650: character maps to 
>>
>> > The file is defined as ASCII.
>>
>> That's the problem: ASCII is a seven bit code. What you have is
>> actually ISO-8859-1 (or possibly Windows-1252).
>>
>> The different ISO-8859-n variants assign various characters to
>> to '\xa9'. Rather than being Western-European centric and assuming
>> ISO-8859-1 by default, Python throws an error when you stray
>> outside of strict ASCII.
>
> Thanks for the help guys. Sorry I left out code, I wasn't sure at the
> time if it would be helpful. Below is my code:
>
>
> #========================================================
> def GetFileContentsAsString( file ):
> ? f = open( file, mode='r', encoding='cp1252' )
> ? contents = f.read()
> ? f.close()
> ? return contents
>
> #========================================================
> def ReplaceVersion( file, version, regExps ):
> ? #match = regExps[0].search( 'FILEVERSION 1,45332,2100,32,' )
> ? #print( match.group() )
> ? text = GetFileContentsAsString( file )
> ? print( text )
>
>
> As you can see, I am trying to load the file with encoding 'cp1252'
> which, according to the python 3.1 docs, translates to windows-1252. I
> also tried 'latin_1', which translates to ISO-8859-1, but this did not
> work either. Am I doing something else wrong?

This is why we need code and full tracebacks. There's a good chance
that your error is on the print(text) line. That's because sys.stdout
is probably a byte stream without an encoding defined. When you try to
print your unicode string, Python has to convert it to a stream of
bytes. Python refuses to guess on the console encoding and just falls
back to ascii, the conversion fails, and you get your error. Try using
print( text.encode( 'cp1252' ) ) instead.
> --
> http://mail.python.org/mailman/listinfo/python-list
>


From aahz at pythoncraft.com  Thu Aug  6 15:55:57 2009
From: aahz at pythoncraft.com (Aahz)
Date: 6 Aug 2009 12:55:57 -0700
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com>
	
Message-ID: 

In article ,
Hendrik van Rooyen   wrote:
>
>Bit slow - but hey, nobody's perfect.

YM "pobody's nerfect" HTH HAND
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"...string iteration isn't about treating strings as sequences of strings, 
it's about treating strings as sequences of characters.  The fact that
characters are also strings is the reason we have problems, but characters 
are strings for other good reasons."  --Aahz


From aahz at pythoncraft.com  Thu Aug  6 16:16:33 2009
From: aahz at pythoncraft.com (Aahz)
Date: 6 Aug 2009 13:16:33 -0700
Subject: How to write replace string for object which will be substituted?
	[regexp]
References: 
	
Message-ID: 

In article ,
ryniek90   wrote:
>
>I started learning regexp, and some things goes well, but most of them 
>still not.

1) 'Some people, when confronted with a problem, think "I know, I'll use
regular expressions."  Now they have two problems.'
--Jamie Zawinski, comp.emacs.xemacs, 8/1997

2) If you really want to learn regexes, get a copy of _Mastering Regular
Expressions_ by Friedl (either 2nd or 3rd edition)
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"...string iteration isn't about treating strings as sequences of strings, 
it's about treating strings as sequences of characters.  The fact that
characters are also strings is the reason we have problems, but characters 
are strings for other good reasons."  --Aahz


From kosta.koeman at gmail.com  Thu Aug  6 16:19:31 2009
From: kosta.koeman at gmail.com (Kosta)
Date: Thu, 6 Aug 2009 13:19:31 -0700 (PDT)
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> 
	
	
	
	<1a236d86-72de-4b43-bc7b-cf0c9bdab615@u38g2000pro.googlegroups.com>
	
Message-ID: <4703dc01-a41a-4bcd-b225-9ef819105144@a39g2000pre.googlegroups.com>

On Aug 6, 11:58?am, Piet van Oostrum  wrote:
> >>>>> Kosta  (K) wrote:
> >K> My interpretation of the above (and your email) is that using Popen
> >K> allows one to pass the Python environment to a child processs (in my
> >K> case, setenv.bat). ? I need the reverse, to propagate from the child
> >K> to the parent.
>
> I don't think there is any modern OS that allows that. Unless you use
> your own protocol of course, like letting the child write the
> environment to its stdout and reading and interpreting it in the parent.
> --
> Piet van Oostrum 
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: p... at vanoostrum.org

Piet,

Yes you are correct.  Thinking more about parent/child processes and
what I am doing: opening a cmd window (its own process), starting up
Python (a child process), and then attempting to run setenv.bat (a
child process to Python), and yes I'm out of luck.


From davea at ieee.org  Thu Aug  6 16:26:11 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 16:26:11 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
Message-ID: <4A7B3C63.2050307@ieee.org>

Robert Dailey wrote:
> Hello,
>
> I'm loading a file via open() in Python 3.1 and I'm getting the
> following error when I try to print the contents of the file that I
> obtained through a call to read():
>
> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> position 1650: character maps to 
>
> The file is defined as ASCII and the copyright symbol shows up just
> fine in Notepad++. However, Python will not print this symbol. How can
> I get this to work? And no, I won't replace it with "(c)". Thanks!
>
>   
I see others have alerted you to changes needed in stdout, which is 
ASCII coded by default.

But I wanted to comment on the (c) remark.  If you're in the US, that's 
the wrong ab